Class: Bitty::BitProxy
- Inherits:
-
Object
- Object
- Bitty::BitProxy
- Defined in:
- lib/bitty/bit_proxy.rb
Class Attribute Summary collapse
-
.column ⇒ Object
Returns the value of attribute column.
Class Method Summary collapse
Instance Method Summary collapse
- #[](key) ⇒ Object
- #[]=(key, val) ⇒ Object
-
#initialize(*args) ⇒ BitProxy
constructor
this will be redefined in self.column=.
- #set!(value) ⇒ Object
Constructor Details
#initialize(*args) ⇒ BitProxy
this will be redefined in self.column=
15 16 |
# File 'lib/bitty/bit_proxy.rb', line 15 def initialize(*args) end |
Class Attribute Details
.column ⇒ Object
Returns the value of attribute column.
54 55 56 |
# File 'lib/bitty/bit_proxy.rb', line 54 def column @column end |
Class Method Details
.bit_names=(names) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/bitty/bit_proxy.rb', line 23 def bit_names=(names) @power2 = {} p = 1 names.each do |name| n = name.to_sym if @power2.include?(n) raise ArgumentError, "Bit name #{n} repeated more that once!" else @power2[n] = p p <<= 1 end end @power2.each do |name, bitmask| inv = ~bitmask class_eval <<-RUBY def #{name} (value & #{bitmask}) != 0 end alias #{name}? #{name} def #{name}=(val) self.value = Bitty.true?(val) ? (value | #{bitmask}) : (value & #{inv}) end RUBY end end |
.named_scope(*args) ⇒ Object
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
# File 'lib/bitty/bit_proxy.rb', line 78 def named_scope(*args) bits = args. args.each { |arg| bits[arg] = true } masks = [0, 0] bits.each do |name, val| mask = power2(name) raise ArgumentError, "invalid bit name #{name}" unless mask masks[Bitty.true?(val) ? 1 : 0] |= mask end cond = [nil, nil] if masks[0] != 0 cond[0] = "#{column} & #{masks[0]} = 0" end if masks[1] != 0 cond[1] = "#{column} & #{masks[1]} = #{masks[1]}" end { :conditions => cond.compact.map { |c| "(#{c})" } * ' AND ' } end |
.power2(name) ⇒ Object
19 20 21 |
# File 'lib/bitty/bit_proxy.rb', line 19 def power2(name) @power2[name.to_sym] end |
Instance Method Details
#[](key) ⇒ Object
105 106 107 108 109 110 111 112 113 |
# File 'lib/bitty/bit_proxy.rb', line 105 def [](key) bitmask = power2(key) if bitmask (value & bitmask) != 0 else nil end end |
#[]=(key, val) ⇒ Object
115 116 117 118 119 120 |
# File 'lib/bitty/bit_proxy.rb', line 115 def []=(key, val) bitmask = power2(key) raise ArgumentError, "unknown bitname: #{key}" unless bitmask self.value = Bitty.true?(val) ? (value | bitmask) : (value & ~bitmask) end |
#set!(value) ⇒ Object
122 123 124 125 126 127 128 129 130 131 132 133 |
# File 'lib/bitty/bit_proxy.rb', line 122 def set!(value) case value when Array value.each { |key| self[key] = true } when Hash value.each { |key, val| self[key] = val } when Fixnum self.value = value else raise ArgumentError, "invalid value (must be Array/Hash/Fixnum)" end end |