Module: NamedScopeForTimeAttr::ClassMethods
- Defined in:
- lib/named_scope_for_time_attr/named_scope_for_time_attr.rb
Instance Method Summary collapse
-
#named_scope_for_time_attr(attr_name, options = {}) ⇒ Object
Provides the
ActiveRecord
helper methodnamed_scope_for_time_attr
.
Instance Method Details
#named_scope_for_time_attr(attr_name, options = {}) ⇒ Object
Provides the ActiveRecord
helper method named_scope_for_time_attr
.
Given the name of a time attribute of an ActiveRecord model (e.g. created_at
of Claim
) it defines a correspondent named scope for easy access to an arbitrarily time range (scope).
Examples
class Claim < ActiveRecord::Base
named_scope_for_time_attr :created_at, :order => 'created_at DESC'
named_scope_for_time_attr :updated_at
named_scope_for_time_attr :last_modified_on, :limit => 10
...
end
It is then possible to use the scope method created_at
and updated_at
as follows:
Claim.created_at(2.days.ago)
Claim.updated_at(2.days.ago, 1.days.ago)
Claim.last_modified_on(3.weeks.ago)
Is is even possible to use one of the following predefined keys to specify a time range:
-
:today
-
:yesterday
-
:tomorrow
-
:this_week
-
:last_week
-
:next_week
-
:this_month
-
:last_month
-
:next_month
-
:this_quarter
-
:last_quarter
-
:next_quarter
-
:q1
-
:q2
-
:q3
-
:q4
-
:this_year
-
:last_year
-
:next_year
And use them as follows:
Claim.created_at(:today)
Claim.updated_at(:this_month)
Claim.last_modified_on(:last_year)
Claim.created_at(:q1) # quarter one
Claim.created_at(:this_quarter)
One can specify additional conditional options to named_scope_for_time_attr
to sort or limit the list of object loaded:
class Claim < ActiveRecord::Base
named_scope_for_time_attr :created_at, :order => 'created_at DESC'
named_scope_for_time_attr :updated_at, :limit => 10
...
end
The definition also provide a scope order
to ordered the list which is used as follows:
Claim.updated_at(:yesterday).order(:updated_at) # => ... ORDER BY created_at
Claim.updated_at(:last_week).order('updated_at DESC') # => ... ORDER BY updated_at DESC
Claim.updated_at(:yesterday).order('shortname') # => ... ORDER BY shortname
77 78 79 80 |
# File 'lib/named_scope_for_time_attr/named_scope_for_time_attr.rb', line 77 def named_scope_for_time_attr(attr_name, = {}) named_scope attr_name, lambda { |*args| build_conditions("#{table_name}.#{attr_name}", *args).merge() } named_scope :order, lambda { |*args| {:order => (args.first || "#{attr_name} DESC") } } end |