Module: Loco::Savable

Included in:
Model
Defined in:
lib/motion-loco/savable.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



119
120
121
# File 'lib/motion-loco/savable.rb', line 119

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#destroy(&block) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'lib/motion-loco/savable.rb', line 8

def destroy(&block)
  adapter = self.class.get_class_adapter
  unless self.id.nil?
    adapter.delete_record(self) do |record|
      self.did_delete
      block.call(record) if block.is_a? Proc
    end
  end
end

#did_createObject Also known as: didCreate



18
19
20
# File 'lib/motion-loco/savable.rb', line 18

def did_create
  # Override to perform actions after creating the record
end

#did_loadObject Also known as: didLoad



23
24
25
# File 'lib/motion-loco/savable.rb', line 23

def did_load
  # Override to perform actions after loading data
end

#did_updateObject Also known as: didUpdate



28
29
30
# File 'lib/motion-loco/savable.rb', line 28

def did_update
  # Override to perform actions after updating the record
end

#load(id, data) ⇒ Object



33
34
35
36
37
38
# File 'lib/motion-loco/savable.rb', line 33

def load(id, data)
  data.merge!({ id: id })
  self.set_properties(data)
  self.did_load
  self
end

#save(&block) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/motion-loco/savable.rb', line 40

def save(&block)
  adapter = self.class.get_class_adapter
  if self.id.nil?
    adapter.create_record(self) do |record|
      self.did_create
      block.call(record) if block.is_a? Proc
    end
  else
    adapter.update_record(self) do |record|
      self.did_update
      block.call(record) if block.is_a? Proc
    end
  end
end

#serialize(options = {}) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/motion-loco/savable.rb', line 55

def serialize(options={})
  json = {}
  if options[:root] == false
    self.class.send(:get_class_properties).each do |key|
      json[key.to_sym] = self.send(key)
    end
  else
    if options[:root].nil? || options[:root] == true
      root = self.class.to_s.underscore.to_sym
    else
      root = options[:root].to_sym
    end
    json[root] = {}
    self.class.send(:get_class_properties).each do |key|
      json[root][key.to_sym] = self.send(key)
    end
  end
  json
end