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
31
# File 'lib/collection-json/attribute.rb', line 13

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

.from_hash(hash) ⇒ Object



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

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



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

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

Instance Method Details

#to_hashObject



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

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



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

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