Class: ActiveRecordBitmask::Map
- Inherits:
-
Object
- Object
- ActiveRecordBitmask::Map
- Includes:
- Enumerable
- Defined in:
- lib/active_record_bitmask/map.rb
Constant Summary collapse
- BLANK_VALUES =
Default blank values for checkbox
[:'', :'0'].freeze
Instance Attribute Summary collapse
-
#mapping ⇒ Object
readonly
Returns the value of attribute mapping.
Instance Method Summary collapse
- #all_combination ⇒ Range<Integer>
- #attributes_to_bitmask(attributes) ⇒ Integer
- #bitmask_combination(bitmask) ⇒ Array<Integer>
- #bitmask_or_attributes_to_bitmask(value) ⇒ Integer
- #bitmask_to_attributes(bitmask) ⇒ Array<Symbol>
-
#initialize(keys) ⇒ Map
constructor
A new instance of Map.
Constructor Details
#initialize(keys) ⇒ Map
Returns a new instance of Map.
17 18 19 |
# File 'lib/active_record_bitmask/map.rb', line 17 def initialize(keys) @mapping = attributes_to_mapping(keys).freeze end |
Instance Attribute Details
#mapping ⇒ Object (readonly)
Returns the value of attribute mapping.
14 15 16 |
# File 'lib/active_record_bitmask/map.rb', line 14 def mapping @mapping end |
Instance Method Details
#all_combination ⇒ Range<Integer>
41 42 43 44 45 46 |
# File 'lib/active_record_bitmask/map.rb', line 41 def all_combination max_bit = values.size max_value = (2 << (max_bit - 1)) - 1 1..max_value end |
#attributes_to_bitmask(attributes) ⇒ Integer
62 63 64 65 66 67 68 69 70 71 |
# File 'lib/active_record_bitmask/map.rb', line 62 def attributes_to_bitmask(attributes) attributes = [attributes].compact unless attributes.respond_to?(:inject) attributes = reject_blank_attributes(attributes) attributes.inject(0) do |bitmask, key| key = key.to_sym if key.respond_to?(:to_sym) bit = mapping.fetch(key) { raise(ArgumentError, "#{key.inspect} is not a valid value") } bitmask | bit end end |
#bitmask_combination(bitmask) ⇒ Array<Integer>
32 33 34 35 36 37 38 |
# File 'lib/active_record_bitmask/map.rb', line 32 def bitmask_combination(bitmask) return [0] if bitmask.to_i.zero? max_value = values.max combination_pattern_size = (max_value << 1) - 1 0.upto(combination_pattern_size).select { |i| i & bitmask == bitmask } end |
#bitmask_or_attributes_to_bitmask(value) ⇒ Integer
24 25 26 27 |
# File 'lib/active_record_bitmask/map.rb', line 24 def bitmask_or_attributes_to_bitmask(value) value = bitmask_to_attributes(value) if value.is_a?(Integer) attributes_to_bitmask(value) end |
#bitmask_to_attributes(bitmask) ⇒ Array<Symbol>
51 52 53 54 55 56 57 |
# File 'lib/active_record_bitmask/map.rb', line 51 def bitmask_to_attributes(bitmask) return [] if bitmask.to_i.zero? mapping.each_with_object([]) do |(key, value), values| values << key.to_sym if (value & bitmask).nonzero? end end |