Class: BanditMask

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

Constant Summary collapse

VERSION =
"0.1.0"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mask = 0b0) ⇒ BanditMask

:nodoc:



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

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

Instance Attribute Details

#maskObject (readonly)

Returns the value of attribute mask.



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

def mask
  @mask
end

Class Method Details

.bit(name, value) ⇒ Object

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

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


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

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

.bitsObject

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

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

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


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

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

.reset_bits!Object

Clears all defined bits.



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

def self.reset_bits!
  @bits = {}
end

Instance Method Details

#<<(name) ⇒ Object

Enables the bit named name. Returns self, so calles to #<< can be chained (think Array#<<). Raises ArgumentError if name 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


74
75
76
77
# File 'lib/banditmask.rb', line 74

def <<(name)
  @mask |= name_to_bit(name)
  self
end

#include?(name) ⇒ Boolean

Returns true if name is among the currently enabled bits. Returns false otherwise. Raises ArgumentError if name 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 0b01
mask.include? :read  # => true
mask.include? :write # => false

Returns:

  • (Boolean)


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

def include?(name)
  @mask & name_to_bit(name) != 0
end

#namesObject 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.names # => [:read]


57
58
59
# File 'lib/banditmask.rb', line 57

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

#to_iObject

Returns integer value of current bitmask.



43
44
45
# File 'lib/banditmask.rb', line 43

def to_i
  mask
end