module BitfieldAttribute::Base

Constants

INTEGER_SIZE

Public Class Methods

new(instance, attribute) click to toggle source
# File lib/bitfield_attribute/base.rb, line 58
def initialize(instance, attribute)
  @instance = instance
  @attribute = attribute

  keys = self.class.keys

  @values = keys.zip([false] * keys.size)
  @values = Hash[@values]

  read_bits
end

Public Instance Methods

as_json(options = nil) click to toggle source
# File lib/bitfield_attribute/base.rb, line 100
def as_json(options = nil)
  attributes
end
attributes() click to toggle source
# File lib/bitfield_attribute/base.rb, line 78
def attributes
  @values.freeze
end
attributes=(value) click to toggle source
# File lib/bitfield_attribute/base.rb, line 82
def attributes=(value)
  @values.each { |key, _| @values[key] = false }
  update(value)
end
to_a() click to toggle source
# File lib/bitfield_attribute/base.rb, line 70
def to_a
  @values.map { |key, value| key if value }.compact
end
update(value) click to toggle source
# File lib/bitfield_attribute/base.rb, line 87
def update(value)
  if value.is_a?(Integer)
    write_bits(value)
  else
    value.symbolize_keys.each do |key, value|
      if @values.keys.include?(key)
        @values[key] = true_value?(value)
      end
    end
    write_bits
  end
end
value() click to toggle source
# File lib/bitfield_attribute/base.rb, line 74
def value
  @instance[@attribute].to_i
end

Private Instance Methods

read_bits() click to toggle source
# File lib/bitfield_attribute/base.rb, line 105
def read_bits
  bit_value = @instance[@attribute].to_i

  @values.keys.each.with_index do |name, index|
    bit = 2 ** index
    @values[name] = true if bit_value & bit == bit
  end
end
true_value?(value) click to toggle source
# File lib/bitfield_attribute/base.rb, line 131
def true_value?(value)
  if ActiveRecord::VERSION::MAJOR == 5
    ActiveRecord::Type::Boolean.new.cast(value)
  elsif ActiveRecord::VERSION::MINOR < 2
    ActiveRecord::ConnectionAdapters::Column.value_to_boolean(value)
  else
    ActiveRecord::Type::Boolean.new.type_cast_from_user(value)
  end
end
write_bits(predefined_bits = nil) click to toggle source
# File lib/bitfield_attribute/base.rb, line 114
def write_bits(predefined_bits = nil)
  if predefined_bits.present?
    bits = predefined_bits
  else
    bits = 0
    @values.keys.each.with_index do |name, index|
      bits = bits | (2 ** index) if @values[name]
    end
  end

  @instance[@attribute] = bits

  if predefined_bits
    read_bits
  end
end