class Bitmask

Attributes

after_change[RW]
bit_ids[RW]
value[R]

Public Class Methods

new( options = {} ) click to toggle source
# 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

Public Instance Methods

[]( bit_id )
Alias for: get
[]=( bit_id, val )
Alias for: set
get( bit_id ) click to toggle source
# File lib/bitmask.rb, line 20
def get ( bit_id )
  position = @bit_ids.index( bit_id )

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

  (@value & (2 ** position)) > 0
end
Also aliased as: []
set( bit_id, val ) click to toggle source
# File lib/bitmask.rb, line 31
def set ( bit_id, val )
  position = @bit_ids.index( bit_id )

  if position == nil
    raise ArgumentError, "#{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

  val
end
Also aliased as: []=
value=( val ) click to toggle source
# File lib/bitmask.rb, line 50
def value= ( val )
  @value = val
  @after_change.call(self) if @after_change
end