Module: TimestampStateFields::ClassMethods
- Defined in:
- lib/timestamp_state_fields.rb
Instance Method Summary collapse
-
#timestamp_state_fields(*timestamps) ⇒ Object
Implements ActiveRecord state fields based on timestamp columns.
Instance Method Details
#timestamp_state_fields(*timestamps) ⇒ Object
Implements ActiveRecord state fields based on timestamp columns.
Requires a column in the model to have :‘state`_at
Example:
class User < ActiveRecord::Base
include TimestampStateFields
:subscribed_at, :verified_at
end
u = User.new
u.mark_as_subscribed
u.subscribed_at # => "2015-11-15 22:51:13 -0800"
u.subscribed? # => true
User.subscribed.count # Number of subscribed users
User.subscribed.not_verified.count # Number of unsubscribed users that are not verified
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/timestamp_state_fields.rb', line 24 def (*) .map(&:to_s).each do || Raise ArgumentError.new("Timestamp name should end with '_at'") unless .end_with?("_at") state = .sub(/_at$/, '') define_singleton_method(:"#{state}") do where.not( => nil) end define_singleton_method(:"not_#{state}") do where( => nil) end define_method(:"#{state}?") do read_attribute().present? end define_method(:"not_#{state}?") do read_attribute().blank? end define_method(:"mark_as_#{state}") do write_attribute(, Time.current) end define_method(:"mark_as_not_#{state}") do write_attribute(, nil) end end end |