Class: ActiveRecordBitmask::Map
- Inherits:
-
Object
- Object
- ActiveRecordBitmask::Map
- 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.
- #keys ⇒ Array<Symbol>
- #values ⇒ Array<Integer>
Constructor Details
#initialize(keys) ⇒ Map
Returns a new instance of Map.
11 12 13 |
# File 'lib/active_record_bitmask/map.rb', line 11 def initialize(keys) @mapping = attributes_to_mapping(keys).freeze end |
Instance Attribute Details
#mapping ⇒ Object (readonly)
Returns the value of attribute mapping.
8 9 10 |
# File 'lib/active_record_bitmask/map.rb', line 8 def mapping @mapping end |
Instance Method Details
#all_combination ⇒ Range<Integer>
35 36 37 38 39 40 |
# File 'lib/active_record_bitmask/map.rb', line 35 def all_combination max_bit = values.size max_value = (2 << (max_bit - 1)) - 1 1..max_value end |
#attributes_to_bitmask(attributes) ⇒ Integer
56 57 58 59 60 61 62 63 64 65 |
# File 'lib/active_record_bitmask/map.rb', line 56 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>
26 27 28 29 30 31 32 |
# File 'lib/active_record_bitmask/map.rb', line 26 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
18 19 20 21 |
# File 'lib/active_record_bitmask/map.rb', line 18 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>
45 46 47 48 49 50 51 |
# File 'lib/active_record_bitmask/map.rb', line 45 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 |
#keys ⇒ Array<Symbol>
68 69 70 |
# File 'lib/active_record_bitmask/map.rb', line 68 def keys mapping.keys end |
#values ⇒ Array<Integer>
73 74 75 |
# File 'lib/active_record_bitmask/map.rb', line 73 def values mapping.values end |