Rails/lib 模块和 [英] Rails /lib modules and

查看:21
本文介绍了Rails/lib 模块和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 open_flash_chart 插件编写自定义包装器.它放在 /lib 中,并作为模块加载到 ApplicationController 中.

I am writing a custom wrapper for open_flash_chart plugin. It's placed in /lib and load it as a module in ApplicationController.

但是,我有一些类层次结构或某些问题.

However, I have some Class hierarchy or smth problem.

我可以从任何控制器访问 open_flash_chart 函数,如 OpenFlashChartLine

From any controller I can access open_flash_chart functions as OpenFlashChart, Line etc

然而,在/lib模块中的类中,它不起作用!

However, in a class in a /lib module, it doesnt work!

有什么想法吗?

推荐答案

在 Rails 中加载文件有两种方式:

There are two ways that files get loaded in Rails:

  • 它是在自动加载过程中注册的,你引用了一个与文件名对应的常量.例如,如果您有 app/controllers/pages_controller.rb 并引用 PagesController,app/controllers/pages_controller.rb 将自动加载.这发生在加载路径中的预设目录列表中.这是 Rails 的一个特性,不是正常 Ruby 加载过程的一部分.
  • 文件是明确的required.如果文件是 required,Ruby 会查看加载路径中的整个路径列表,并找到 required 的文件在加载路径中的第一种情况.您可以通过检查 $LOAD_PATH($: 的别名)查看整个加载路径.
  • It is registered in the autoload process, and you reference a constant that corresponds to the file name. For instance, if you have app/controllers/pages_controller.rb and reference PagesController, app/controllers/pages_controller.rb will automatically be loaded. This happens for a preset list of directories in the load path. This is a feature of Rails, and is not part of the normal Ruby load process.
  • Files are explicitly required. If a file is required, Ruby looks through the entire list of paths in your load paths, and find the first case where the file you required is in the load path. You can see the entire load path by inspecting $LOAD_PATH (an alias for $:).

因为 lib 在你的加载路径中,你有两个选择:要么用与常量相同的名字命名你的文件,这样当你引用有问题的常量时 Rails 会自动选择它们,或明确要求该模块.

Since lib is in your load path, you have two options: either name your files with the same names as the constants, so Rails will automatically pick them up when you reference the constant in question, or explicitly require the module.

我还注意到您可能对另一件事感到困惑.ApplicationController 不是 系统中的根对象.观察:

I also notice that you might be confused about another thing. ApplicationController is not the root object in the system. Observe:

module MyModule
  def im_awesome
    puts "#{self} is so awesome"
  end
end

class ApplicationController < ActionController::Base
  include MyModule
end

class AnotherClass
end

AnotherClass.new.im_awesome
# NoMethodError: undefined method `im_awesome' for #<AnotherClass:0x101208ad0>

您需要将该模块包含在您想在其中使用它的任何类中.

You will need to include the module into whatever class you want to use it in.

class AnotherClass
  include MyModule
end

AnotherClass.new.im_awesome
# AnotherClass is so awesome

当然,为了能够首先包含模块,您需要使其可用(使用上述任一技术).

Of course, in order to be able to include the module in the first place, you'll need to have it available (using either of the techniques above).

这篇关于Rails/lib 模块和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