Rails - 访问模型中的模块方法

时间:2013-08-08 10:47:38

标签: ruby-on-rails-3 module

所以,我已经读完了所有内容:

但我不能让它发挥作用。这是我的情况:

我的calc_distance(place1, place2)模型有places方法和属性User,我想在calc_total_distance模型中定义方法User

我希望通过calc_distance lib访问Utils方法,而不是在使用时加载整个util。

/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模块......

2 个答案:

答案 0 :(得分:2)

如果你不想做mixin,只是为了定义一些Utils的方法,那么你可以在模块级别定义方法(使用self。前缀):

module Utils
  def self.calc_distance a, b
    # Blah blah blah
  end
end

然后以这种方式打电话:

Utils.calc_distance(place1, place2)

而不是

Utils::calc_distance(place1, place2)

答案 1 :(得分:0)

class Athlete < ActiveRecord::Base
  include Utils
  def get_total_distance
    # Blah blah blah
    dist += calc_distance(place1, place2)
    # Blah blah blah
  end
end
相关问题