Rails中会自动引用一些文件,例如再Controller中引用Model等是自动发生的,如果再Rails项目中加入一个新的文件夹怎么引用其中的代码呢?
1.新建文件夹 daigong
2.在 config/application.py中修改
告诉rails自动加载daigong目录下的module
3.因为在rails中使用库,就要按照rails的方式来建立文件夹,这个应该是说是特性呢,还是应该说麻烦 - -#
这个详细解答为:
[url]
http://stackoverflow.com/questions/4074830/adding-lib-to-config-autoload-paths-in-rails-3-does-not-autoload-my-module
[/url]
Hmm, I discovered an interesting thing. In order for Rails to auto load my class, the class name should be compliant to the file name and the folder structure. For example, if I want to have Google module autoloaded, I must placed it inside google.rb, directly under /lib (incase I specify autoload from /lib). If I want to auto load Google::Docs, then I either place it inside google.rb or google/docs.rb
其实rails中的意思是和java的包的概念差不多
再daigong文件夹下建立lib.rb那么里面的代码必须是 module Lib ** end 也就是说必须lib.rb文件中模块名字叫 Lib,这样rails才会自动加载(需要再文件头部include 模块名字),如果是文件夹形式
daigong/one/two.rb 那么模块名字module One::Two
4.现在再Controll和helper里面的就自动引用了Model
include 模块名字,一定要再头部加
1.新建文件夹 daigong
2.在 config/application.py中修改
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(#{config.root}/daigong)
告诉rails自动加载daigong目录下的module
3.因为在rails中使用库,就要按照rails的方式来建立文件夹,这个应该是说是特性呢,还是应该说麻烦 - -#
这个详细解答为:
[url]
http://stackoverflow.com/questions/4074830/adding-lib-to-config-autoload-paths-in-rails-3-does-not-autoload-my-module
[/url]
Hmm, I discovered an interesting thing. In order for Rails to auto load my class, the class name should be compliant to the file name and the folder structure. For example, if I want to have Google module autoloaded, I must placed it inside google.rb, directly under /lib (incase I specify autoload from /lib). If I want to auto load Google::Docs, then I either place it inside google.rb or google/docs.rb
其实rails中的意思是和java的包的概念差不多
再daigong文件夹下建立lib.rb那么里面的代码必须是 module Lib ** end 也就是说必须lib.rb文件中模块名字叫 Lib,这样rails才会自动加载(需要再文件头部include 模块名字),如果是文件夹形式
daigong/one/two.rb 那么模块名字module One::Two
4.现在再Controll和helper里面的就自动引用了Model
include 模块名字,一定要再头部加