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.
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/'
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/'