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.

Monday, March 24, 2008

Vik's Rbot Presentation

Slides for Vik's rbot presentation can be found here. Other points Vik covered out loud, but aren't in the slides:

Installation:
  • Not at 1.0 yet (<1.0>
  • Don't use 0.9.10, use the version in git (but 0.9.10 works for me)

Plugin Example:
  • Notice the call to an external app
  • The format maps named parameters to ordered parameters
  • You can also map different function names

But What Can I Do:
  • They didn't take full advantage of their plugin-based design
  • Admin features should be in a plugin
  • Logging should be in a plugin
  • IRC connection should be in a plugin, so that we could also use other
  • services (AIM)
  • There is room for rbot competition in the Ruby world
  • rbot is still better than Eggdrop

Meeting Notes, 3/20/2008

We had an especially informative meeting on Thursday, March 20. Three presentations to the group, in chronological order:
  1. Vik on rbot, a Ruby IRC bot library
  2. Josh on domain-specific languages in Ruby
  3. Jason on regular expressions in Ruby
Next meeting will be Thursday, April 17. Thanks again to ITT Tech for providing the meeting space -- the quality of the rooms and projectors is great.

Friday, November 16, 2007

November 15 Meeting Notes

Presentation was by Josh on Google Maps On Rails In Fifteen Minutes - see post below. By unanimous decision, the third Thursday of the month was selected for future meetings to avoid conflicts with the Central PA Linux Users Group. Next meeting will be December 20th at ITT Tech in the Rossmoyne business park on Rte 15 in Mechanicsburg. Bring a laptop, a friend to convert, and $5 for pizza. See everyone there.

Google Maps On Rails In Fifteen Minutes

First Things First:
  1. Get yourself a Google Maps API Key
  2. Create a Rails app - rails vacation - and configure your database setup.
  3. Get the Cartographer plugin - download zip of plugin with my edits; unzip into vendor/plugins, move cartographer.yml into config
  4. Get the Geokit plugin - script/plugin install svn://rubyforge.org/var/svn/geokit/trunket
  5. Copy/paste your API Key into cartographer.yml and environment.rb
Model:

We're going to use just one model in this app, called Spot (as in "vacation spot"), and it's going to be very simple. It will have just an address, a description (to display when a user clicks the map marker), and the fields that Geokit requires to store its location. The migration looks like this:

create_table :spots do |t|
t.column :address, :string
t.column :description, :string
t.column :lat, :float
t.column :lng, :float
end

In the model, we only need one line, which tells Geokit to automatically geocode (i.e., ask Google where the Lat and Lng are for a given street address) each object upon creation:

auto_geocode => true

Controller:

Our controller will need methods for two views -- index, for the front-facing page of our app, and create, which will parse the form for a new vacation spot and redirect the user back to the index. In the index, we need to accomplish three things: find all our vacation spots (line 2), set up the map (lines 3-6), and add a marker for each spot to the map (lines 7-9):

def index
@spots = Spot.find(:all)
@map = Cartographer::Gmap.new("spots")
@map.zoom = :bound
@map.controls = [ :small, :scale ]
@map.debug = true
@spots.each do |spot|
@map.markers << name =""> "spot_" + spot.id.to_s, :position => [spot.lat, spot.lng], :info_window => spot.description)
end
end

In our second step, setting up the map, we first declare an instance variable to represent the map in Cartographer which we'll pass into the view. In the Gmap.new method, we pass an argument "spots" that corresponds to the name of the div in our view that will be replaced by the map. The next three lines set up options for the map -- :bound tells it to automatically zoom out to show all the markers, we add the Google Maps small arrow control and the scale control, and we set debug to true so the Javascript Cartographer puts in the page is nicely-formatted and we can look at it later.

Finally, we cycle through all the Spots found and instantiate new Gmarkers for them and add them to the map. In order to correctly attach the info_windows to each marker, we need to give them all unique names -- using the id of each is a good way to ensure uniqueness when you're only working with one model.

The create method will be much simpler.

def create
@spot = Spot.create(params[:spot])
redirect_to :action => "index"
end

We simply use the built-in Rails convenience method to create a model from a form_for in our view (don't forget, Geokit is automatically geocoding our Spots for us!), then send the user straight back to the index to see the results.

View:

Our view is just one page called index.rhtml -- a title, the map, and a form to add a new spot. Inside the head element, we need to call <%= Cartographer::Header.header_for(request) %> so that the Javascript libraries from Google are loaded. The rest of the page will look like this:


<h1>Where I Went On Vacation</h1>
<hr />
<%= @map.to_html(true) %>
<div id="spots" style="width: 600px; height: 400px;"></div>
<hr />
<h2>Add New Vacation Spot</h2>
<% form_for :spot, :url => { :action => :create } do |f| %>
<p>Address:
<%= f.text_field :address %></p>
<p>Description:
<%= f.text_field :description %></p>
<p><%= submit_tag "Add Spot" %></p>
<% end %>


The to_html(true) method inserts the Javascript needed to draw our @map that we instantiated in the controller. The div where we want the map has to have an id corresponding to the one we gave to @map. Finally, our new spot form is the simple Rails form_for with just a text box for each user-entered field in our model.

Finishing Up:

Run your database migration, start your app, browse to localhost:3000/spot/index and enter yourself a vacation spot. That's it!

Resources: