Module: Ampere::Model::ClassMethods

Defined in:
lib/ampere/model.rb

Overview

Class methods

Instance Method Summary collapse

Instance Method Details

#allObject

Returns a lazy collection of all the records that have been stored.



203
204
205
# File 'lib/ampere/model.rb', line 203

def all
  Ampere::Collection.new(self, Ampere.connection.keys("#{to_s.downcase}.*"))
end

#belongs_to(field_name, options = {}) ⇒ Object

Declares a belongs_to relationship to another model.



208
209
210
# File 'lib/ampere/model.rb', line 208

def belongs_to(field_name, options = {})
  has_one field_name, options
end

#compound_indicesObject

Like @indices, but only returns the compound indices this class defines.



213
214
215
# File 'lib/ampere/model.rb', line 213

def compound_indices
  @indices.select{|i| i.class == Array}
end

#countObject

Returns the number of instances of this record that have been stored.



218
219
220
# File 'lib/ampere/model.rb', line 218

def count
  Ampere.connection.keys("#{to_s.downcase}.*").length
end

#create(hash = {}) ⇒ Object Also known as: create!

Instantiates and saves a new record.



223
224
225
# File 'lib/ampere/model.rb', line 223

def create(hash = {})
  new(hash).save
end

#delete(id) ⇒ Object

Deletes the record with the given ID.



229
230
231
232
233
234
# File 'lib/ampere/model.rb', line 229

def delete(id)
  record = find(id)
  Ampere.connection.del(key_for_find(self, id))
  record.destroyed = true
  record
end

#field(name, options = {}) ⇒ Object

Declares a field. See the README for more details.



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/ampere/model.rb', line 237

def field(name, options = {})
  @fields         ||= []
  @field_defaults ||= {}
  @indices        ||= []
  @unique_indices ||= []
  @field_types    ||= {}

  @fields << name

  # attr_accessor :"#{name}"

  # Handle default value
  @field_defaults[name] = options[:default]

  # Handle type, if any
  if options[:type] then
    @field_types[:"#{name}"] = options[:type].to_s
  end

  define_method :"#{name}" do
    instance_variable_get("@#{name}") or self.class.field_defaults[name]
  end

  define_method :"#{name}=" do |val|
    if not self.class.field_types[:"#{name}"] or val.is_a?(eval(self.class.field_types[:"#{name}"])) then
      instance_variable_set("@#{name}", val)
    else
      raise "Cannot set field of type #{self.class.field_types[name.to_sym]} with #{val.class} value"
    end
  end
end

#field_defaultsObject



273
274
275
# File 'lib/ampere/model.rb', line 273

def field_defaults
  @field_defaults
end

#field_typesObject



277
278
279
# File 'lib/ampere/model.rb', line 277

def field_types
  @field_types
end

#fieldsObject



269
270
271
# File 'lib/ampere/model.rb', line 269

def fields
  @fields
end

#find(options = {}) ⇒ Object

Finds the record with the given ID, or the first that matches the given conditions



282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/ampere/model.rb', line 282

def find(options = {})
  if options.class == String or options.is_a?(Fixnum) then
    options = key_for_find(self, options)
    
    if Ampere.connection.exists(options) then
      new(Ampere.connection.hgetall(options), true)
    else
      nil
    end
  else
    # TODO Write a handler for this case, even if it's an exception
    raise "Cannot find by #{options.class} yet"
  end
end

#firstObject



297
298
299
# File 'lib/ampere/model.rb', line 297

def first
  all.first
end

#has_many(field_name, options = {}) ⇒ Object

Defines a has_many relationship with another model. See the README for more details.



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/ampere/model.rb', line 323

