如何从Rails模型中正确包含模块和调用模块功能? [英] How do I properly include a module and call module functions from my Rails model?

查看:74
本文介绍了如何从Rails模型中正确包含模块和调用模块功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,一个Show和一个模块实用程序

I have a model, Show and a module Utilities

class Show < ActiveRecord::Base
  include Utilities

   ...
   def self.something
      fix_url("www.google.com")
   end
end

我的实用程序文件在lib/utilities.rb

My Utilities file is in lib/utilities.rb

module Utilities
  def fix_url(u)
    !!( u !~ /\A(?:http:\/\/|https:\/\/)/i ) ? "http://#{u}" : u
  end
end

但是,当我在show类中调用Rails时,它会为"fix_url"抛出NoMethodError.在模型中包含模块时,我需要做些不同的事情吗?

But Rails is throwing a NoMethodError for "fix_url" when I call it in my show class. Do I have to do something different when including a module in my model?

谢谢!

推荐答案

尝试通过extend而不是include注入该mixin.基本上,因为您是从类方法中调用mixin方法,但是包含mixin仅使其实例方法可用.您可以使用扩展样式获取类方法.

try injecting that mixin via the extend instead of include. Basically, because you are calling the mixin method from a class method, but including a mixin only makes its instance methods available. You can use the extend style to get class methods.

搜索Ruby是否包含并扩展以了解它们之间的差异.一种常见的模式是像这样:

Search around for Ruby include and extend to learn the differences. A common pattern is to do it like here:

http://www.dcmanges.com/blog/27

在使用included钩子混合实例和类级别方法的地方.

Where you use the included hook to mixin both instance and class level methods.

@Tony-这对我有用

@Tony - this works for me

class User < ActiveRecord::Base
  extend Utilities
  def self.test
    go()
  end
end

module Utilities
 def go
  puts "hello"
 end
end

From console:

>> User.test
hello
=> nil

在任何时候我都不必使用self.

At no point do I have to explicitly call a method with self.

这篇关于如何从Rails模型中正确包含模块和调用模块功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