Class: Incline::BitEnum

Inherits:
ConstantEnum show all
Defined in:
lib/incline/bit_enum.rb

Instance Attribute Summary

Attributes inherited from ConstantEnum

#name, #value

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from ConstantEnum

#initialize

Constructor Details

This class inherits a constructor from Incline::ConstantEnum

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *a, &b) ⇒ Object

Enable bit checking and bit setting/clearing.

For instance, with a constant FLAG_1, this enables :flag_1? and :flag_1=(true|false).



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/incline/bit_enum.rb', line 42

def method_missing(m,*a,&b)
  name = m.to_s
  if name[-1] == '?'
    name = name[0...-1].upcase.to_sym
    if constants(false).include?(name)
      v = const_get(name)
      return (value & v) == v
    end
  elsif name[-1] == '='
    name = name[0...-1].upcase.to_sym
    if constants(false).include?(name)
      v = const_get(name)
      if a[0]
        @value |= v
      else
        @value &= ~v
      end
      @name = self.class.name_for(@value)
      return a[0]
    end
  end
  super m, *a, &b
end

Class Method Details

.name_for(value, set_nil = false) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/incline/bit_enum.rb', line 4

def self.name_for(value, set_nil = false)
  ret = values.select{|(v,_)| v == value}.map{|(_,k)| k}
  return ret unless ret.blank?
  
  ret = []
  
  values.each do |(v,k)|
    if v.power_of_2? && value >= v
      if set_nil
        ret << k || v.to_s
      else
        ret << k
      end
      value -= v
    end
  end
  
  if value > 0
    ret << set_nil ? value.to_s : nil
  end
  
  ret.sort
end

.named?(value) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
31
32
# File 'lib/incline/bit_enum.rb', line 28

def self.named?(value)
  nm = name_for(value, false)
  return false if nm.blank?
  nm.select{|v| v.nil?}.blank?
end

Instance Method Details

#to_sObject



34
35
36
# File 'lib/incline/bit_enum.rb', line 34

def to_s
  self.class.name_for(value, true).join(' | ')
end