Class: Rev::ApiSerializable

Inherits:
Object
  • Object
show all
Defined in:
lib/rev-api/api_serializable.rb

Overview

Utility class with instance methods for hash/JSON conversion

Instance Method Summary collapse

Constructor Details

#initialize(fields = {}) ⇒ ApiSerializable

Map given hash to instance properties

Parameters:

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

    of fields to initialize instance. See instance attributes for available fields.



8
9
10
# File 'lib/rev-api/api_serializable.rb', line 8

def initialize(fields = {})
  fields.each { |k,v| self.instance_variable_set("@#{k.to_sym}", v) if self.methods.include? k.to_sym }
end

Instance Method Details

#to_hashHash

Returns:

  • (Hash)

    hash map of the object including all nested children



16
17
18
19
20
21
22
23
# File 'lib/rev-api/api_serializable.rb', line 16

def to_hash
  h = {}
  instance_variables.each do |e|
    o = instance_variable_get e.to_sym
    h[e[1..-1]] = (o.respond_to? :to_hash) ? o.to_hash : o;
  end
  h
end

#to_json(*args) ⇒ Object

Recursively convert object to JSON (internally utilizing hash)



26
27
28
# File 'lib/rev-api/api_serializable.rb', line 26

def to_json *args
  to_hash.to_json *args
end