Module DataMapper::Persistence::ConvenienceMethods::ClassMethods
In: lib/data_mapper/persistence.rb
lib/data_mapper/persistence.rb

Methods

[]   []   all   all   count   count   create   create   create!   create!   delete_all   delete_all   each   each   find   find   find_by_sql   find_by_sql   find_or_create   find_or_create   first   first   get   get   truncate!   truncate!  

Public Instance methods

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

- @public

[Source]

     # File lib/data_mapper/persistence.rb, line 398
398:         def [](*keys)
399:           # Eventually this ArgumentError should be removed. It's only here 
400:           # to help
401:           # migrate users away from the [options_hash] syntax, which is no
402:           # longer supported.
403:           raise ArgumentError.new('Hash is not a valid key') if keys.size == 1 && keys.first.is_a?(Hash)
404:           instance = database.get(self, keys)
405:           raise ObjectNotFoundError.new() unless instance
406:           return instance
407:         end

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

- @public

[Source]

     # File lib/data_mapper/persistence.rb, line 398
398:         def [](*keys)
399:           # Eventually this ArgumentError should be removed. It's only here 
400:           # to help
401:           # migrate users away from the [options_hash] syntax, which is no
402:           # longer supported.
403:           raise ArgumentError.new('Hash is not a valid key') if keys.size == 1 && keys.first.is_a?(Hash)
404:           instance = database.get(self, keys)
405:           raise ObjectNotFoundError.new() unless instance
406:           return instance
407:         end

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

- @public

[Source]

     # File lib/data_mapper/persistence.rb, line 261
261:         def all(options = {})
262:           database.all(self, options)
263:         end

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

- @public

[Source]

     # File lib/data_mapper/persistence.rb, line 261
261:         def all(options = {})
262:           database.all(self, options)
263:         end

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

- @public

[Source]

     # File lib/data_mapper/persistence.rb, line 320
320:         def count(*args)
321:           database.count(self, *args)
322:         end

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

- @public

[Source]

     # File lib/data_mapper/persistence.rb, line 320
320:         def count(*args)
321:           database.count(self, *args)
322:         end

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

[Source]

     # File lib/data_mapper/persistence.rb, line 410
410:         def create(attributes)
411:           instance = self.new_with_attributes(attributes)
412:           instance.save
413:           instance
414:         end

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

[Source]

     # File lib/data_mapper/persistence.rb, line 410
410:         def create(attributes)
411:           instance = self.new_with_attributes(attributes)
412:           instance.save
413:           instance
414:         end

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

[Source]

     # File lib/data_mapper/persistence.rb, line 418
418:         def create!(attributes)
419:           instance = create(attributes)
420:           raise ObjectNotFoundError.new(instance) if instance.new_record?
421:           instance
422:         end

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

[Source]

     # File lib/data_mapper/persistence.rb, line 418
418:         def create!(attributes)
419:           instance = create(attributes)
420:           raise ObjectNotFoundError.new(instance) if instance.new_record?
421:           instance
422:         end

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

- @public

[Source]

     # File lib/data_mapper/persistence.rb, line 336
336:         def delete_all
337:           database.delete_all(self)
338:         end

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

- @public

[Source]

     # File lib/data_mapper/persistence.rb, line 336
336:         def delete_all
337:           database.delete_all(self)
338:         end

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.

[Source]

     # File lib/data_mapper/persistence.rb, line 271
271:         def each(options = {}, &b)
272:           raise ArgumentError.new(":offset is not supported with the #each method") if options.has_key?(:offset)
273: 
274:           offset = 0
275:           limit = options[:limit] || (self::const_defined?('DEFAULT_LIMIT') ? self::DEFAULT_LIMIT : 500)
276: 
277:           until (results = all(options.merge(:limit => limit, :offset => offset))).empty?
278:             results.each(&b)
279:             offset += limit
280:           end
281:         end

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.

[Source]

     # File lib/data_mapper/persistence.rb, line 271
271:         def each(options = {}, &b)
272:           raise ArgumentError.new(":offset is not supported with the #each method") if options.has_key?(:offset)
273: 
274:           offset = 0
275:           limit = options[:limit] || (self::const_defined?('DEFAULT_LIMIT') ? self::DEFAULT_LIMIT : 500)
276: 
277:           until (results = all(options.merge(:limit => limit, :offset => offset))).empty?
278:             results.each(&b)
279:             offset += limit
280:           end
281:         end

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

[Source]

     # File lib/data_mapper/persistence.rb, line 352
352:         def find(type_or_id, options = {})
353:           case type_or_id
354:             when :first then first(options)
355:             when :all then all(options)
356:             else first(type_or_id, options)
357:           end
358:         end

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

[Source]

     # File lib/data_mapper/persistence.rb, line 352
352:         def find(type_or_id, options = {})
353:           case type_or_id
354:             when :first then first(options)
355:             when :all then all(options)
356:             else first(type_or_id, options)
357:           end
358:         end

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.

[Source]

     # File lib/data_mapper/persistence.rb, line 371
371:         def find_by_sql(*args)
372:           DataMapper::database.query(*args)
373:         end

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.

[Source]

     # File lib/data_mapper/persistence.rb, line 371
371:         def find_by_sql(*args)
372:           DataMapper::database.query(*args)
373:         end

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

- @public

[Source]

     # File lib/data_mapper/persistence.rb, line 214
214:         def find_or_create(search_attributes, create_attributes = {})
215:           first(search_attributes) || create(search_attributes.merge(create_attributes))
216:         end

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

- @public

[Source]

     # File lib/data_mapper/persistence.rb, line 214
214:         def find_or_create(search_attributes, create_attributes = {})
215:           first(search_attributes) || create(search_attributes.merge(create_attributes))
216:         end

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

- @public

[Source]

     # File lib/data_mapper/persistence.rb, line 299
299:         def first(*args)
300:           database.first(self, *args)
301:         end

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

- @public

[Source]

     # File lib/data_mapper/persistence.rb, line 299
299:         def first(*args)
300:           database.first(self, *args)
301:         end

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'

[Source]

     # File lib/data_mapper/persistence.rb, line 381
381:         def get(*keys)
382:           database.get(self, keys)
383:         end

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'

[Source]

     # File lib/data_mapper/persistence.rb, line 381
381:         def get(*keys)
382:           database.get(self, keys)
383:         end

[Source]

     # File lib/data_mapper/persistence.rb, line 340
340:         def truncate!
341:           database.truncate(self)
342:         end

[Source]

     # File lib/data_mapper/persistence.rb, line 340
340:         def truncate!
341:           database.truncate(self)
342:         end

[Validate]