Nice programing

Rails 모듈에서 URL 도우미에 액세스하는 방법

nicepro 2020. 11. 19. 21:59
반응형

Rails 모듈에서 URL 도우미에 액세스하는 방법


기능이있는 모듈이 있습니다. /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

어떤 상황에서도 작동합니다. includeurl_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

카피 바라 테스트의 또 다른 예

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 '

참고URL : https://stackoverflow.com/questions/6074831/how-to-access-url-helper-from-rails-module

반응형