【发布时间】:2013-08-08 10:47:37
【问题描述】:
所以,我已经阅读了所有内容:
- Best way to load module/class from lib folder in Rails 3?
- Rails doesn't load my module from lib
- Rails /lib modules and
- How to create and use a module using Ruby on Rails 3?
但我不能让它工作。这是我的情况:
我的User 模型有一个calc_distance(place1, place2) 方法和一个属性places,我想在User 模型中定义一个方法calc_total_distance。
我想通过Utils 库访问calc_distance 方法,而不是在使用它时加载整个实用程序。
在/lib/utils.rb
module Utils
def calc_distance a, b
# Blah blah blah
end
end
在/config/application.rb我有:
config.autoload_paths += %W(#{config.root}/lib)
在控制台中,我可以做到
include Utils 然后calc_distance(place1, place2) 它工作。但是Utils::calc_distance(place1 place2) 不行……
额外的问题是我可以这样做吗?
然后在我的User.rb 模型中:
def get_total_distance
# Blah blah blah
dist += calc_distance(place1, place2)
# Blah blah blah
end
回复我undefined method 'include' for #<User:0x00000006368278>
和
def get_total_distance
# Blah blah blah
dist += Utils::calc_distance(place1, place2)
# Blah blah blah
end
回复我undefined method 'calc_distance' for Utils:Module
知道我真的更喜欢第二种方法(据我估计,它不会加载整个 Utils 模块...
【问题讨论】:
-
你可以试试
include Utils到user.rb吗?