Created
November 12, 2011 00:24
-
-
Save jrep/1359766 to your computer and use it in GitHub Desktop.
controller helpers for URLs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
… | |
end | |
# 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() | |
render_result(result) | |
end | |
… | |
end | |
# 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]}" } ) | |
end | |
respond_to do |format| | |
format.json { render :json => result, :status => status } | |
format.xml { render :xml => result, :status => status } | |
end | |
end | |
# The above works, but generates only a relative URL. I'd like an absolute URL, like | |
# https://api.codesion.com/1/doc/organizations | |
# The schema might, under various assumptions, but http or https; | |
# the host name might be api.codesion.com 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