class Edgarj::EnumCache

build map: value -> label on-the-fly

Public Class Methods

new() click to toggle source
# File lib/edgarj/enum_cache.rb, line 6
def initialize
  @enum_map = {}

  # for stat
  @hit = @out = @out_of_enum = 0
end

Public Instance Methods

label(rec, attr, enum = nil) click to toggle source

return label of ‘rec.attr’, where attr is enum value.

# 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() click to toggle source

return statistic information of hit, out, out_of_enum.

# File lib/edgarj/enum_cache.rb, line 42
def stat
  [@hit, @out, @out_of_enum]
end