Class: Compass::JsonFormatter::Formatter

Inherits:
Object
  • Object
show all
Defined in:
lib/compass/json_formatter.rb

Overview

Formats an object into a JSON hash.

Instance Method Summary collapse

Constructor Details

#initialize(attrs, attr_options) ⇒ Formatter

Initializes a new Formatter.

Parameters:

  • attrs (Array)

    the attributes to format

  • attr_options (Hash)

    the options for the attributes



68
69
70
71
72
73
74
75
76
# File 'lib/compass/json_formatter.rb', line 68

def initialize(attrs, attr_options)
  @attrs = attrs.index_with { nil }
  @attr_options = attr_options
  attrs.each do |attr|
    define_singleton_method(attr) do |&block|
      @attrs[attr] = block
    end
  end
end

Instance Method Details

#to_h(service, obj) ⇒ Hash

Formats an object into a ruby hash.

Parameters:

  • service (Object)

    the service requesting the formatting of obj

  • obj (Object)

    the object to format

Returns:

  • (Hash)

    the formatted hash



82
83
84
85
86
87
88
89
# File 'lib/compass/json_formatter.rb', line 82

def to_h(service, obj)
  Hash[@attrs.map do |method, formatter|
    value = formatter ? formatter.call(obj) : service.try(method)
    validate!(method, value)

    [ method, value ]
  end].compact
end