def has_many(field_name, options = {})
  klass_name = (options[:class] or options['class'] or field_name.to_s.gsub(/s$/, ''))
  my_klass_name = to_s.downcase

  define_method(:"#{field_name}") do
    (Ampere.connection.smembers(key_for_has_many(my_klass_name, self.id, field_name))).map do |id|
      eval(klass_name.to_s.capitalize).find(id)
    end
  end

  define_method(:"#{field_name}=") do |val|
    val.each do |v|
      Ampere.connection.multi do
        Ampere.connection.sadd(key_for_has_many(my_klass_name, self.id, field_name), v.id)
        # Set pointer for belongs_to
        Ampere.connection.hset(key_for_find(v.class, v.id), "#{my_klass_name}_id", self.send("id"))
      end
    end
  end
end

#has_one(field_name, options = {}) ⇒ Object

Defines a has_one relationship with another model. See the README for more details.



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/ampere/model.rb', line 302

def has_one(field_name, options = {})
  referred_klass_name = (options[:class] or options['class'] or field_name)
  my_klass_name = to_s.downcase

  field :"#{field_name}_id"

  define_method(field_name.to_sym) do
    return if self.send("#{field_name}_id").nil?
    eval(referred_klass_name.to_s.capitalize).find(self.send("#{field_name}_id"))
  end

  define_method(:"#{field_name}=") do |val|
    return nil if val.nil?
    # Set attr with key where referred model is stored
    self.send("#{field_name}_id=", val.id)
    # Also update that model's hash with a pointer back to here
    val.send("#{my_klass_name}_id=", self.send("id")) if val.respond_to?("#{my_klass_name}_id=")
  end
end

#index(field_name, options = {}) ⇒ Object

Defines an index. See the README for more details.



345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'lib/ampere/model.rb', line 345

def index(field_name, options = {})
  # TODO There has just got to be a better way to handle this.
  @fields         ||= []
  @field_defaults ||= {}
  @indices        ||= []
  @unique_indices ||= []
  @field_types    ||= {}

  if field_name.class == String or field_name.class == Symbol then
    # Singular index
    raise "Can't index a nonexistent field!" unless @fields.include?(field_name)
  elsif field_name.class == Array then
    # Compound index
    field_name.each{|f| raise "Can't index a nonexistent field!" unless @fields.include?(f)}
    field_name.sort!
  else
    raise "Can't index a #{field_name.class}"
  end

  @indices << field_name
  @unique_indices << field_name if options[:unique]
end

#indicesObject



368
369
370
# File 'lib/ampere/model.rb', line 368

def indices
  @indices
end

#lastObject



372
373
374
# File 'lib/ampere/model.rb', line 372

def last
  all.last
end

#unique_indicesObject



376
377
378
# File 'lib/ampere/model.rb', line 376

def unique_indices
  @unique_indices
end

#where(options = {}) ⇒ Object

Finds an array of records which match the given conditions. This method is much faster when all the fields given are indexed.



382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'lib/ampere/model.rb', line 382

def where(options = {})
  if options.empty? then
    Ampere::Collection.new(eval(to_s), [])
  else
    indexed_fields    = (options.keys & @indices) + compound_indices_for(options)
    nonindexed_fields = (options.keys - @indices) - compound_indices_for(options).flatten
  
    results = nil
  
    unless indexed_fields.empty?
      indexed_fields.map {|key|
        if key.class == String or key.class == Symbol then
          Ampere.connection.hget(key_for_index(key), options[key]).split(/:/) #.map {|id| find(id)}
        else
          # Compound index
          Ampere.connection.hget(
            key_for_index(key.join(':')),
            key.map{|k| options[k]}.join(':')
          ).split(/:/) #.map {|id| find(id)}
        end
      }.each {|s|
        return s if s.empty?
    
        if results.nil? then
          results = s
        else
          results &= s
        end
      }
    end
    
    unless nonindexed_fields.empty?
      results = all if results.nil?
      results = results.to_a.map{|r| r.class == String ? find(r) : r}
      nonindexed_fields.each do |key|
        results.select!{|r| 
          r.send(key) == options[key]
        }
      end
    end
  
    # TODO The eval(to_s) trick seems a little... ghetto. 
    Ampere::Collection.new(eval(to_s), results.reverse)
  end
end