Sha256: 93a9efbf844743051980b4a034de81595542e0bce6c84e4cf53b07bbe747b586

Contents?: true

Size: 1.16 KB

Versions: 3

Compression:

Stored size: 1.16 KB

Contents

# Implements as_json as returning a Hash
# containing the return values of all the
# reader methods of an object that have
# associated pair writer methods.
#
#   class Foo
#     include AttributesJSON
#     attr_accessor :number_of_bars
#   end
#   the_foo = Foo.new
#   the_foo.number_of_bars = 42
#   the_foo.as_json #=> {:number_of_bars => 42}
module FormatParser::AttributesJSON

  # Implements a sane default `as_json` for an object
  # that accessors defined
  def as_json(*_maybe_root_option)
    h = {}
    h['nature'] = nature if respond_to?(:nature) # Needed for file info structs
    methods.grep(/\w\=$/).each_with_object(h) do |attr_writer_method_name, h|
      reader_method_name = attr_writer_method_name.to_s.gsub(/\=$/, '')
      value = public_send(reader_method_name)
      # When calling as_json on our members there is no need to pass the root: option given to us
      # by the caller
      h[reader_method_name] = value.respond_to?(:as_json) ? value.as_json : value
    end
  end

  # Implements to_json with sane defaults - like
  # support for `JSON.pretty_generate` vs. `JSON.dump`
  def to_json(generator_state)
    generator_state.generate(as_json)
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
format_parser-0.3.5 lib/attributes_json.rb
format_parser-0.3.4 lib/attributes_json.rb
format_parser-0.3.3 lib/attributes_json.rb