skwpspace yan pritzker’s home on the web

skwpspace is Yan Pritzker's home on the web

Blog :: Photography :: About Me

TwitterCounter for @skwp

Get the news feed
Get updates by email
Follow me on twitter

hello, i'm yan

This blog is about startups, blogging, Ruby On Rails, virtualization and cloud computing, photography, customer service, marketing, ux and design, git, and lots more.

Top Posts

planypus

I'm the founder of Planypus, the place to share your plans!

cohesiveft

Accessible, manageable, virtualized application stacks ready to download or deploy to the cloud!

flickr

it's hailing in san franciscojessatianalyndaBird in the handkerimodeldanielle pettee and models-4449

Archives

Contact

Reach me at yan at pritzker.ws

Posted
22 September 2006 @ 3pm

Tagged
RubyOnRails

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:

def friend_tags
  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


There are no comments yet. You could be the first!

Leave a Comment

vi mode in rails console Multi column lists using in_groups_of