Module: ArrayBitMask::ClassMethods
- Defined in:
- lib/array_bit_mask.rb
Instance Method Summary collapse
-
#as_bit_mask(attr, options = {}) ⇒ Object
Creates methods that accepts array of values and save them as bit mask to the attribute with an “_mask” suffix using specified source.
Instance Method Details
#as_bit_mask(attr, options = {}) ⇒ Object
Creates methods that accepts array of values and save them as bit mask to the attribute with an “_mask” suffix using specified source
Options
- :source
-
Specify array of values of method name which should return an array.
- :column
-
Specify the column which would be used to store bit mask. By default, this is an attribute with an “_mask” suffix.
Example
as_bit_mask :actions, :source => [:create, :show, :update], :column => :my_mask_column
as_bit_mask :actions, :source => :subject_actions
will save bit mask to :actions_mask attribute
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/array_bit_mask.rb', line 22 def as_bit_mask(attr, ={}) return 0 unless [:source] [:column] ||= "#{attr}_mask" define_method "#{attr}=" do |val| source = bit_mask_source_for([:source]) values = val.map(&:to_sym) & source res = self.send("#{[:column]}=", values.map { |a| 2**source.index(a) }.inject(:+)) instance_variable_set("@#{attr}", values) end define_method attr do instance_variable_get("@#{attr}") || begin source = bit_mask_source_for([:source]) res = source.reject { |r| ((self.send([:column]) || 0) & 2**source.index(r)).zero? } instance_variable_set("@#{attr}", res) end end end |