Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 获取已实现某个方法的所有模型_Ruby On Rails_Object_Methods - Fatal编程技术网

Ruby on rails 获取已实现某个方法的所有模型

Ruby on rails 获取已实现某个方法的所有模型,ruby-on-rails,object,methods,Ruby On Rails,Object,Methods,我有许多使用标准rails模型生成器创建的模型。 一些模型得到了一个名为foo()的方法 有没有一种简单的方法来计算实现了foo()方法的生成模型的所有类名 我的意思是编程,从rails控制器,而不是从控制台对源代码进行grepping。rails没有保存模型的索引,因此您只需浏览应用程序/模型目录即可 下面是一个例子: # Open the model directory models_dir = Dir.open("#{RAILS_ROOT}/app/models") # Walk dir

我有许多使用标准rails模型生成器创建的模型。 一些模型得到了一个名为foo()的方法

有没有一种简单的方法来计算实现了foo()方法的生成模型的所有类名


我的意思是编程,从rails控制器,而不是从控制台对源代码进行grepping。

rails没有保存模型的索引,因此您只需浏览
应用程序/模型
目录即可

下面是一个例子:

# Open the model directory
models_dir = Dir.open("#{RAILS_ROOT}/app/models")

# Walk directory entries
models = models_dir.collect do |filename|
  # Get the name without extension.
  # (And skip anything that isn't a Ruby file.)
  next if not filename =~ /^(.+)\.rb$/
  basename = $~[1]

  # Now, get the model class
  klass = basename.camelize.constantize

  # And return it, if it implements our method
  klass if klass.method_defined? :foo
end

# Remove nils
models.compact!
Rails会在模型和控制器第一次被引用时延迟加载它们。这是使用Ruby的
const_missing
方法完成的,您可以在
active_support/dependencies.rb
中看到ActiveSupport中发生的所有奇迹

要详细说明上面发生的事情,您还需要知道类名和文件名是链接的。Rails期望一个
ThingyBob
模型生活在
ThingyBob.rb
中。在这两个名称之间转换的方法是使用字符串方法
camelize
。(与之相反的是
下划线
方法。)这些字符串扩展也是ActiveSupport的一部分

最后,使用ActiveSupport方法
constantize
,这也是一个字符串扩展,我们将字符串作为常量取消引用。所以基本上是
“ThingyBob”。constantize
与编写
ThingyBob
是一样的;我们只需返回
ThingyBob
类。在上面的示例中,
constantize
也会触发常规依赖项加载魔法

希望这有助于揭开某些事情的神秘面纱。:)