How to simulate Java-like annotations in ruby?
(We\'ll I have the answer, generalizing http://bens.me.uk/2009/java-style-annotations-in-ruby)
My requirement is
On a page I display a list of all instance_methods for a Class ABC, and there should be a 1 line description too with every method
Now I don' know if it is just me or storing the descriptions for all those methods with their names in a new table in the DB sounds "Super LAME"
Answer is - "Annotations"
Here's how I did it -
Class abc.rb
class Abc
extend Annotations
create_annotation("_annotation")
_annotation({:description=>"Info e-mail address"})
def info_email
APP_CONFIG['info_email']
end
_annotation({:description=>"Location of order"})
def location
unless self.order.blank?
@location ||= self.order.location.description
end
end
VIEW methods_list.html.erb
<% default_description = "Description not specified" %>
<% Abc.instance_methods.each do |method| %>
<%= (Abc.annotations[method.to_sym].present?
?
(Abc.annotations[method.to_sym][:_annotation][:description].blank?
? default_description :
Abc.annotations[method.to_sym][:_annotation][:description])
: default_description) %>
<% end %>
Hope it helps!