Class: ActiveRecordBitmask::Map

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

Constructor Details

#initialize(keys) ⇒ Map

Returns a new instance of Map.

Parameters:

  • keys (Array<#to_sym>)


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

#mappingObject (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_combinationRange<Integer>

Returns:

  • (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

Parameters:

  • attributes (Array<#to_sym>)

Returns:

  • (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>

Parameters:

  • bitmask (Integer)

Returns:

  • (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

Parameters:

  • value (Integer, Symbol, Array<#to_sym>)

Returns:

  • (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>

Parameters:

  • bitmask (Integer)

Returns:

  • (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