我在模型中遇到了以下问题:
class Search < ActiveRecord::Base
#search different system user by dn
def self.gets(sys, dn)
sys.constantize.search(dn)
end
end
我可以看到目的是将不同的模型名称作为 sys
传递,并在这些特定模型中通过 dn
进行搜索。然而,我在 Ruby 中搜索 constantize
并没有看到任何关于这种用法的详细解释。
最佳答案
Rails documentation (因为 constantize 是一种 Rails 方法)说:
Tries to find a constant with the name specified in the argument string.
例如,如果您的应用程序中有一个名为 Foo 的模型,那么您可以将 constantize 方法应用于一个字符串,该字符串包含确切的单词 Foo,它会为您提供一个具有该模型的新对象。请注意,这必须大写,因为 Rails 会与您的模型一起工作,如果您做了错误的引用,那么您将得到一个 NameError
错误:
NameError: wrong constant name foo
它是如何做到的?,如果您转到方法定义,或者如果您使用该方法出现错误,您将看到源指向 activesupport-5.1.5/lib/active_support/inflector/methods.rb:269:in 'const_get'
,这是方法定义和错误源。
在方法根据接收到的参数在内部处理的情况之间,您将看到 Object.const_get(string)
这是 Ruby(纯)处理“constantiz-ation”的方式",这与做
Object.const_get('Foo') # Foo(...)
Object.const_get('foo') # NameError: wrong constant name foo
如果想实现这个方便的方法,您可以看看 Gavin Miller 的 post从几年前开始。
关于ruby-on-rails - ruby on rails 常量化方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49184301/