Class: Flagpole
- Inherits:
-
Object
- Object
- Flagpole
- Defined in:
- lib/flagpole.rb,
lib/flagpole/version.rb
Constant Summary collapse
- VERSION =
"0.1.0".freeze
Instance Method Summary collapse
-
#[](key) ⇒ Object
Public: Get a specific flag by name.
-
#[]=(flag, val) ⇒ Object
Public: Set a specific flag by name.
-
#initialize(value = 0, flags) ⇒ Flagpole
constructor
Public: Initialize the set of flags.
-
#to_h ⇒ Object
Public: Returns a Hash with all the flags and their current values.
-
#to_i ⇒ Object
Public: Returns the current value of the flag set as an Integer.
-
#value_of(flag) ⇒ Object
Public: Find the integer value of a single flag, regardless of whether it is set or not.
Constructor Details
#initialize(value = 0, flags) ⇒ Flagpole
Public: Initialize the set of flags.
value - An Integer with the initial value of the set. flags - The name of the flags you’re using.
6 7 8 |
# File 'lib/flagpole.rb', line 6 def initialize(value = 0, flags) @flags = flags.zip(bitmap(value, flags.size)).to_h end |
Instance Method Details
#[](key) ⇒ Object
Public: Get a specific flag by name.
key - One of the flag names passed to the initializer.
Returns Boolean.
15 16 17 |
# File 'lib/flagpole.rb', line 15 def [](key) @flags.fetch(key) end |
#[]=(flag, val) ⇒ Object
Public: Set a specific flag by name.
flag - One of the flag names passed to the initializer. value - A Boolean.
Returns nothing. Raises ArgumentError if passed a flag that isn’t in the set.
26 27 28 29 |
# File 'lib/flagpole.rb', line 26 def []=(flag, val) fail ArgumentError, "#{flag} isn't a valid flag" unless @flags.key?(flag) @flags[flag] = val end |
#to_h ⇒ Object
Public: Returns a Hash with all the flags and their current values.
39 40 41 |
# File 'lib/flagpole.rb', line 39 def to_h @flags end |
#to_i ⇒ Object
Public: Returns the current value of the flag set as an Integer.
32 33 34 35 36 |
# File 'lib/flagpole.rb', line 32 def to_i @flags.each_value.with_index.inject(0) do |flag, (bit, power)| flag | (bit ? 1 : 0) * 2**power end end |
#value_of(flag) ⇒ Object
Public: Find the integer value of a single flag, regardless of whether it is set or not. This value can then be added/substracted from the integer value of this set for low-level manipulation of the flag set.
flag - The name of a flag.
Returns an Integer. Raises ArgumentError if passed a flag that isn’t in the set.
51 52 53 54 |
# File 'lib/flagpole.rb', line 51 def value_of(flag) fail ArgumentError, "#{flag} isn't a valid flag" unless @flags.key?(flag) 2 ** @flags.keys.index(flag) end |