Module: Wakame::StatusDB::Model::ClassMethods

Defined in:
lib/wakame/status_db.rb

Instance Method Summary collapse

Instance Method Details

#_instance_cacheObject



172
173
174
175
176
# File 'lib/wakame/status_db.rb', line 172

def _instance_cache
  return {} unless @enable_cache

  @_instance_cache ||= {}
end

#delete(id) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/wakame/status_db.rb', line 242

def delete(id)
  obj = find(id)
  if obj
    obj.on_before_delete
    StatusDB.barrier {
      StatusDB.adapter.delete(id)
    }
    _instance_cache.delete(id)

    obj.on_after_delete 
  end
end

#disable_cacheObject



165
166
167
168
169
170
# File 'lib/wakame/status_db.rb', line 165

def disable_cache
  if @enable_cache
    @enable_cache = false
    @_instance_cache = {}
  end
end

#enable_cacheObject



158
159
160
161
162
163
# File 'lib/wakame/status_db.rb', line 158

def enable_cache
  unless @enable_cache
    @enable_cache = true
    @_instance_cache = {}
  end
end

#exists?(id) ⇒ Boolean

Returns:

  • (Boolean)


225
226
227
228
229
# File 'lib/wakame/status_db.rb', line 225

def exists?(id) 
  StatusDB.barrier {
    _instance_cache.has_key?(id) || StatusDB.adapter.exists?(id)
  }
end

#find(id) ⇒ Object



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/wakame/status_db.rb', line 178

def find(id)
  raise "Can not retrieve the data with nil." if id.nil?
  obj = _instance_cache[id]
  return obj unless obj.nil?

  hash = StatusDB.barrier {
    StatusDB.adapter.find(id)
  }
  return nil unless hash

  if hash[AttributeHelper::CLASS_TYPE_KEY]
    klass_const = Util.build_const(hash[AttributeHelper::CLASS_TYPE_KEY])
  else
    klass_const = self
  end
  
  # klass_const class is equal to self class or child of self class
  if klass_const <= self
    obj = klass_const.new
  else
    raise "Can not instanciate the object #{klass_const.to_s} from #{self}"
  end
  
  obj.on_before_load
  
  obj.instance_variable_set(:@id, id)
  obj.instance_variable_set(:@load_at, Time.now)
  
  hash.each { |k,v|
    obj.instance_variable_set("@#{k}", v)
  }
  
  obj.on_after_load

  _instance_cache[id] = obj
  obj
end

#find_allObject



217
218
219
220
221
222
223
# File 'lib/wakame/status_db.rb', line 217

def find_all
  StatusDB.barrier {
    StatusDB.adapter.find_all(self.to_s).map { |id|
      find(id)
    }
  }
end

#property(key, opts = {}) ⇒ Object

A helper method to define an accessor with persistent flag.



232
233
234
235
236
237
238
239
240
# File 'lib/wakame/status_db.rb', line 232

def property(key, opts={})
  case opts 
  when Hash
    opts.merge!({:persistent=>true})
  else
    opts = {:persistent=>true}
  end
  def_attribute(key.to_sym, opts)
end