Class: DecimalSupport::FlagValues
- Inherits:
-
Object
- Object
- DecimalSupport::FlagValues
- Defined in:
- lib/decimal/support.rb
Overview
This class assigns bit-values to a set of symbols so they can be used as flags and stored as an integer.
fv = FlagValues.new(:flag1, :flag2, :flag3)
puts fv[:flag3]
fv.each{|f,v| puts "#{f} -> #{v}"}
Defined Under Namespace
Classes: InvalidFlagError, InvalidFlagTypeError
Instance Method Summary collapse
-
#[](flag) ⇒ Object
Get the bit-value of a flag.
- #all_flags_value ⇒ Object
-
#each(&blk) ⇒ Object
Return each flag and its bit-value.
-
#initialize(*flags) ⇒ FlagValues
constructor
The flag symbols must be passed; values are assign in increasing order.
- #size ⇒ Object
Constructor Details
#initialize(*flags) ⇒ FlagValues
The flag symbols must be passed; values are assign in increasing order.
fv = FlagValues.new(:flag1, :flag2, :flag3)
puts fv[:flag3]
20 21 22 23 24 25 26 27 28 |
# File 'lib/decimal/support.rb', line 20 def initialize(*flags) @flags = {} value = 1 flags.each do |flag| raise InvalidFlagType,"Flags must be defined as symbols or classes; invalid flag: #{flag.inspect}" unless flag.kind_of?(Symbol) || flag.instance_of?(Class) @flags[flag] = value value <<= 1 end end |
Instance Method Details
#[](flag) ⇒ Object
Get the bit-value of a flag
31 32 33 34 35 |
# File 'lib/decimal/support.rb', line 31 def [](flag) v = @flags[flag] raise InvalidFlagError, "Invalid flag: #{flag}" unless v v end |
#all_flags_value ⇒ Object
50 51 52 |
# File 'lib/decimal/support.rb', line 50 def all_flags_value (1 << size) - 1 end |
#each(&blk) ⇒ Object
Return each flag and its bit-value
38 39 40 41 42 43 44 |
# File 'lib/decimal/support.rb', line 38 def each(&blk) if blk.arity==2 @flags.to_a.sort_by{|f,v|v}.each(&blk) else @flags.to_a.sort_by{|f,v|v}.map{|f,v|f}.each(&blk) end end |
#size ⇒ Object
46 47 48 |
# File 'lib/decimal/support.rb', line 46 def size @flags.size end |