Class: BitMask::Field
- Inherits:
-
Object
- Object
- BitMask::Field
- Defined in:
- lib/bit_mask/field.rb
Instance Attribute Summary collapse
-
#name ⇒ Object
readonly
Returns the value of attribute name.
-
#options ⇒ Object
readonly
Returns the value of attribute options.
Instance Method Summary collapse
- #bits ⇒ Object
- #default ⇒ Object
- #from_i(value) ⇒ Object
-
#initialize(name, opts) ⇒ Field
constructor
A new instance of Field.
- #null ⇒ Object
- #to_bin(value) ⇒ Object
- #values ⇒ Object
Constructor Details
#initialize(name, opts) ⇒ Field
Returns a new instance of Field.
5 6 7 8 9 10 11 |
# File 'lib/bit_mask/field.rb', line 5 def initialize(name, opts) @name = name @options = opts if !values.is_a?(Integer) && !values.is_a?(Array) raise "#{values.class} is an invalid class for values." end end |
Instance Attribute Details
#name ⇒ Object (readonly)
Returns the value of attribute name.
2 3 4 |
# File 'lib/bit_mask/field.rb', line 2 def name @name end |
#options ⇒ Object (readonly)
Returns the value of attribute options.
3 4 5 |
# File 'lib/bit_mask/field.rb', line 3 def @options end |
Instance Method Details
#bits ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/bit_mask/field.rb', line 13 def bits @bits ||= if [:bits] [:bits] elsif values.kind_of?(Integer) && values < 0 -1 else if [:limit] max_number = [:limit] elsif values.is_a?(Integer) max_number = values elsif values.is_a?(Array) max_number = values.size end max_number += 1 if null (Math.log(max_number) / Math.log(2)).ceil end end |
#default ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/bit_mask/field.rb', line 42 def default @default ||= if null nil elsif values.kind_of? Integer 0 elsif values.respond_to? :first values.first elsif values.respond_to? :defaults values.defaults end end |
#from_i(value) ⇒ Object
67 68 69 70 71 72 73 74 75 76 |
# File 'lib/bit_mask/field.rb', line 67 def from_i(value) value -= 1 if self.null if self.null && value == -1 value = nil elsif self.values.respond_to?(:at) value = self.values.at(value) end value end |
#null ⇒ Object
38 39 40 |
# File 'lib/bit_mask/field.rb', line 38 def null [:null] end |
#to_bin(value) ⇒ Object
55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/bit_mask/field.rb', line 55 def to_bin(value) if self.null && value.nil? value = 0 elsif self.values.respond_to? :index value = self.values.index(value) value += 1 if self.null end value = value.to_s(2) value = value.rjust(self.bits,'0') if self.bits > 0 value end |
#values ⇒ Object
34 35 36 |
# File 'lib/bit_mask/field.rb', line 34 def values [:values] end |