I need to use the root_url
method from a method defined in a file in the lib
folder. Is that possible?
I tried including this line in my class:
include Rails.application.routes.url_helpers
but this gives me the error
Missing host to link to! Please provide :host parameter or set default_url_options[:host]
Edit: I found out that it works if I first initialize the routes:
def initialize_routes
if Rails.env.development? || Rails.env.test?
Rails.application.routes.default_url_options[:host] = 'localhost:3000'
elsif Rails.env.production?
Rails.application.routes.default_url_options[:host] = 'example.com'
end
end
Is there a better way to accomplish this? Maybe setting the routes in a config file?
A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words .
URL helpers are used in the context of a web request, i.e. within a view or controller. In these cases the host or domain of the request is provided automatically by the application. Outside of this context you'll need to ensure you specify a host for any helpers ending in _url .
Searching For Missing Route Values Under the hood, Rails path helpers use ActionDispatch to generate paths that map to routes defined in routes.
Basically helpers in Rails are used to extract complex logic out of the view so that you can organize your code better.
@JDutil's #3 solution, as mentioned in the comments, is configuring the action mailer and not the router's routes. However, in the configuration you can perform the following:
In config/environments/development.rb
and config/environments/test.rb
:
MyApp::Application.configure do
# other configuration ...
config.after_initialize do
Rails.application.routes.default_url_options[:host] = 'localhost:3000'
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With