Module: DataMapper::Searcher::ClassMethods

Defined in:
lib/dm-searcher/searcher.rb

Instance Method Summary collapse

Instance Method Details

#search(opts = {}) ⇒ DataMapper::Collection

Valid symbol operators for the conditions are:

gt    # greater than
lt    # less than
gte   # greater than or equal
lte   # less than or equal
not   # not equal
eql   # equal
like  # like

Examples:


# Models
class User
  include DataMapper::Resource
  include DataMapper::Searcher

  property :id, Serial
  property :name, String

  has n, :roles
end

class Role
  include DataMapper::Resource
  include DataMapper::Searcher

  property :id, Serial
  property :name, String

  belongs_to :user
end

# Search for records
User.search('name.like' => '%Tower%')
# => Returns the users whose name contains 'Tower'.

User.search('id.gt' => 10)
# => Returns the users whose id is greater than 10.

User.search('roles.name' => 'Administrators')
# => Returns the users whose role is 'Administrator'.

User.search('name.like' => '%Tower%',
            'id.gt' => 10,
            'roles.name' => 'Administrators') 
# => Returns the users whose name contains 'Tower', id is greater than 10 and role is 'Administrators'.

# Combining the result
User.search('name.like' => '%Tower%') + User.search('id.gt' => 10)
User.search('name.like' => '%Tower%') | User.search('id.gt' => 10)
# => Returns the users whose name contains 'Tower' or id is greater than 10.

User.search('name.like' => '%Tower%') & User.search('id.gt' => 10)
User.search('name.like' => '%Tower%') - User.search('id.gt' => 10)
# => Returns the users whose name contains 'Tower' and id is greater than 10.

Returns:

  • (DataMapper::Collection)

    Matched records



64
65
66
67
68
# File 'lib/dm-searcher/searcher.rb', line 64

def search(opts = {})
  options = parse_opts(self, opts || {})

  self.all(options)
end