Yan Pritzker photographer, entrepreneur, software engineer, musician, skier

Blog :: Git Workflows Book :: Dotfiles :: Photography :: About Me

TwitterCounter for @skwp

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

hello, i'm yan

I am a photographer, entrepreneur, software engineer, guitarist, climber, and telemark skier

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

Enterprise intelligence with prediction markets

Find out what your team, colleagues and partners really know about the future — and leverage their knowledge to improve business decisions.

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

Archives

Contact

Reach me at yan at pritzker.ws

Dynamically adding instance methods for fun and profit

Posted 22 September 2006 @ 3pm | Tagged RubyOnRails


Submit to HN

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