Skip to content

Instantly share code, notes, and snippets.

@coop
Last active December 24, 2015 09:09
Show Gist options
  • Save coop/6775161 to your computer and use it in GitHub Desktop.
Save coop/6775161 to your computer and use it in GitHub Desktop.

Accessing routes outside controllers

Accessing the router outside of the controller context can be a real pain especially if you need access to _url helpers. It is even more difficult if you want to pass the router as an argument to a method or class. We had come up with a few different solutions but so far this has been the most reliable.

Accessing the routes in a class

ENV['SOME_URL'] = 'http://my.url.com'

class MyClassThatHasAccessToRoutes
  include AppRoutes
end

my_class = MyClassThatHasAccessToRoutes.new
my_class.root_path # => '/'
my_class.root_url  # => 'http://my.url.com/'

Passing the router as an argument

ENV['SOME_URL'] = 'http://my.url.com'

class MyClassWithARouter
  def initialize router = AppRouter.new
    @router = router
  end
  
  def path
    @router.root_path
  end
  
  def url
    @router.root_url
  end
end

my_class = MyClassWithARouter.new
my_class.path # => '/'
my_class.url  # => 'http://my.url.com/'
class AppRouter
include AppRoutes
end
module AppRoutes
extend ActiveSupport::Concern
included do
include Rails.application.routes.url_helpers
default_url_options.merge!(
host: app_uri.host,
protocol: app_uri.scheme
)
end
module ClassMethods
def app_uri
@app_uri ||= URI ENV.fetch('SOME_URL')
end
def app_uri= new_uri
@app_uri = new_uri
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment