Module: LightSide::Resources

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



63
64
65
66
# File 'lib/lightside/resources.rb', line 63

def self.included(base)
  base.extend(ClassMethods)
  base.singleton_class.class_eval { attr_accessor :resource_base, :readonly_attributes, :writable_attributes }
end

Instance Method Details

#attributesObject



8
9
10
11
12
# File 'lib/lightside/resources.rb', line 8

def attributes
  self.class.attributes.inject({}) do |memo, attr|
    memo.merge(attr => self.__send__(attr))
  end
end

#deleteObject



14
15
16
# File 'lib/lightside/resources.rb', line 14

def delete
  self.class.delete_resource(id)
end

#idObject



18
19
20
# File 'lib/lightside/resources.rb', line 18

def id
  url && url.split("/").last
end

#initialize(hash = {}) ⇒ Object



4
5
6
# File 'lib/lightside/resources.rb', line 4

def initialize(hash={})
  set_attributes_from_hash(hash)
end

#reloadObject



22
23
24
25
26
27
# File 'lib/lightside/resources.rb', line 22

def reload
  self.class.resource(id) do |hash|
    set_attributes_from_hash(hash)
  end
  self
end

#saveObject



33
34
35
36
37
38
39
40
41
# File 'lib/lightside/resources.rb', line 33

def save
  json = JSON.generate(writable_attributes)
  if id
    self.class.update_resource(id, json) { |hash| set_attributes_from_hash(hash) }
  else
    self.class.create_resource(json) { |hash| set_attributes_from_hash(hash) }
  end
  self
end

#set_attributes_from_hash(hash) ⇒ Object



43
44
45
46
47
# File 'lib/lightside/resources.rb', line 43

def set_attributes_from_hash(hash)
  self.class.attributes.each do |attr|
    self.__send__("#{attr.to_s}=", hash.fetch(attr, nil))
  end
end

#to_sObject



49
50
51
52
53
54
55
# File 'lib/lightside/resources.rb', line 49

def to_s
  %w(id url errors).map(&:to_sym).inject("#{self.class.name}") do |memo, attr|
    val = self.__send__(attr)
    memo << " #{attr}:#{val}" if val
    memo
  end
end

#updateObject



29
30
31
# File 'lib/lightside/resources.rb', line 29

def update
  save
end

#writable_attributesObject



57
58
59
60
61
# File 'lib/lightside/resources.rb', line 57

def writable_attributes
  self.class.writable_attributes.inject({}) do |memo, attr|
    memo.merge(attr => self.__send__(attr))
  end
end