Monday, March 31, 2008

Monkeypatching, Ruby, and Rails

We had a bit of a spirited discussion at the last meeting about the usefulness and desirability of monkeypatching in Ruby, and especially Rails. I had a situation crop up today where the dilemma presented itself again.

One of the nice things about Rails 2.0's RESTful function is the ability to render an object or collection of objects in a number of formats -- like XML, HTML, JSON, etc.:

# GET /agents
# GET /agents.xml
def index
@agents = Agent.find(:all)

respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @agents }
end
end


Another nice thing would be if I could render a collection of objects in, say, CSV format, which would be great for downloading to Excel for business reports.

format.csv { render :csv => @agents }


Rails doesn't have a built-in renderer for CSV. And unfortunately, the renderers are defined as in-line if statements:

if file = options[:file]
render_for_file(file, options[:status], options[:use_full_path], options[:locals] || {})
#...

elsif xml = options[:xml]
response.content_type ||= Mime::XML
render_for_text(xml.respond_to?(:to_xml) ? xml.to_xml : xml, options[:status])

elsif json = options[:json]
json = json.to_json unless json.is_a?(String)
json = "#{options[:callback]}(#{json})" unless options[:callback].blank?
response.content_type ||= Mime::JSON
render_for_text(json, options[:status])


So what to do? The slick Ruby way would be to alias_method :old_render :render, write a new one with the CSV renderer in it. But you're in trouble then if you install someone else's plugin that does the same thing. And since #render is in ActionController::Base, the chances of that are pretty good.

I think probably the way to go here for Rails would be to have a list of formats that it looked for, like this:

elsif format = render_formats.collect {|format| options.include?[format] }


Then you could add to the render_formats array or hash or whatever, and so could everyone else. There's different danger levels of monkeypatching, I think -- concatenating another option to an array has pretty minimal impact, but rewriting a base method of Rails itself can be dicey. I'm not sure if there's a reason I haven't thought of that Rails defines the renderers the way it does -- maybe they don't want to have some gigantic list of every format under the sun end up in the world's Rails codebases, and wanted to deliberately exclude non-XML or JSON formats. But I think there are some design decisions you can make that make monkeypatching more powerful and less dangerous.

No comments: