Sha256: 1737279c7181330ffcaa16abe5f75785a567c709977b147bfd6e189a3962fe15

Contents?: true

Size: 1008 Bytes

Versions: 1

Compression:

Stored size: 1008 Bytes

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
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
format_parser-0.3.2 lib/attributes_json.rb