Skip to content

Commit

Permalink
ActiveSupport::Dependencies.constantize shortcut for caching named co…
Browse files Browse the repository at this point in the history
…nstant lookups
  • Loading branch information
jeremy committed Jun 6, 2010
1 parent 35ae42b commit fd1a504
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 14 deletions.
11 changes: 11 additions & 0 deletions activesupport/lib/active_support/core_ext/string/conversions.rb
Expand Up @@ -47,4 +47,15 @@ def to_datetime
d[5] += d.pop
::DateTime.civil(*d)
end

# +constantize+ tries to find a declared constant with the name specified
# in the string. It raises a NameError when the name is not in CamelCase
# or is not initialized.
#
# Examples
# "Module".constantize # => Module
# "Class".constantize # => Class
def constantize
ActiveSupport::Inflector.constantize(self)
end
end
11 changes: 0 additions & 11 deletions activesupport/lib/active_support/core_ext/string/inflections.rb
Expand Up @@ -146,15 +146,4 @@ def humanize
def foreign_key(separate_class_name_and_id_with_underscore = true)
ActiveSupport::Inflector.foreign_key(self, separate_class_name_and_id_with_underscore)
end

# +constantize+ tries to find a declared constant with the name specified
# in the string. It raises a NameError when the name is not in CamelCase
# or is not initialized.
#
# Examples
# "Module".constantize # => Module
# "Class".constantize # => Class
def constantize
ActiveSupport::Inflector.constantize(self)
end
end
12 changes: 9 additions & 3 deletions activesupport/lib/active_support/dependencies.rb
Expand Up @@ -484,8 +484,10 @@ def remove_unloadable_constants!
end

class Reference
def initialize(constant, name)
@constant, @name = constant, name
attr_reader :name

def initialize(name, constant = nil)
@name, @constant = name, constant
end

def get
Expand All @@ -498,7 +500,11 @@ def clear!
end

def ref(name)
references[name] ||= Reference.new(Inflector.constantize(name), name)
references[name] ||= Reference.new(name)
end

def constantize(name)
ref(name).get
end

# Determine if the given constant has been automatically loaded.
Expand Down
6 changes: 6 additions & 0 deletions activesupport/test/dependencies_test.rb
Expand Up @@ -446,6 +446,12 @@ def test_references_should_work
end
end

def test_constantize_shortcut_for_cached_constant_lookups
with_loading 'dependencies' do
assert_equal ServiceOne, ActiveSupport::Dependencies.constantize("ServiceOne")
end
end

def test_nested_load_error_isnt_rescued
with_loading 'dependencies' do
assert_raise(MissingSourceFile) do
Expand Down

0 comments on commit fd1a504

Please sign in to comment.