Module: DataMapper::Persistence::ConvenienceMethods::ClassMethods

Defined in:
lib/data_mapper/persistence.rb

Instance Method Summary collapse

Instance Method Details

#[](*keys) ⇒ Object

synonym for get()

Parameters

keys <any>:: keys which which to look up objects in the table.

Returns

object :: object matching the request

Raises

DataMapper::ObjectNotFoundError
  could not find the object requested

-

Raises:

  • (ArgumentError)


398
399
400
401
402
403
404
405
406
407
# File 'lib/data_mapper/persistence.rb', line 398

def [](*keys)
  # Eventually this ArgumentError should be removed. It's only here 
  # to help
  # migrate users away from the [options_hash] syntax, which is no
  # longer supported.
  raise ArgumentError.new('Hash is not a valid key') if keys.size == 1 && keys.first.is_a?(Hash)
  instance = database.get(self, keys)
  raise ObjectNotFoundError.new() unless instance
  return instance
end

#all(options = {}) ⇒ Object

returns an array of objects matching options.

Parameters

options <hash>::
  hash of parameters to search by

Returns

Array:: contains all matched objects from the database, or an 
        empty set

Options

Basics:

Widget.all                                          # => no conditions
Widget.all :order => 'created_at desc'              # => ORDER BY created_at desc
Widget.all :limit => 10                             # => LIMIT 10
Widget.all :offset => 100                           # => OFFSET 100
Widget.all :include => [:gadgets]                   # => performs the JOIN according to
                                                         its association with Gadgets

Any non-standard options are assumed to be column names and are ANDed together:

Widget.all :age => 10                               # => WHERE age = 10
Widget.all :age => 10, :title => 'Toy'              # => WHERE age = 10 AND title = 'Toy'

Using Symbol Operators:

Widget.all :age.gt => 20                            # => WHERE age > 10
Widget.all :age.gte => 20, :name.like => '%Toy%'    # => WHERE age >= 10 and name like '%Toy%'

Variations of syntax include the :conditions => {} as well as interpolated arrays

Widget.all :conditions => {:age => 10}              # => WHERE age = 10
Widget.all :conditions => ["age = ?", 10]           # => WHERE age = 10

Syntaxes can be mixed-and-matched as well

Widget.all :conditions => ["age = ?", 10], :title => 'Toy'
# => WHERE age = 10 AND title = 'Toy'

Raises

DataMapper::Adapters::Sql::Commands::LoadCommand::ConditionsError

A query could not be constructed from the hash passed in as options

DataObject::QueryError

The database threw an error

-



261
262
263
# File 'lib/data_mapper/persistence.rb', line 261

def all(options = {})
  database.all(self, options)
end

#count(*args) ⇒ Object

returns the count of rows that match the given options hash. See all() for a list of possible arguments. NOTE: discards :offset, :limit, :order

Parameters

see all().

Returns

Integer:: number of rows matching query

Raises

DataMapper::Adapters::Sql::Commands::LoadCommand::ConditionsError::
  A query could not be generated from the arguments passed in
DataObject::QueryError::
  The database threw an error

-



320
321
322
# File 'lib/data_mapper/persistence.rb', line 320

def count(*args)
  database.count(self, *args)
end

#create(attributes) ⇒ Object

creates (and saves) a new instance of the object.



410
411
412
413
414
# File 'lib/data_mapper/persistence.rb', line 410

def create(attributes)
  instance = self.new_with_attributes(attributes)
  instance.save
  instance
end

#create!(attributes) ⇒ Object

the same as create(), though will raise an ObjectNotFoundError if the instance could not be saved



418
419
420
421
422
# File 'lib/data_mapper/persistence.rb', line 418

def create!(attributes)
  instance = create(attributes)
  raise ObjectNotFoundError.new(instance) if instance.new_record?
  instance
end

#delete_allObject

Does what it says. Deletes all records in a model’s table. before_destroy and after_destroy callbacks are called and paranoia is respected.

Returns

nil:: successfully deleted all rows

Raises

