【问题标题】:How do I invoke a helper module method from a Rails service?如何从 Rails 服务调用辅助模块方法?
【发布时间】:2016-07-04 02:33:58
【问题描述】:

我使用的是 Rails 4.2.3。我已经创建了 app/helpers/webpage_helper.rb

require "resolv-replace.rb"
require 'open-uri'

module WebpageHelper

  def self.max_attempts
    3
  end

  def get_url(url)
    attempts = 0
    begin
      doc = Nokogiri::HTML(open(url))
    rescue => e
      puts "error: #{e.message}"
      attempts = attempts + 1
      if attempts <= max_attempts
        retry
      end
    end
  end

end

如何从另一个 Rails 服务(不是控制器)调用这个辅助方法?我试过了

doc = WebpageHelper::get_url(url)

但这会导致错误“未定义的方法 `get_url' for WebpageHelper:Module”。

【问题讨论】:

    标签: ruby-on-rails-4 methods module helper


    【解决方案1】:

    有两种方法可以做到这一点。要么包含 WebpageHelper,然后只使用 get_url 方法,要么将 get_url 定义为模块函数。

    module WebpageHelper
    
      ...
    
      module_function :get_url
    end
    
    and then you can use this like
    WebpageHelper.get_url
    

    【讨论】:

      猜你喜欢
      • 2011-03-27
      • 2016-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-05
      • 2012-02-13
      • 1970-01-01
      • 2017-05-01
      相关资源
      最近更新 更多