Class: Edgarj::EnumCache
- Inherits:
-
Object
- Object
- Edgarj::EnumCache
- Includes:
- Singleton
- Defined in:
- lib/edgarj/enum_cache.rb
Overview
build map: value -> label on-the-fly
Instance Method Summary collapse
-
#initialize ⇒ EnumCache
constructor
A new instance of EnumCache.
-
#label(rec, attr, enum = nil) ⇒ Object
return label of ‘rec.attr’, where attr is enum value.
-
#stat ⇒ Object
return statistic information of hit, out, out_of_enum.
Constructor Details
#initialize ⇒ EnumCache
Returns a new instance of EnumCache.
6 7 8 9 10 11 |
# File 'lib/edgarj/enum_cache.rb', line 6 def initialize @enum_map = {} # for stat @hit = @out = @out_of_enum = 0 end |
Instance Method Details
#label(rec, attr, enum = nil) ⇒ Object
return label of ‘rec.attr’, where attr is enum value.
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/edgarj/enum_cache.rb', line 14 def label(rec, attr, enum = nil) if !enum enum = rec.class.const_get(attr.to_s.camelize) raise(NameError, "wrong constant name #{attr}") if !enum end if !@enum_map[enum] @enum_map[enum] = {} end value = rec.attributes[attr.to_s] if label = @enum_map[enum][value] @hit += 1 label else member = enum.constants.detect{|m| enum.const_get(m) == value } @enum_map[enum][value] = if member @out += 1 rec.class.human_const_name(enum, member) else @out_of_enum += 1 '??' end end end |
#stat ⇒ Object
return statistic information of hit, out, out_of_enum.
42 43 44 |
# File 'lib/edgarj/enum_cache.rb', line 42 def stat [@hit, @out, @out_of_enum] end |