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, &block) ⇒ Formatter

Initializes a new Formatter.

Parameters:

  • attrs (Array)

    the attributes to format

  • attr_options (Hash)

    the options for the attributes



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

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

  instance_eval(&block)
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 ? service.instance_exec(obj, &formatter) : service.try(method)
    validate!(method, value)

    [ method, value ]
  end].compact
end