Module: Pacecar::State::ClassMethods

Defined in:
lib/pacecar/state.rb

Instance Method Summary collapse

Instance Method Details

#has_state(*names) ⇒ Object



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
# File 'lib/pacecar/state.rb', line 9

def has_state(*names)
  opts = names.extract_options!
  names.each do |name|
    constant = opts[:with] || const_get(name.to_s.pluralize.upcase)
    constant.each do |state|
      scope "#{name}_#{state.downcase}", -> {
        where(arel_table[name].eq state)
      }
      scope "#{name}_not_#{state.downcase}", -> {
        where(arel_table[name].not_eq state)
      }
      self.class_eval %Q{
        def #{name}_#{state.downcase}?
          #{name} == '#{state}'
        end
        def #{name}_not_#{state.downcase}?
          #{name} != '#{state}'
        end
      }
    end
    scope "#{name}", ->(state) {
      where(arel_table[name].eq state)
    }
    scope "#{name}_not", ->(state) {
      where(arel_table[name].not_eq state)
    }
  end
end