Class: CollectionJSON::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/collection-json/attribute.rb

Direct Known Subclasses

Collection, Data, Error, Item, Link, Query, Template

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.attribute(name, opts = {}) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/collection-json/attribute.rb', line 13

def self.attribute(name, opts={})
  nested_attributes << name
  define_method(name) do |arg=nil|
    if arg
      if opts[:transform]
        instance_variable_set(:"@#{name}", opts[:transform].call(arg))
      else
        instance_variable_set(:"@#{name}", arg)
      end
    else
      unless instance_variable_get(:"@#{name}").nil?
         instance_variable_get(:"@#{name}")
       else
        opts[:default]
      end
    end
  end
end

.from_hash(hash) ⇒ Object



37
38
39
40
41
# File 'lib/collection-json/attribute.rb', line 37

def self.from_hash(hash)
  self.new.tap do |item|
    hash.each { |k,v| item.send(k, v) if item.respond_to?(k) }
  end
end

.nested_attributesObject



9
10
11
# File 'lib/collection-json/attribute.rb', line 9

def self.nested_attributes
  @nested_attributes ||= []
end

.root_node(value = nil) ⇒ Object



32
33
34
35
# File 'lib/collection-json/attribute.rb', line 32

def self.root_node(value = nil)
  @root_node = value.to_s if value
  @root_node
end

Instance Method Details

#to_hashObject



43
44
45
46
47
48
49
50
51
# File 'lib/collection-json/attribute.rb', line 43

def to_hash
  hash = Hash.new.tap do |item|
    self.class.nested_attributes.each do |attribute|
      value = send(attribute)
      item[attribute] = value unless skip_value?(value)
    end
  end
  self.class.root_node ? {self.class.root_node => hash} : hash
end

#to_json(*args) ⇒ Object



53
54
55
# File 'lib/collection-json/attribute.rb', line 53

def to_json(*args)
  to_hash.to_json(args)
end