Dynamically adding instance methods for fun and profit
Here’s an easy way to dynamically add methods to instances of an object for fun and profit. In this case, I had a collection of ‘taggings’ which is a binding between a user and a tag. I wanted to get a count of taggings per tag (so how many users are tagged as a particular tag). Rather than defining another relationship on my model that would hit the database again for this info, I decided to simply calculate it on the app side, and dynamically define a tagged_count method on each tag:
self.friend_taggings.group_by(&:tag).collect do |tag,tagged|
returning(tag){tag.meta_def(:tagged_count) {tagged.count}}
end
end
This code assumes you’re using why_’s metaid.rb metaprogramming aid which simplifies metaprogramming by giving you nice methods for accessing an object’s metaclass (a.k.a eigenclass, singleton class) and defining methods therein.










No Comments Yet