Module: Lettr::Resource

Included in:
ApiMailing, Delivery
Defined in:
lib/lettr/resource.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



3
4
5
6
7
8
# File 'lib/lettr/resource.rb', line 3

def self.included base
  base.extend ClassMethods
  base.cattr_accessor :path
  base.send(:attr_accessor, :errors)
  base.send(:attr_accessor, :id)
end

Instance Method Details

#attributesObject



61
62
63
64
65
66
67
# File 'lib/lettr/resource.rb', line 61

def attributes
  attributes = {}
  each_pair do |key, value|
    attributes.merge! key => value
  end
  attributes
end

#clientObject



37
38
39
# File 'lib/lettr/resource.rb', line 37

def client
  self.class.client
end

#destroyObject



45
46
47
# File 'lib/lettr/resource.rb', line 45

def destroy
  client.destroy self
end

#initialize(*args) ⇒ Object



24
25
26
# File 'lib/lettr/resource.rb', line 24

def initialize *args
  @errors = []
end

#pathObject



57
58
59
# File 'lib/lettr/resource.rb', line 57

def path
  "#{self.class.path}/#{id}"
end

#resource_nameObject



49
50
51
# File 'lib/lettr/resource.rb', line 49

def resource_name
  self.class.to_s.demodulize.underscore
end

#saveObject



28
29
30
31
32
33
34
35
# File 'lib/lettr/resource.rb', line 28

def save
  res = client.save self
  self.id = ActiveSupport::JSON.decode(res)[resource_name]['id'] unless res.blank?
  true
rescue RestClient::UnprocessableEntity => e
  self.errors = ActiveSupport::JSON.decode(e.response)
  false
end

#to_jsonObject



53
54
55
# File 'lib/lettr/resource.rb', line 53

def to_json
  { resource_name => attributes }.to_json
end

#to_payloadObject



41
42
43
# File 'lib/lettr/resource.rb', line 41

def to_payload
  { self.resource_name => self.attributes }
end