Skip to content

Commit 7057ccf

Browse files
committed
Directly delegate constantize to Object.const_get
All the complexity of that method was to work around various problems caused by Ruby's constant lookup semantic as well as the classic autoloader shortcommings. Now that Rails require Ruby 2.7 I don't think we need anything more than just `Object.const_get`. ```ruby require 'benchmark/ips' require 'active_support/all' module Foo module Bar module Baz end end end def patched_constantize(name) Object.const_get(name) end Benchmark.ips do |x| x.report('orig') { ActiveSupport::Inflector.constantize("Foo::Bar::Baz") } x.report('patched') { patched_constantize("Foo::Bar::Baz") } x.compare! end ``` ``` Warming up -------------------------------------- orig 69.668k i/100ms patched 391.385k i/100ms Calculating ------------------------------------- orig 705.027k (± 1.9%) i/s - 3.553M in 5.041486s patched 3.935M (± 1.1%) i/s - 19.961M in 5.072912s Comparison: patched: 3935235.5 i/s orig: 705027.2 i/s - 5.58x (± 0.00) slower ```
1 parent fe8f47b commit 7057ccf

File tree

1 file changed

+1
-32
lines changed
  • activesupport/lib/active_support/inflector

1 file changed

+1
-32
lines changed

activesupport/lib/active_support/inflector/methods.rb

Lines changed: 1 addition & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -277,38 +277,7 @@ def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
277277
# NameError is raised when the name is not in CamelCase or the constant is
278278
# unknown.
279279
def constantize(camel_cased_word)
280-
if camel_cased_word.blank? || !camel_cased_word.include?("::")
281-
Object.const_get(camel_cased_word)
282-
else
283-
names = camel_cased_word.split("::")
284-
285-
# Trigger a built-in NameError exception including the ill-formed constant in the message.
286-
Object.const_get(camel_cased_word) if names.empty?
287-
288-
# Remove the first blank element in case of '::ClassName' notation.
289-
names.shift if names.size > 1 && names.first.empty?
290-
291-
names.inject(Object) do |constant, name|
292-
if constant == Object
293-
constant.const_get(name)
294-
else
295-
candidate = constant.const_get(name)
296-
next candidate if constant.const_defined?(name, false)
297-
next candidate unless Object.const_defined?(name)
298-
299-
# Go down the ancestors to check if it is owned directly. The check
300-
# stops when we reach Object or the end of ancestors tree.
301-
constant = constant.ancestors.inject(constant) do |const, ancestor|
302-
break const if ancestor == Object
303-
break ancestor if ancestor.const_defined?(name, false)
304-
const
305-
end
306-
307-
# owner is in Object, so raise
308-
constant.const_get(name, false)
309-
end
310-
end
311-
end
280+
Object.const_get(camel_cased_word)
312281
end
313282

314283
# Tries to find a constant with the name specified in the argument string.

0 commit comments

Comments
 (0)