Skip to content

Commit

Permalink
no longer pollute object namespace with Object#to_enum_sym
Browse files Browse the repository at this point in the history
  • Loading branch information
lwe committed Jan 14, 2012
1 parent ab74414 commit 4185186
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 46 deletions.
6 changes: 1 addition & 5 deletions lib/simple_enum.rb
Expand Up @@ -13,7 +13,6 @@
require 'active_support'

require 'simple_enum/enum_hash'
require 'simple_enum/object_support'
require 'simple_enum/validation'

require 'active_support/deprecation'
Expand Down Expand Up @@ -231,7 +230,7 @@ def self.#{attr_name}_for_select(attr = :key, &block)
prefix = options[:prefix] && "#{options[:prefix] == true ? enum_cd : options[:prefix]}_"

values.each do |k,code|
sym = k.to_enum_sym
sym = EnumHash.symbolize(k)

define_method("#{prefix}#{sym}?") do
code == read_attribute(options[:column])
Expand Down Expand Up @@ -267,9 +266,6 @@ def human_enum_name(enum, key, options = {})
end
end

# Tie stuff together and load translations if ActiveRecord is defined
Object.send(:include, SimpleEnum::ObjectSupport)

# include in AR
ActiveRecord::Base.send(:include, SimpleEnum) if defined?(ActiveRecord)
# load MongoID support
Expand Down
34 changes: 22 additions & 12 deletions lib/simple_enum/enum_hash.rb
@@ -1,14 +1,23 @@
module SimpleEnum

# Internal hash class, used to handle the enumerations et al.
# Works like to original +Hash+ class, but with some added value,
# like access to
# like access to
#
#
#
class EnumHash < ::ActiveSupport::OrderedHash

# Converts an entity to a symbol, uses to_enum_sym, if possible.
def self.symbolize(sym)
return sym.to_enum_sym if sym.respond_to?(:to_enum_sym)
return sym.to_sym if sym.respond_to?(:to_sym)
return sym.name.to_s.parameterize('_').to_sym if sym.respond_to?(:name)
sym.to_param.to_sym unless sym.blank?
end

def initialize(args = [])
super()

@reverse_sym_lookup = {}
@sym_value_lookup = {}

Expand All @@ -21,26 +30,27 @@ def initialize(args = [])
ary.each { |e| set_value_for_reverse_lookup(e[0], e[1]) }
end
end

def default(k = nil)
@sym_value_lookup[k.to_enum_sym] if k
@sym_value_lookup[EnumHash.symbolize(k)] if k
end

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
sym = EnumHash.symbolize(symbol)
if @sym_value_lookup.has_key?(sym)
return @reverse_sym_lookup[sym] if args.first
self[symbol]
else
super
end
end

private
def set_value_for_reverse_lookup(key, value)
sym = key.to_enum_sym
sym = EnumHash.symbolize(key)
self[key] = value
@reverse_sym_lookup[sym] = key
@sym_value_lookup[sym] = value
end
end
end
end
29 changes: 0 additions & 29 deletions test/object_support_test.rb

This file was deleted.

0 comments on commit 4185186

Please sign in to comment.