How to access URL helper from rails module

前端 未结 5 942
感情败类
感情败类 2020-12-25 10:42

I have a module with a function. It resides in /lib/contact.rb:

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


        
5条回答
  •  再見小時候
    2020-12-25 11:26

    Here is how I do it in any context without include

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

    That works in any context. If you're trying to include url_helpers - make sure you are doing that in the right place e.g. this works

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

    and this does not work

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

    One more example with Capybara tests

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

    and now the right one

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

提交回复
热议问题