Posts from April 2008
I really love the old books at Linderman, I’ll have to go back and take more shots some time.
A little while back, I complained about WordPress’ handling of URLs without “http://”. While it turns out WP actually handles these correctly, it brings up the question on how to handle a user’s inputted data. It’s always important to format or sanitize incoming data, and for items like URLs, which have a well-defined format, it’s really easy to do. Here’s how to do it in Rails.
One of the great things about Ruby is the way it treats just about anything as a method, so if I call
link.url = "http://website.com", it’s actually calling the method
Link#url= with the parameter of “http://website.com”. So, to intercept incoming data, I just overwrite the default url= method in my Link model:
class Link < ActiveRecord def url=(new_url) if new_url[0..6] != 'http://' new_url = 'http://' + new_url end super(new_url) end end
So, now, when I set the url, it’s automatically formatted correctly. Some may advocate putting something like this in a before_save callback, but personally, I like to make sure the data is always correct, even when it hasn’t yet been saved.