Module: ActAsTimeAsBoolean::ClassMethods

Defined in:
lib/act_as_time_as_boolean/concern.rb

Instance Method Summary collapse

Instance Method Details

#time_as_boolean(field, options = {}) ⇒ Object


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
42
43
44
45
46
47
48
# File 'lib/act_as_time_as_boolean/concern.rb', line 7

def time_as_boolean(field, options = {})
  define_method field do
    !send(:"#{field}_at").nil?
  end
  send :alias_method, :"#{field}?", :"#{field}"

  define_method :"#{field}=" do |value|
    value = value && value.to_s != '0'
    if value && !send(field)
      send :"#{field}_at=", Time.now
      true
    elsif !value && send(field)
      send :"#{field}_at=", nil
    end
  end

  define_method :"#{field}!" do
    send :"#{field}=", true
    save!
  end

  scope field, -> {
    where "#{table_name}.#{field}_at IS NOT NULL AND #{table_name}.#{field}_at <= ?", Time.current
  }

  if options[:opposite]
    opposite = options[:opposite]
    define_method :"#{opposite}" do
      send(:"#{field}_at").nil?
    end
    send :alias_method, :"#{opposite}?", :"#{opposite}"

    define_method :"#{opposite}!" do
      send :"#{field}=", false
      save!
    end

    scope opposite, -> {
      where "#{table_name}.#{field}_at IS NULL OR #{table_name}.#{field}_at > ?", Time.current
    }
  end
end