This post originated from an RSS feed registered with Ruby Buzz
by Aslak Hellesøy.
Original Post: Annotations in Ruby
Feed Title: Aslak Hellesøy's uncommon sense
Feed URL: http://aslakhellesoy.com/rss
Feed Description: Ruby-related blog posts from Aslak Hellesøy
A couple of days ago I wished there was a way to use annotations in Ruby. I'm writing a Ruby on Rails application that renders a lot of objects in HTML. Many of these objects are "editable" via the web interface, and in order to make it easier for the user, I wanted the web interface to have both an explanatory text and a HTML tooltip for each object's field.
Because I like simple things I also like to keep things in one place (I don't want to maintain this metadata in a separate RHTML template).
Ruby doesn't support annotations out of the box, so I opened up the Class class and added support for annotations. Now I can do:
require 'rscm/annotations'
class EmailSender
ann :description => "IP address of the mail server", :tip => "Use 'localhost' if you have a good box, sister!"
attr_accessor :server
end
The class' annotations can then be accessed like this:
EmailSender.server[:description] # => "IP address of the mail server"
It took the Java community forever to do stuff like this. First a couple of years of XDoclet, then JSR175. And tons of code too. In Ruby it's 1 hour's work and 25 lines of code. Go figure.
For more info see http://rscm.rubyforge.org/classes/Class.html
And oh, here's the code:
class Class
def ann(anns)
@@anns ||= {}
def self.method_missing(sym, *args) #:nodoc:
@@anns[sym]
end
$attr_anns ||= {}
$attr_anns.merge!(anns)
end
alias old_attr_reader attr_reader #:nodoc:
def attr_reader(*syms) #:nodoc:
syms.each do |sym|
@@anns[sym] = $attr_anns
end
$attr_anns = nil
old_attr_reader(*syms)
end
def attr_accessor(*syms) #:nodoc:
attr_reader(*syms)
attr_writer(*syms)
end
end
UPDATE (March 3 2005) An updated version of the Ruby annotations library is available at rafb