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
11
# File 'lib/active_flag/definition.rb', line 5

def initialize(column, keys, klass)
  @column = column
  @keys = keys.freeze
  @maps = keys.map.with_index { |key, i| [key, 2**i] }.to_h.freeze
  @klass = klass
  @scope = 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



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

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

#pairsObject



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

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



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

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

#to_array(integer) ⇒ Object



54
55
56
# File 'lib/active_flag/definition.rb', line 54

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

#to_i(arg) ⇒ Object



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

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



50
51
52
# File 'lib/active_flag/definition.rb', line 50

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

#unset_all!(key) ⇒ Object



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

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

#with_scope(scope) ⇒ Object



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

def with_scope(scope)
  dup.tap do |d|
    d.instance_variable_set(:@scope, scope)
  end
end