Method: Mbrao::PublicInterface::ClassMethods#as_json

Defined in:
lib/mbrao/parser.rb

#as_json(target, keys, options = {}) ⇒ Hash

Returns an object as a JSON compatible hash

Parameters:

  • target (Object)

    The target to serialize.

  • keys (Array)

    The attributes to include in the serialization

  • options (Hash) (defaults to: {})

    Options to modify behavior of the serialization. The only supported value are:

    • :exclude, an array of attributes to skip.
    • :exclude_empty, if to exclude nil values. Default is false.

Returns:

  • (Hash)

    An hash with all attributes.



76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/mbrao/parser.rb', line 76

def as_json(target, keys, options = {})
  include_empty = !options[:exclude_empty].to_boolean
  exclude = options[:exclude].ensure_array(nil, true, true, true, :ensure_string)
  keys = keys.ensure_array(nil, true, true, true, :ensure_string)

  (keys - exclude).reduce({}) {|rv, key|
    value = target.send(key)
    value = value.as_json if value && value.respond_to?(:as_json)
    rv[key] = value if include_empty || !value.is_a?(NilClass)
    rv
  }.deep_stringify_keys
end