簡體   English   中英

如何從rails模塊訪問URL幫助程序

[英]How to access URL helper from rails module

我有一個帶功能的模塊。 它位於/lib/contact.rb中:

module Contact
  class << self
    def run(current_user)
      ...
    end
  end
end

我想訪問模塊中的'users_path'之類的URL幫助程序。 我怎么做?

在您的模塊中,只需執行:

 include Rails.application.routes.url_helpers

對url_helpers的委派似乎比將整個模塊包含到模型中要好得多

delegate :url_helpers, to: 'Rails.application.routes' 
url_helpers.users_url  => 'www.foo.com/users'

參考

以下是我在沒有include任何上下文中的方式

routes = Rails.application.routes.url_helpers
url = routes.some_path

這適用於任何情況。 如果您嘗試include url_helpers - 請確保您在正確的位置執行此操作,例如此方法有效

module Contact
  class << self
    include Rails.application.routes.url_helpers
  end
end

這不起作用

module Contact
  include Rails.application.routes.url_helpers
  class << self
  end
end

Capybara測試的另一個例子

feature 'bla-bla' do
  include Rails.application.routes.url_helpers
  path = some_path #unknown local variable some_path
end

而現在是正確的

include Rails.application.routes.url_helpers
feature 'bla-bla' do
  path = some_path #this is ok
end

我一直在努力解決幫助者從默認控制器和堆棧( default_url_options等)所期待的細節,並且不想對主機進行硬編碼。

我們的URL幫助程序由我們的漂亮模塊提供,當然:

include Rails.application.routes.url_helpers

但是按原樣包含它,並且(1)幫助器將查找default_url_options ,並且(2)將不知道請求主機和請求。

主機部分來自控制器實例的url_options 因此,我將控制器上下文傳遞給我以前的模塊,現在是一個類:

class ApplicationController
  def do_nifty_things
    HasAccessToRoutes.new(self).render
  end
end

class HasAccessToRoutes
  include Rails.application.routes.url_helpers
  delegate :default_url_options, :url_options, to: :@context

  def initialize(context)
    @context = context
  end

  def render
    nifty_things_url
  end
end

可能不適合所有情況,但在實現一種自定義渲染器時它對我很有用。

以任何方式:

  • 如果要無縫訪問默認URL選項或請求的主機,則需要傳遞控制器/請求上下文
  • 如果你只需要路徑,沒有主機,並且不關心url選項,你可以制作一些虛擬方法。
delegate :url_helpers, to: 'Rails.application.routes' 
url_helpers.users_url  => 'www.foo.com/users'

對Augustin Riedinger來說,委托代碼需要引用url_helpers(復數),否則你就得到了

未定義的方法`url_helper'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM