Class: Rack::JSON::Document

Inherits:
Object
  • Object
show all
Defined in:
lib/rackjson/document.rb

Direct Known Subclasses

JSONDocument, MongoDocument

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



4
5
6
# File 'lib/rackjson/document.rb', line 4

def attributes
  @attributes
end

Class Method Details

.create(doc) ⇒ Object



6
7
8
9
10
11
12
13
14
# File 'lib/rackjson/document.rb', line 6

def self.create(doc)
  if doc.is_a? String
    Rack::JSON::JSONDocument.new(doc)
  elsif doc.is_a? BSON::OrderedHash
    Rack::JSON::MongoDocument.new(doc)
  else
    raise Rack::JSON::DocumentFormatError
  end
end

Instance Method Details

#add_attributes(pair) ⇒ Object



16
17
18
# File 'lib/rackjson/document.rb', line 16

def add_attributes(pair)
  attributes.merge!(pair)
end

#field(field_names) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/rackjson/document.rb', line 20

def field(field_names)
  attrs = attributes
  Array.wrap(field_names).each do |field_name|
    if attrs.is_a? Array
      attrs = attrs[field_name.to_i]
    else
      attrs = attrs[field_name]
    end
  end
  attrs
end

#set_id(val) ⇒ Object



32
33
34
# File 'lib/rackjson/document.rb', line 32

def set_id(val)
  add_attributes('_id' => val) unless attributes.keys.include? '_id'
end

#to_hObject



36
37
38
# File 'lib/rackjson/document.rb', line 36

def to_h
  attributes
end

#to_json(options = {}) ⇒ Object



40
41
42
# File 'lib/rackjson/document.rb', line 40

def to_json(options={})
  attributes.to_json
end