Skip to content

Commit

Permalink
Change Inflector#constantize to use eval instead of const_get
Browse files Browse the repository at this point in the history
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@3049 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information
seckar committed Nov 16, 2005
1 parent c98011b commit 1cc8ab8
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
2 changes: 2 additions & 0 deletions activesupport/CHANGELOG
@@ -1,5 +1,7 @@
*1.2.3* (November 7th, 2005)

* Change Inflector#constantize to use eval instead of const_get. [Nicholas Seckar]

* Fix const_missing handler to ignore the trailing '.rb' on files when comparing paths. [Nicholas Seckar]

* Define kernel.rb methods in "class Object" instead of "module Kernel" to work around a Windows peculiarity [Sam Stephenson]
Expand Down
8 changes: 5 additions & 3 deletions activesupport/lib/active_support/inflector.rb
Expand Up @@ -142,9 +142,11 @@ def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
end

def constantize(camel_cased_word)
camel_cased_word.split("::").inject(Object) do |final_type, part|
final_type = final_type.const_get(part)
end
raise NameError, "#{camel_cased_word.inspect} is not a valid constant name!" unless
camel_cased_word.split("::").all? { |part| /^[A-Z]\w*$/ =~ part }

camel_cased_word = "::#{camel_cased_word}" unless camel_cased_word[0, 2] == '::'
Object.module_eval(camel_cased_word, __FILE__, __LINE__)
end

def ordinalize(number)
Expand Down
5 changes: 5 additions & 0 deletions activesupport/test/inflector_test.rb
Expand Up @@ -276,6 +276,11 @@ def test_constantize
assert_equal Ace::Base::Case, Inflector.constantize("Ace::Base::Case")
assert_equal InflectorTest, Inflector.constantize("InflectorTest")
assert_raises(NameError) { Inflector.constantize("UnknownClass") }
assert_raises(NameError) { Inflector.constantize("An invalid string") }
end

def test_constantize_doesnt_look_in_parent
assert_raises(NameError) { Inflector.constantize("Ace::Base::InflectorTest") }
end

def test_ordinal
Expand Down

0 comments on commit 1cc8ab8

Please sign in to comment.