How to Access Url Helper from Rails Module

How to access URL helper from rails module

In your module, just perform a :

 include Rails.application.routes.url_helpers

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

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.

After much searching 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!

How do I invoke a helper module method from a Rails service?

There are two ways you can do this. either include WebpageHelper and then just use get_url method or define get_url as a module function.

module WebpageHelper

...

module_function :get_url
end

and then you can use this like
WebpageHelper.get_url

Rails: Check output of path helper from console

You can show them with rake routes directly.

In a Rails console, you can call app.post_path. This will work in Rails ~= 2.3 and >= 3.1.0.



Related Topics



Leave a reply



Submit