class HashSerializer::JSON

Public Class Methods

attributes() click to toggle source
# File lib/hash_serializer/json.rb, line 19
def attributes
  @attributes
end
default_attribute_options() click to toggle source
# File lib/hash_serializer/json.rb, line 23
def default_attribute_options
  @default_attribute_options || {}
end
format(format_name, &formatter) click to toggle source
# File lib/hash_serializer/json.rb, line 37
def format(format_name, &formatter)
  @formats ||= {}
  @formats[format_name] = formatter
end
formats() click to toggle source
# File lib/hash_serializer/json.rb, line 27
def formats
  @formats
end
new(hash) click to toggle source
# File lib/hash_serializer/json.rb, line 8
def initialize(hash)
  @__hash__ = hash
end
reveal(*attrs, as: nil, format: nil) click to toggle source
# 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) { || ... } click to toggle source
# 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

Public Instance Methods

as_json() click to toggle source
# 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
formats() click to toggle source
# File lib/hash_serializer/json.rb, line 54
def formats
  self.class.formats
end
to_json() click to toggle source
# File lib/hash_serializer/json.rb, line 50
def to_json
  ::JSON.generate(as_json)
end

Private Instance Methods

attributes() click to toggle source
# File lib/hash_serializer/json.rb, line 60
def attributes
  self.class.attributes
end
hash_to_object!() click to toggle source
# File lib/hash_serializer/json.rb, line 64
def hash_to_object!
  @hash_to_object ||= __setobj__(OpenStruct.new(@__hash__)) || true
end