Class: SimpleEnum::EnumHash
- Inherits:
-
ActiveSupport::OrderedHash
- Object
- ActiveSupport::OrderedHash
- SimpleEnum::EnumHash
- Defined in:
- lib/simple_enum/enum_hash.rb
Overview
Internal hash class, used to handle the enumerations et al. Works like to original Hash class, but with some added value, like access to
Instance Method Summary collapse
- #default(k = nil) ⇒ Object
-
#initialize(args = []) ⇒ EnumHash
constructor
A new instance of EnumHash.
- #method_missing(symbol, *args) ⇒ Object
Constructor Details
#initialize(args = []) ⇒ EnumHash
Returns a new instance of EnumHash.
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/simple_enum/enum_hash.rb', line 9 def initialize(args = []) super() @reverse_sym_lookup = {} @sym_value_lookup = {} if args.is_a?(Hash) args.each { |k,v| set_value_for_reverse_lookup(k, v) } else ary = args.send(args.respond_to?(:enum_with_index) ? :enum_with_index : :each_with_index).to_a unless args.first.is_a?(ActiveRecord::Base) or args.first.is_a?(Array) ary = args.map { |e| [e, e.id] } if args.first.is_a?(ActiveRecord::Base) ary ||= args ary.each { |e| set_value_for_reverse_lookup(e[0], e[1]) } end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(symbol, *args) ⇒ Object
29 30 31 32 33 34 35 36 |
# File 'lib/simple_enum/enum_hash.rb', line 29 def method_missing(symbol, *args) if @sym_value_lookup.has_key?(symbol.to_enum_sym) return @reverse_sym_lookup[symbol.to_enum_sym] if args.first self[symbol] else super end end |
Instance Method Details
#default(k = nil) ⇒ Object
25 26 27 |
# File 'lib/simple_enum/enum_hash.rb', line 25 def default(k = nil) @sym_value_lookup[k.to_enum_sym] if k end |