Module: Toy::Persistence

Extended by:
ActiveSupport::Concern
Included in:
DirtyStore, Store
Defined in:
lib/toy/persistence.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#adapterObject



44
45
46
# File 'lib/toy/persistence.rb', line 44

def adapter
  self.class.adapter
end

#deleteObject



91
92
93
94
# File 'lib/toy/persistence.rb', line 91

def delete
  @_destroyed = true
  adapter.delete(persisted_id)
end

#destroyObject



87
88
89
# File 'lib/toy/persistence.rb', line 87

def destroy
  delete
end

#destroyed?Boolean

Returns:



70
71
72
# File 'lib/toy/persistence.rb', line 70

def destroyed?
  @_destroyed == true
end

#initialize(attrs = {}) ⇒ Object



48
49
50
51
# File 'lib/toy/persistence.rb', line 48

def initialize(attrs={})
  @_new_record = true
  super
end

#initialize_copy(other) ⇒ Object



60
61
62
63
64
# File 'lib/toy/persistence.rb', line 60

def initialize_copy(other)
  super
  @_new_record = true
  @_destroyed  = false
end

#initialize_from_database(attrs = {}) ⇒ Object



53
54
55
56
57
58
# File 'lib/toy/persistence.rb', line 53

def initialize_from_database(attrs={})
  @_new_record = false
  initialize_attributes
  send("attributes=", attrs, false)
  self
end

#new_record?Boolean

Returns:



66
67
68
# File 'lib/toy/persistence.rb', line 66

def new_record?
  @_new_record == true
end

#persistObject

Public: Choke point for overriding how data gets written.



116
117
118
# File 'lib/toy/persistence.rb', line 116

def persist
  adapter.write(persisted_id, persisted_attributes)
end

#persisted?Boolean

Returns:



74
75
76
# File 'lib/toy/persistence.rb', line 74

def persisted?
  !new_record? && !destroyed?
end

#persisted_attributesObject

Public: Choke point for overriding what attributes get stored.



105
106
107
108
109
110
111
112
113
# File 'lib/toy/persistence.rb', line 105

def persisted_attributes
  attributes = {}
  self.class.persisted_attributes.each do |attribute|
    if (value = attribute.to_store(read_attribute(attribute.name)))
      attributes[attribute.persisted_name] = value
    end
  end
  attributes
end

#persisted_idObject

Public: Choke point for overriding what id is used to write and delete.



97
98
99
100
101
102
# File 'lib/toy/persistence.rb', line 97

def persisted_id
  attribute_name = 'id'
  attribute = attribute_instance(attribute_name)
  attribute_value = read_attribute(attribute_name)
  attribute.to_store(attribute_value)
end

#saveObject



78
79
80
# File 'lib/toy/persistence.rb', line 78

def save(*)
  new_record? ? create : update
end

#update_attributes(attrs) ⇒ Object



82
83
84
85
# File 'lib/toy/persistence.rb', line 82

def update_attributes(attrs)
  self.attributes = attrs
  save
end