Class: Bitmask

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Bitmask

Returns a new instance of Bitmask.



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/bitmask.rb', line 6

def initialize ( options = {} )
  default_values = {
    :value => 0,
    :bit_ids => []
  }
  options = default_values.merge(options)

  # Events
  @after_change = options[:after_change]

  @value   = options[:value].to_i
  @bit_ids = options[:bit_ids]
end

Instance Attribute Details

#after_changeObject

Returns the value of attribute after_change.



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

def after_change
  @after_change
end

#bit_idsObject

Returns the value of attribute bit_ids.



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

def bit_ids
  @bit_ids
end

#valueObject

Returns the value of attribute value.



4
5
6
# File 'lib/bitmask.rb', line 4

def value
  @value
end

Instance Method Details

#get(bit_id) ⇒ Object



20
21
22
23
24
25
26
27
28
# File 'lib/bitmask.rb', line 20

def get ( bit_id )
  position = @bit_ids.index( bit_id )

  if position == nil
    raise "#{bit_id.inspect} was not included on bit_ids array"
  end

  return (@value & (2 ** position)) > 0
end

#set(bit_id, val) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/bitmask.rb', line 30

def set ( bit_id, val )
  position = @bit_ids.index( bit_id )

  if position == nil
    raise "#{bit_id.inspect} was not included on bit_ids array"
  end

  if val == true
    self.value |= (2 ** position)
  else
    self.value &= ~(2 ** position)
  end

  @after_change.call(self) if @after_change

  return self.value
end