This gem provides additional scopes for your ActiveRecord models.
Add this line to your application's Gemfile:
gem 'usefull_scopes'
Or install it yourself as:
$ gem install usefull_scopes
In order to access these scopes, include UsefullScopes
module in your model.
For example:
class User < ActiveRecord::Base
include UsefullScopes
end
Name | Description |
---|---|
random | Random record |
exclude | Records who are not in a given array (you could also provide a single object as an argument) |
with | Records, where attributes' values are corresponding to a given hash. |
without | Records, where attributes' values are `NULL` or aren't equal to values from a given hash. |
asc_by | Records sorted in ascending order using provided attributes. |
desc_by | Records sorted in descending order using provided attributes. |
more_than | FIXME |
less_than | FIXME |
more_or_equal | FIXME |
less_or_equal | FIXME |
These are the scopes created for each of the model attribute.
Name | Description |
---|---|
by_{attribute} | Records ordered by attribute in descending order. |
asc_{by_attribute} | Records ordered by attribute in ascending order. |
like_by_{attribute} | Records, where attribute's value LIKE a given term. |
ilike_by_{attribute} | Сase insensitive implementation of `like_by_{attribute}`. |
{attribute}_more | Records with attribute's value greater than a given value. |
{attribute}_less | Records with attribute's value less than a given value. |
{attribute}_more_or_equal | Records with attribute's value greater or equal than a given value. |
{attribute}_less_or_equal | Records with attribute's value less or equal than a given value. |
Now, it is time to play with our model!
User.create([{name: 'Mike'}, {name: 'Paul'}])
user = User.random
user.name
=> 'Mike'
User.asc_by_name.map(&:name)
=> ['Mike', 'Paul']
User.by_name.map(&:name)
=> ['Paul', 'Mike']
users = User.with_name('Mike')
users.map(&:name)
=> ['Mike']
users = User.with(name: 'Mike')
=> SELECT "users".* FROM "users" WHERE ("users"."name" = 'Mike')
users.map(&:name)
=> ['Mike']
users = User.without(name: ['Mike', 'Paul'])
=> SELECT "users".* FROM "users" WHERE ("users"."name" NOT IN ('Mike','Paul'))
users
=> []
users = User.without(:name, :id)
=> SELECT "users".* FROM "users" WHERE ("users"."name" IS NULL AND "users"."id" IS NULL)
users.count
=> 2
Please see CONTRIBUTING.md for details.
Maintained by kaize.
Thank you to all our amazing contributors!
usefull_scopes is Copyright © 2012-2014 kaize. It is free software, and may be redistributed under the terms specified in the LICENSE file.