Module: BitmaskAttribute::Concern::ClassMethods

Defined in:
lib/bitmask_attribute/concern.rb

Instance Method Summary collapse

Instance Method Details

#bitmask_attribute(name, options_hash) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/bitmask_attribute/concern.rb', line 10

def bitmask_attribute(name, options_hash)
  single_name = name.to_s.singularize
  define_method "#{single_name}_present?" do |bit_sequence|
    send(name) & bit_sequence == bit_sequence
  end

  define_method "add_#{single_name}" do |bit_sequence|
    current_bits = send(name)
    send("#{name}=", current_bits | bit_sequence)
  end

  define_method "remove_#{single_name}" do |bit_sequence|
    current_bits = send(name)
    send("#{name}=", current_bits & ~bit_sequence)
  end

  options_hash.each do |key, value|
    define_method "#{key}=" do |bool_value|
      bool_value ? send("add_#{single_name}", value) : send("remove_#{single_name}", value)
    end
  end
end