Module: BoolAt::Macro::ClassMethods

Defined in:
lib/bool_at/macro.rb

Instance Method Summary collapse

Instance Method Details

#bool_at(*attrs) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/bool_at/macro.rb', line 6

def bool_at(*attrs)
  attrs.each do |attr|
    at_attribute = "#{attr}_at"
    at_setter = "#{attr}_at="
    setter = "#{attr}="
    predicate = "#{attr}?"

    attribute attr, :boolean, default: false

    after_initialize do
      self[attr] = send(attr)
    end

    # Changes dirty state in virtual attribute
    define_method setter do |value|
      super(value)
      send(at_setter, self[attr] ? self[at_attribute] || Time.now : nil)
    end

    define_method attr do
      send(at_attribute).present? if respond_to?(at_attribute)
    end

    define_method at_setter do |value|
      self[attr] = value.present?
      super(value)
    end

    alias_method predicate, attr

    scope attr, -> { where("#{table_name}.#{attr}_at IS NOT NULL") }
    scope :"not_#{attr}", -> { where("#{table_name}.#{attr}_at IS NULL") }
    scope :"order_#{attr}", -> { order("#{table_name}.#{attr}_at DESC") }
    scope :"reverse_#{attr}", -> { order("#{table_name}.#{attr}_at ASC") }
  end
end