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

Defined in:
lib/wakame/status_db.rb

Instance Method Summary collapse

Instance Method Details

#_instance_cacheObject



206
207
208
209
210
# File 'lib/wakame/status_db.rb', line 206

def _instance_cache
  return {} unless @enable_cache

  @_instance_cache ||= {}
end

#delete(id) ⇒ Object



270
271
272
273
274
275
276
277
278
279
280
# File 'lib/wakame/status_db.rb', line 270

def delete(id)
  obj = find(id)
  if obj
    obj.on_before_delete

    StatusDB.adapter.delete(id)
    _instance_cache.delete(id)

    obj.on_after_delete 
  end
end

#disable_cacheObject



199
200
201
202
203
204
# File 'lib/wakame/status_db.rb', line 199

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

#enable_cacheObject



192
193
194
195
196
197
# File 'lib/wakame/status_db.rb', line 192

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

#exists?(id) ⇒ Boolean

Returns:

  • (Boolean)


255
256
257
# File 'lib/wakame/status_db.rb', line 255

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

#find(id) ⇒ Object



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/wakame/status_db.rb', line 212

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

  StatusDB.adapter.find(id) { |id, hash|
    if hash[AttributeHelper::CLASS_TYPE_KEY]
      klass_const = Util.build_const(hash[AttributeHelper::CLASS_TYPE_KEY])
    else
      klass_const = self.class
    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(:@_orig, hash.dup.freeze)
    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



249
250
251
252
253
# File 'lib/wakame/status_db.rb', line 249

def find_all
  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.



260
261
262
263
264
265
266
267
268
# File 'lib/wakame/status_db.rb', line 260

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