Likeable: Love your Objects with Redis
03 Nov 2011This is a re-post of an article I wrote for Gowalla’s Engineering Blog. You can view the original article here.
Likeable is a new open-source Ruby library that we built here at Gowalla to power all of the “loves” on stories, comments, highlights and photos that you see. It’s built on top of Redis to be extremely simple, isolated and fast. Likeable plays well with ActiveRecord objects, but can be used with any Ruby object that implements an #id
method.
To see it in action, head over to my Gowalla profile and love the first thing you see. Immediately you’ll see the heart change colors and the love count increase by one. If you click on that number you’ll see everyone who has loved that object.
This might seem trivial at first glance. But consider that dozens of elements on the page must pull this information: how many people have loved it, whether the viewer has loved it, and (on some pages) which of your friends have loved it. Using Redis allows us to stay simple, flexible and fast.
The Code
Let’s say we’ve got a comment made on a recent Gowalla story.
@comment = Comment.last
@comment.like_count #=> 0
If our user wants to like this comment, he can do so with ease:
@user = User.find_by_username('schneems')
@user.like! @comment
And that’s it. The comment now reports the details of the like.
@comment.like_count #=> 1
@comment.likes #=> [#<Likeable::Like ... >]
@comment.likes.last.user #=> #<User username: "schneems" ...>
The Install
For Rails apps, Likeable is extremely simple to set up.
First, add Likeable to your Gemfile
:
gem 'likeable'
Set up your Redis connection in (e.g.) config/initializers/likeable.rb
:
Likeable.setup do |likeable|
likeable.redis = Redis.new
end
Next, add the Likeable::UserMethods
module to your User
model:
class User < ActiveRecord::Base
include Likeable::UserMethods
end
Finally, add the Likeable
module to any model you want to be likeable:
class Comment < ActiveRecord::Base
include Likeable
end
To learn more, check out the Likeable source, look at the example Rails app or watch the Likeable screencast.
Contributing
We’d love to get contributions to Likeable. If you want it to do something it doesn’t already, open an issue on GitHub. Or, if you feel so inclined, create a patch and submit a pull request.