Class: HashSerializer::JSON

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/hash_serializer/json.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ JSON

Returns a new instance of JSON.



8
9
10
# File 'lib/hash_serializer/json.rb', line 8

def initialize(hash)
  @__hash__ = hash
end

Class Method Details

.attributesObject



19
20
21
# File 'lib/hash_serializer/json.rb', line 19

def attributes
  @attributes
end

.default_attribute_optionsObject



23
24
25
# File 'lib/hash_serializer/json.rb', line 23

def default_attribute_options
  @default_attribute_options || {}
end

.format(format_name, &formatter) ⇒ Object



37
38
39
40
# File 'lib/hash_serializer/json.rb', line 37

def format(format_name, &formatter)
  @formats ||= {}
  @formats[format_name] = formatter
end

.formatsObject



27
28
29
# File 'lib/hash_serializer/json.rb', line 27

def formats
  @formats
end

.reveal(*attrs, as: nil, format: nil) ⇒ Object



13
14
15
16
17
# File 'lib/hash_serializer/json.rb', line 13

def reveal(*attrs, as: nil, format: nil)
  @attributes ||= []
  attribute_options = {as: as, format: format}.merge(default_attribute_options)
  @attributes.push(*attrs.map {|name| HashSerializer::Attribute.new(name, attribute_options)})
end

.with_format(format_name) ⇒ Object



31
32
33
34
35
# File 'lib/hash_serializer/json.rb', line 31

def with_format(format_name)
  @default_attribute_options = { format: format_name }
  yield
  @default_attribute_options = nil
end

Instance Method Details

#as_jsonObject



43
44
45
46
47
48
# File 'lib/hash_serializer/json.rb', line 43

def as_json
  hash_to_object!
  attributes.inject({}) do |memo, attribute|
    memo.merge(attribute.as_json(self))
  end
end

#formatsObject



54
55
56
# File 'lib/hash_serializer/json.rb', line 54

def formats
  self.class.formats
end

#to_jsonObject



50
51
52
# File 'lib/hash_serializer/json.rb', line 50

def to_json
  ::JSON.generate(as_json)
end