Class: BanditMask

Inherits:
Object
  • Object
show all
Defined in:
lib/banditmask.rb,
lib/banditmask/version.rb,
lib/banditmask/banditry.rb

Defined Under Namespace

Modules: Banditry

Constant Summary collapse

VERSION =
'0.2.1'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bitmask = 0b0) ⇒ BanditMask

:nodoc:



7
8
9
# File 'lib/banditmask.rb', line 7

def initialize(bitmask = 0b0) # :nodoc:
  @bitmask = bitmask
end

Instance Attribute Details

#bitmaskObject (readonly)

Returns the value of attribute bitmask.



5
6
7
# File 'lib/banditmask.rb', line 5

def bitmask
  @bitmask
end

Class Method Details

.bit(name, value) ⇒ Object

Maps name to value in the global list of defined bits.

class MyMask < BanditMask
  bit :read, 0b001
  bit :write, 0b010
  bit :execute, 0b100
end


32
33
34
# File 'lib/banditmask.rb', line 32

def self.bit(name, value)
  bits.update name => value
end

.bitsObject

Returns a Hash mapping all defined names to their respective bits.

class MyMask < BanditMask
  bit :read, 0b01
  bit :write, 0b10
end

MyMask.bits # => { :read => 1, :write => 2 }


20
21
22
# File 'lib/banditmask.rb', line 20

def self.bits
  @bits ||= {}
end

Instance Method Details

#<<(bit) ⇒ Object

Enables the bit named bit. Returns self, so calls to #<< can be chained. (Think Array#<<.) Raises ArgumentError if bit does not correspond to a bit that was previously declared with BanditMask.bit.

class BanditMask
  bit :read, 0b01
  bit :write, 0b10
end

mask = BanditMask.new
mask << :read << :write


69
70
71
72
# File 'lib/banditmask.rb', line 69

def <<(bit)
  @bitmask |= bit_value(bit)
  self
end

#bitsObject Also known as: to_a

Returns an array of names of the currently enabled bits.

class BanditMask
  bit :read, 0b01
  bit :write, 0b10
end

mask = BanditMask.new 0b01
mask.bits # => [:read]


52
53
54
# File 'lib/banditmask.rb', line 52

def bits
  self.class.bits.select { |bit, _| include? bit }.keys
end

#include?(*bits) ⇒ Boolean

Returns false if any bit in bits is not enabled. Returns true otherwise. Raises ArgumentError if bits is empty or if any element in bits does not correspond to bit that was previously declared with BanditMask.bit.

class BanditMask
  bit :read, 0b001
  bit :write, 0b010
  bit :execute, 0b100
end

mask = BanditMask.new 0b101

mask.include? :read           # => true
mask.include? :write          # => false
mask.include? :execute        # => true

mask.include? :read, :write   # => false
mask.include? :read, :execute # => true

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


93
94
95
96
# File 'lib/banditmask.rb', line 93

def include?(*bits)
  raise ArgumentError, 'wrong number of arguments (0 for 1+)' if bits.empty?
  bits.all? { |bit| bitmask & bit_value(bit) != 0 }
end

#to_iObject

Returns integer value of current bitmask.



38
39
40
# File 'lib/banditmask.rb', line 38

def to_i
  bitmask
end