Module: Cooler::Model

Defined in:
lib/cooler/model.rb

Overview

Defines the base methods to define a model class.

Defined Under Namespace

Modules: ClassMethods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#_keyObject

The key for the document.

Returns the String key for this document.



144
145
146
# File 'lib/cooler/model.rb', line 144

def _key
  @_key || self.class.key.(self)
end

Class Method Details

.included(base) ⇒ Object

Called after including in some class. For more information, read: www.ruby-doc.org/core-1.9.3/Module.html#method-i-included

Returns nothing.



8
9
10
11
# File 'lib/cooler/model.rb', line 8

def self.included(base)
  base.send :extend, ClassMethods
  base.instance_variable_set :@default_values, {}
end

Instance Method Details

#attributes=(attributes) ⇒ Object

Assigns attributes from the passed Hash. Only setteable attributes will be assigned.

attributes - The Hash with the attributes to assign.

Returns nothing.



154
155
156
157
158
# File 'lib/cooler/model.rb', line 154

def attributes=(attributes)
  return unless Hash === attributes
  attributes = attributes.symbolize_keys
  attributes.each { |k, v| send("#{k}=", v) if respond_to?("#{k}=") }
end

#initialize(*attrs) ⇒ Object

Initialize a Base.

attrs - May contain at the first position, the String key for the

document owner of the instance. Then it a Hash with its
attributes (default: {}).


135
136
137
138
139
# File 'lib/cooler/model.rb', line 135

def initialize(*attrs)
  @_key = attrs.shift if String === attrs.first
  self.attributes = attrs.shift || {}
  set_default_values
end

#saveObject

Saves persisted attributes to the database.

Returns true if saved, false if not.



173
174
175
176
# File 'lib/cooler/model.rb', line 173

def save
  Cooler::Adapter.set.(_key, serializable_hash)
  !Cooler::Adapter.get.(_key).nil?
end

#save!Object

Saves persisted attributes to the database. Raises an exception if not able to save it.

Returns nothing. Raises Cooler::InvalidObject if not able to save it.



183
184
185
# File 'lib/cooler/model.rb', line 183

def save!
  raise Cooler::InvalidObject unless save
end

#serializable_hashObject

Provides basic serialization of the instance, it includes only its Struct attributes, and not those defined from attr_accessor.

Returns the serialized Hash.



164
165
166
167
168
# File 'lib/cooler/model.rb', line 164

def serializable_hash
  hash = {}
  each_pair { |key, value| hash[key] = value }
  hash
end