Module: BitfieldAttribute::Base

Extended by:
ActiveSupport::Concern
Defined in:
lib/bitfield_attribute/base.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#as_json(options = nil) ⇒ Object



100
101
102
# File 'lib/bitfield_attribute/base.rb', line 100

def as_json(options = nil)
  attributes
end

#attributesObject



78
79
80
# File 'lib/bitfield_attribute/base.rb', line 78

def attributes
  @values.freeze
end

#attributes=(value) ⇒ Object



82
83
84
85
# File 'lib/bitfield_attribute/base.rb', line 82

def attributes=(value)
  @values.each { |key, _| @values[key] = false }
  update(value)
end

#initialize(instance, attribute) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
# 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

#to_aObject



70
71
72
# File 'lib/bitfield_attribute/base.rb', line 70

def to_a
  @values.map { |key, value| key if value }.compact
end

#update(value) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
# 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

#valueObject



74
75
76
# File 'lib/bitfield_attribute/base.rb', line 74

def value
  @instance[@attribute].to_i
end