如何在lib模块中使用url helper,并为多个环境设置host

And*_*vey 21 ruby-on-rails

在Rails 3.2应用程序中,我需要访问lib文件中的url_helpers .我正在使用

Rails.application.routes.url_helpers.model_url(model)
Run Code Online (Sandbox Code Playgroud)

但我得到了

ArgumentError (Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true):
Run Code Online (Sandbox Code Playgroud)

我已经找到了一些关于此的内容,但没有真正解释如何在多种环境中解决这个问题.

即我假设我需要在我的development.rb和production.rb文件中添加一些东西,但是什么?

最近我看到建议使用的答案config.action_mailer.default_url_option,但这不适用于动作邮件.

为多个环境设置主机的正确方法是什么?

And*_*vey 38

这是一个我一直遇到的问题,并且已经让我烦恼了一段时间.

我知道很多人会说它违反了MVC架构来访问模型和模块中的url_helpers,但有时候 - 例如在与外部API接口时 - 它确实有意义.

现在感谢这篇精彩的博文,我找到了答案!

#lib/routing.rb

module Routing
  extend ActiveSupport::Concern
  include Rails.application.routes.url_helpers

  included do
    def default_url_options
      ActionMailer::Base.default_url_options
    end
  end
end

#lib/url_generator.rb

class UrlGenerator
  include Routing
end
Run Code Online (Sandbox Code Playgroud)

我现在可以在任何模型,模块,类,控制台等中调用以下内容

UrlGenerator.new.models_url
Run Code Online (Sandbox Code Playgroud)

结果!


bbo*_*ozo 17

Andy的可爱答案略有改善(至少对我而言)

module UrlHelpers

  extend ActiveSupport::Concern

  class Base
    include Rails.application.routes.url_helpers

    def default_url_options
      ActionMailer::Base.default_url_options
    end
  end

  def url_helpers
    @url_helpers ||= UrlHelpers::Base.new
  end

  def self.method_missing method, *args, &block
    @url_helpers ||= UrlHelpers::Base.new

    if @url_helpers.respond_to?(method)
      @url_helpers.send(method, *args, &block)
    else
      super method, *args, &block
    end
  end

end
Run Code Online (Sandbox Code Playgroud)

以及你使用它的方式是:

include UrlHelpers
url_helpers.posts_url # returns https://blabla.com/posts
Run Code Online (Sandbox Code Playgroud)

或者干脆

UrlHelpers.posts_url # returns https://blabla.com/posts
Run Code Online (Sandbox Code Playgroud)

谢谢安迪!+1


小智 6

在任何模块控制器中使用此字符串来获取应用程序 URL 帮助程序在任何视图或控制器中工作。

include Rails.application.routes.url_helpers
Run Code Online (Sandbox Code Playgroud)

请注意,一些内部模块 url-helper 应该被命名空间。

示例: 根应用程序

路由文件

Rails.application.routes.draw do
get 'action' =>  "contr#action", :as => 'welcome'
mount Eb::Core::Engine => "/" , :as => 'eb'
end
Run Code Online (Sandbox Code Playgroud)

模块 Eb 中的 URL 助手:

users_path
Run Code Online (Sandbox Code Playgroud)

加入include Rails.application.routes.url_helpers控制器contr

所以在那个帮手之后应该是

eb.users_path
Run Code Online (Sandbox Code Playgroud)

所以在 Eb 模块中,您可以使用welcome_path与根应用程序相同的功能!