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.



201
202
203
# File 'lib/ampere/model.rb', line 201

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.



206
207
208
# File 'lib/ampere/model.rb', line 206

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.



211
212
213
# File 'lib/ampere/model.rb', line 211

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

#countObject

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



216
217
218
# File 'lib/ampere/model.rb', line 216

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

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

Instantiates and saves a new record.



221
222
223
# File 'lib/ampere/model.rb', line 221

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

#delete(id) ⇒ Object

Deletes the record with the given ID.



227
228
229
230
231
# File 'lib/ampere/model.rb', line 227

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

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

Declares a field. See the README for more details.



234
235
236
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
# File 'lib/ampere/model.rb', line 234

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



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

def field_defaults
  @field_defaults
end

#field_typesObject



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

def field_types
  @field_types
end

#fieldsObject



266
267
268
# File 'lib/ampere/model.rb', line 266

def fields
  @fields
end

#find(options = {}) ⇒ Object

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



279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/ampere/model.rb', line 279

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



294
295
296
# File 'lib/ampere/model.rb', line 294

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.



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/ampere/model.rb', line 320

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(to_s.downcase, 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.sadd(key_for_has_many(to_s.downcase, 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

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

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



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

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"))
  end
end

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

Defines an index. See the README for more details.



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/ampere/model.rb', line 340

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



363
364
365
# File 'lib/ampere/model.rb', line 363

def indices
  @indices
end

#lastObject



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

def last
  all.last
end

#unique_indicesObject



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

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.



377
378
379
380
381
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
# File 'lib/ampere/model.rb', line 377

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