How to use url helpers in lib modules, and set host for multiple environments

前端 未结 4 627
情深已故
情深已故 2020-12-25 14:43

In a Rails 3.2 app I need to access url_helpers in a lib file. I\'m using

Rails.application.routes.url_helpers.model_url(model)
<
4条回答
  •  粉色の甜心
    2020-12-25 15:20

    This is a problem that I keep running into and has bugged me for a while.

    I know many will say it goes against the MVC architecture to access url_helpers in models and modules, but there are times—such as when interfacing with an external API—where it does make sense.

    And now thanks to this great blog post I've found an answer!

    #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
    

    I can now call the following in any model, module, class, console, etc

    UrlGenerator.new.models_url
    

    Result!

提交回复
热议问题