本文介绍了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.

但是,我有一些类层次结构或smth问题。

However, I have some Class hierarchy or smth problem.

从任何控制器,我可以访问 open_flash_chart 作为 OpenFlashChart

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加载过程的一部分。

  • 文件是显式的 require d。如果一个文件是 require d,Ruby会在加载路径中查找整个路径列表,并找到第一种情况,其中 / code> d在加载路径中。您可以通过检查$ 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模块和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 08:48