Module: Riagent::Document::ClassMethods

Defined in:
lib/riagent/document.rb

Instance Method Summary collapse

Instance Method Details

#from_json(json_obj, key = nil) ⇒ Riagent::Document?

Returns a Riagent::Document instance, given a JSON string

Parameters:

  • json_object (String)

    JSON Object string

  • key (String) (defaults to: nil)

    Optional document key. If not provided, will be loaded from _id attribute in the JSON itself

Returns:

  • (Riagent::Document, nil)

    Riagent::Document instance, or nil if the JSON string is nil/empty



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/riagent/document.rb', line 50

def from_json(json_obj, key=nil)
  return nil if json_obj.nil? or json_obj.empty?
  attributes_hash = JSON.parse(json_obj)
  return nil if attributes_hash.empty?
  instance = self.instantiate(attributes_hash)
  if key.nil?
    # Load key from the JSON object
    key = attributes_hash['_id']
  end
  instance.key = key
  instance
end

#instantiate(attributes) ⇒ Object

Returns Riagent::Document instance, given a Hash of attributes



64
65
66
# File 'lib/riagent/document.rb', line 64

def instantiate(attributes)
  self.new attributes
end