Skip to content

Instantly share code, notes, and snippets.



Created Nov 12, 2011
What would you like to do?
controller helpers for URLs
# I'm looking for URL helpers that allow me to generate URLs from within the controller.
# All controllers inherit from a common base:
class UsersController < ApplicationController
# This is an API, not a web site: there are no views. Instead, controller methods
# use ApplicationController#render_result() to format the result in the requested
# format (we support several reply formats, for user convenience).
UsersController < ApplicationController
def index
result = do_stuff()
# Within ApplicationController#render_result(), I want to compose URLs that are based
# in part on the actual, concrete controller class name. The URLs point to the on-line
# documentation for the resource:
ApplicationController << ActionController::Base
def render_result(result, status=200)
result['links'] ||= {}
result['links'].merge!( { :rel => 'help',
:href => "/1/doc/#{self.class.to_s.snakecase[/(.*)_controller/, 1]}" } )
respond_to do |format|
format.json { render :json => result, :status => status }
format.xml { render :xml => result, :status => status }
# The above works, but generates only a relative URL. I'd like an absolute URL, like
# The schema might, under various assumptions, but http or https;
# the host name might be or several other possibilities;
# the help url has "/doc" interpolated into the base URL for the resource.
# That is, "GET .../1/users" shows the list of users, while
# "GET .../1/doc/users" shows the documentation for the various users methods.
# Is there some link_to or url_for or something like that that will do this?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment