Rails3 加载自定义Lib库

Rails中会自动引用一些文件,例如再Controller中引用Model等是自动发生的,如果再Rails项目中加入一个新的文件夹怎么引用其中的代码呢?

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 模块名字,一定要再头部加
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值