Though I’m very new to Rails, I’ve been chugging along with the
tutorials that are available. They’re quite fun. While building my own
web apps, I’ve decided to use a different URL scheme than the default
controller/action/id scheme Rails defaults to.
For instance, I’m working on cloning a small section of YubNub, where
URLs like http://yubnub.org/parser/parse?command=gim+dogs redirects
the user to a Google Images query for dogs. When most of the activity
will take place in one action (parse), there doesn’t seem to be a good
way for Rails to delegate actions. Because there is no real route for
Rails to follow to get to the many actions (command=google,
command=yahoo, command=ask), I can’t just tell the various methods to
render or redirect_to those actions. Also, any HTML forms I have in
place cannot access an action unless there is a route to it. This
makes sense–how else would the browser know which URL to send the
form information?
Another example would be creating a wiki, where the default action
should be to show a wiki page, but routing overrides any request to do
things like http://site.com/wiki/SomePage?action=edit or
http://site.com/wiki/SomePage?action=delete.
Currently, I’ve been cutting and pasting the code from action methods
such as show, edit, destroy, and so on into one really big index
method. I know this is slipping into spaghetti code territory, so I
want to know if there is a better way of doing this.
Initial code as routed for controller/action/id URL scheme
http://site.com/parser/command.
def index
respond_to { |format| format.html }
end
def google
respond_to { |format| format.html }
end
def yahoo
respond_to { |format| format.html }
end
def ask
respond_to { |format| format.html }
end
Code after combining into single action for use with URL scheme
http://site.com/?command=.
def index
case params[:command]
when “google”
respond_to { |format| format.html } # google stuff…
when “yahoo”
respond_to { |format| format.html } # yahoo stuff …
when “ask”
respond_to { |format| format.html| # ask stuff …
end
end