Class: ActiveFlag::Definition

Inherits:
Object
  • Object
show all
Defined in:
lib/active_flag/definition.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(column, keys, klass) ⇒ Definition

Returns a new instance of Definition.



5
6
7
8
9
10
# File 'lib/active_flag/definition.rb', line 5

def initialize(column, keys, klass)
  @column = column
  @keys = keys.freeze
  @maps = Hash[keys.map.with_index{ |key, i| [key, 2**i] }].freeze
  @klass = klass
end

Instance Attribute Details

#columnObject (readonly)

Returns the value of attribute column.



3
4
5
# File 'lib/active_flag/definition.rb', line 3

def column
  @column
end

#keysObject (readonly)

Returns the value of attribute keys.



3
4
5
# File 'lib/active_flag/definition.rb', line 3

def keys
  @keys
end

#mapsObject (readonly)

Returns the value of attribute maps.



3
4
5
# File 'lib/active_flag/definition.rb', line 3

def maps
  @maps
end

Instance Method Details

#humansObject



12
13
14
15
16
17
# File 'lib/active_flag/definition.rb', line 12

def humans
  @humans ||= {}
  @humans[I18n.locale] ||= begin
    @keys.map { |key| [key, human(key)] }.to_h
  end
end

#pairsObject



19
20
21
22
# File 'lib/active_flag/definition.rb', line 19

def pairs
  @pairs ||= {}
  @pairs[I18n.locale] ||= humans.invert
end

#set_all!(key) ⇒ Object

Set / unset a bit on all records for migration stackoverflow.com/a/12928899/157384



27
28
29
# File 'lib/active_flag/definition.rb', line 27

def set_all!(key)
  @klass.update_all("#{@column} = COALESCE(#{@column}, 0) | #{@maps[key]}")
end

#to_array(integer) ⇒ Object



45
46
47
# File 'lib/active_flag/definition.rb', line 45

def to_array(integer)
  @maps.map { |key, mask| (integer & mask > 0) ? key : nil }.compact
end

#to_i(arg) ⇒ Object



35
36
37
38
39
# File 'lib/active_flag/definition.rb', line 35

def to_i(arg)
  arg = [arg] unless arg.is_a?(Enumerable)
  arg = arg.uniq
  arg.map { |s| s && @maps[s.to_s.to_sym] || 0 }.sum
end

#to_value(instance, integer) ⇒ Object



41
42
43
# File 'lib/active_flag/definition.rb', line 41

def to_value(instance, integer)
  Value.new(to_array(integer)).with(instance, self)
end

#unset_all!(key) ⇒ Object



31
32
33
# File 'lib/active_flag/definition.rb', line 31

def unset_all!(key)
  @klass.update_all("#{@column} = COALESCE(#{@column}, 0) & ~#{@maps[key]}")
end