Class: Code42::Resource

Inherits:
Object
  • Object
show all
Defined in:
lib/code42/resource.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = {}, client = nil) ⇒ Resource

Returns a new instance of Resource.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/code42/resource.rb', line 40

def initialize(data = {}, client = nil)
  self.client = client || Code42.client
  self.attributes = {}
  data.each do |key, value|
    unless self.respond_to?("#{key}=".to_sym)
      self.class.instance_eval { attr_writer key.to_sym }
    end
    unless self.respond_to?("#{key}".to_sym)
      self.class.instance_eval { attr_reader key.to_sym }
    end
    self.send("#{key}=", value)
    attributes[key.to_sym] = self.send(key.to_sym)
  end
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



38
39
40
# File 'lib/code42/resource.rb', line 38

def attributes
  @attributes
end

#clientObject

Returns the value of attribute client.



38
39
40
# File 'lib/code42/resource.rb', line 38

def client
  @client
end

Class Method Details

.attribute(*args) ⇒ Object



26
27
28
29
30
31
# File 'lib/code42/resource.rb', line 26

def attribute(*args)
  options = args.extract_options!
  args.each do |name|
    serializer << Attribute.new(name, options)
  end
end

.collection_from_response(array) ⇒ Object



33
34
35
# File 'lib/code42/resource.rb', line 33

def collection_from_response(array)
  (array || []).map { |element| self.deserialize_and_initialize(element, self) }
end

.deserialize(data) ⇒ Object



18
19
20
# File 'lib/code42/resource.rb', line 18

def deserialize(data)
  data.inject({}) { |o, ary| o.merge! serializer.deserialize(*ary) }
end

.deserialize_and_initialize(data, client = nil) ⇒ Object



10
11
12
# File 'lib/code42/resource.rb', line 10

def deserialize_and_initialize(data, client = nil)
  new deserialize(data), client
end

.from_response(response, client = nil) ⇒ Object



6
7
8
# File 'lib/code42/resource.rb', line 6

def from_response(response, client = nil)
  deserialize_and_initialize(response, client)
end

.serialize(data) ⇒ Object



14
15
16
# File 'lib/code42/resource.rb', line 14

def serialize(data)
  data.inject({}) { |o, ary| o.merge! serializer.serialize(*ary) }
end

.serializerObject



22
23
24
# File 'lib/code42/resource.rb', line 22

def serializer
  @serializer ||= Code42::AttributeSerializer.new
end

Instance Method Details

#serializeObject



55
56
57
# File 'lib/code42/resource.rb', line 55

def serialize
  self.class.serialize attributes
end