Nikolay's Blog

Rails Using Urls Outside of Controllers and Views

Cover Image for Rails Using Urls Outside of Controllers and Views
  • Created at:

Sometimes you want to access routes outside controllers or views. For example in services:

module UserService
  def text
    "Users are there: #{users_url}" # raises error
  end
end

Urls can be accessed through url_helpers object

Rails.application.routes.url_helpers.users_url

Use Routes in Class

Just include url_helpers

class UserService
  include Rails.application.routes.url_helpers

  def text
    "Users are there: #{users_url}"
  end
end

UserService.new.text #=> "Users are there: http://example.com/users"

ArgumentError Missing host exception

Sometimes it raises missing :host error

ArgumentError (Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true)

Just add :host manually

# it can be moved to ./config/development.rb file
Rails.application.routes.default_url_options = { host: 'example.com' }

Rails.application.routes.url_helpers.users_url
#=> 'http://example.com/users'

Or pass :host as argument directly

Rails.application.routes.url_helpers.users_url(host: 'example.com')

Use Routes in Module

Just extend module with url_helpers

module UserService
  extend Rails.application.routes.url_helpers

  def text
    "Users are there: #{users_url}"
  end
end

UserService.text #=> "Users are there: http://example.com/users"

I hope it helped you to have deal with routes