DataObject::QueryError::
  The database threw an error

-



336
337
338
# File 'lib/data_mapper/persistence.rb', line 336

def delete_all
  database.delete_all(self)
end

#each(options = {}, &b) ⇒ Object

Allows you to iterate over a collection of matching records. The first argument is the find options. The second is a block that will be called for every matching record.

The valid options are the same as those documented in #all, except the :offset option, which is not allowed.

Raises:

  • (ArgumentError)


271
272
273
274
275
276
277
278
279
280
281
# File 'lib/data_mapper/persistence.rb', line 271

def each(options = {}, &b)
  raise ArgumentError.new(":offset is not supported with the #each method") if options.has_key?(:offset)

  offset = 0
  limit = options[:limit] || (self::const_defined?('DEFAULT_LIMIT') ? self::DEFAULT_LIMIT : 500)

  until (results = all(options.merge(:limit => limit, :offset => offset))).empty?
    results.each(&b)
    offset += limit
  end
end

#find(type_or_id, options = {}) ⇒ Object

This method allows for ActiveRecord style queries. The first argument is a symbol indicating a search for a single record or a collection — :first and :all respectively. The second argument is the hash of options for your query. For a list of valid options, please refer to the #all method.

Widget.find(:all,   :active => true)    # => An array of active widgets
Widget.find(:first, :active => true)    # => The first active widget found


352
353
354
355
356
357
358
# File 'lib/data_mapper/persistence.rb', line 352

def find(type_or_id, options = {})
  case type_or_id
    when :first then first(options)
    when :all then all(options)
    else first(type_or_id, options)
  end
end

#find_by_sql(*args) ⇒ Object

supply this method with the full SQL you wish to search on, and it will return an array of Structs with your results set in them.

NOTE: this does NOT return objects of a specific type, but rather Struct objects with as many attributes as what you requested in your full SQL query. These structs are read-only.

If you only indicate you want 1 specific column, Datamapper and DataObjects will do their best to type-cast the result as best they can, rather than supplying you with an array of length 1 containing Structs with 1 attribute.



371
372
373
# File 'lib/data_mapper/persistence.rb', line 371

def find_by_sql(*args)
  DataMapper::database.query(*args)
end

#find_or_create(search_attributes, create_attributes = {}) ⇒ Object

Attempts to find an object using options passed as search_attributes, and falls back to creating the object if it can’t find it.

Parameters

search_attributes <hash>

attributes used to perform the search, and which can be later merged with create_attributes when creating a record

create_attributes <hash>

attributes which are merged into the search_attributes when a record is unfound and needs to be created

Returns

Object

the found or created object from the database

Raises

ValidationError

An object was not found, and could not be created due to errors in validation.

DataObject::QueryError

The database threw an error

-



214
215
216
# File 'lib/data_mapper/persistence.rb', line 214

def find_or_create(search_attributes, create_attributes = {})
  first(search_attributes) || create(search_attributes.merge(create_attributes))
end

#first(*args) ⇒ Object

Returns the first object which matches the query generated from the arguments

Parameters

see all()

Returns

Object:: first object from the database which matches the query
nil::  no object could be found which matches the query

Raises

DataMapper::Adapters::Sql::Commands::LoadCommand::ConditionsError::
  A query could not be generated from the arguments passed in
DataObject::QueryError::
  The database threw an error

-



299
300
301
# File 'lib/data_mapper/persistence.rb', line 299

def first(*args)
  database.first(self, *args)
end

#get(*keys) ⇒ Object

finds a single row from the database by it’s primary key. If you declared a property with :key => true, it’s safe to use here. Example:

Widget.get(100)                                        # => widget with the primary key of 100
Widget.get('Toy')                                      # => widget with the primary natural key of 'Toy'


381
382
383
# File 'lib/data_mapper/persistence.rb', line 381

def get(*keys)
  database.get(self, keys)
end

#truncate!Object



340
341
342
# File 'lib/data_mapper/persistence.rb', line 340

def truncate!
  database.truncate(self)
end