Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a route helper method from a file in the lib directory?

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?

like image 841
alf Avatar asked Feb 15 '12 16:02

alf


People also ask

What is helper method in ruby?

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 .

What are URL helpers?

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 .

What is path helper in Rails?

Searching For Missing Route Values Under the hood, Rails path helpers use ActionDispatch to generate paths that map to routes defined in routes.

Why helper is used in Rails?

Basically helpers in Rails are used to extract complex logic out of the view so that you can organize your code better.


1 Answers

@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
like image 79
burtlo Avatar answered Oct 20 '22 00:10

burtlo