module AttrBitwise

Helper to define a bits based value on a Rails model attribute

this helper expose a set of methods to make bitwise operations

Usage :

attr_bitwise :<name>, [column_name: <column_name>,] mapping: <values_sym>

Example class MyModel < ActiveRecord::Base

include AttrBitwise

attr_bitwise :payment_types, mapping: [:slots, :credits]

end

Will define the following high-level methods :

- Class#payment_types => [<Symbol>, ...]
- Class#payment_type?(value_or_sym) => Boolean
- Class#add_payment_type(value_or_sym) => Fixnum
- Class#remove_payment_type(value_or_sym) => Fixnum

Will define the following low-level methods :

- Class.to_bitwise_values(object, name) => [<Fixnum>, ...]
- Class#payment_types_union([Fixnum, ..]) => [Fixnum, ..]
- Class.bitwise_union([Fixnum, ..], name) => [Fixnum, ..]
- Class#payment_types_intersection([Fixnum, ..]) => [Fixnum, ..]
- Class.bitwise_intersection([Fixnum, ..], name) => [Fixnum, ..]
- Class#payment_types_mapping => Hash

More details in methods definition

Constants

VERSION

Private Instance Methods

add_value(column_name, val) click to toggle source

add ‘value_or_symbol` to mask

Ex, with values = `10`
  add_value(1) => 11
# File lib/attr_bitwise.rb, line 245
def add_value(column_name, val)
  send("#{column_name}=", send(column_name) | val)
end
force_to_bitwise_value(value_or_symbol, mapping) click to toggle source

Private instance methods

# File lib/attr_bitwise.rb, line 213
def force_to_bitwise_value(value_or_symbol, mapping)
  self.class.force_to_bitwise_value(value_or_symbol, mapping)
end
remove_value(column_name, val) click to toggle source

remove ‘value_or_symbol` to mask

Ex, with values = `11`
  remove_value(1) => 10
# File lib/attr_bitwise.rb, line 252
def remove_value(column_name, val)
  send("#{column_name}=", send(column_name) & ~val)
end
value?(column_name, val) click to toggle source

Return if value presents in mask (raw value)

# File lib/attr_bitwise.rb, line 238
def value?(column_name, val)
  send(column_name) & val != 0
end
value_getter(name, mapping) click to toggle source

Return current value to symbols array

Ex : 011 => :slots, :credits
# File lib/attr_bitwise.rb, line 224
def value_getter(name, mapping)
  ComparableSymbolsArray.new(
    mapping.values.select { |pv| (send(name) & pv) != 0 }.
      map { |v| value_to_sym(v, mapping) }
  )
end
value_setter(column_name, values_or_symbols_array, mapping) click to toggle source

Set current values from values array

# File lib/attr_bitwise.rb, line 232
def value_setter(column_name, values_or_symbols_array, mapping)
  send("#{column_name}=", 0)
  values_or_symbols_array.each { |val| add_value(column_name, force_to_bitwise_value(val, mapping)) }
end
value_to_sym(value, mapping) click to toggle source

Given a raw value (int) return proper raw value (int)

# File lib/attr_bitwise.rb, line 218
def value_to_sym(value, mapping)
  mapping.invert[value]
end