Acts As Bookmarkable Plugin

This is my latest installment on Ruby on Rails plugins. Here is a rails plugin which can help your user manage bookmarks of model records. A bookmarkable model can be any ActiveRecord class so you can use the acts_as_bookmarkable to bookmark other users in a friends list, or bookmark posts in a favorites list, etc. And following the Web 2.0 trends, bookmarks themselves can act as taggable so that you can label bookmarks with tags. You need to install the acts_as_taggable plugin separately, or you can remove one line in the bookmark.rb file to disable tags for bookmarks.

To get started download the plugin from its repository:

script/plugin install http://juixe.com/svn/acts_as_bookmarkable

The installation process will add several ruby files in the vendor/plugins directory. Create a new rails migration and cut and past the following self.up and self.down methods:

def self.up
  create_table :bookmarks, :force => true do |t|
    t.column :title, :string, :limit => 50, :default => ""
    t.column :created_at, :datetime, :null => false
    t.column :bookmarkable_type, :string,
      :limit => 15, :default => "", :null => false
    t.column :bookmarkable_id, :integer, :default => 0, :null => false
    t.column :user_id, :integer, :default => 0, :null => false
  end

  add_index :bookmarks, ["user_id"], :name => "fk_bookmarks_user"
end

def self.down
  drop_table :bookmarks
end

Once you have the acts_as_bookmarkable plugin installed you can make your ActiveRecord classes act as models that can be bookmarkable by calling the acts_as_bookmakble method.

class Post < ActiveRecord::Base
  acts_as_bookmarkable
end

In your controller you can bookmark a post with just a few lines of code:

post = Post.find(params[:id])
bmark = Bookmark.new(:title => someTitle)
post.bookmarks << bmark

And like my other plugins you can assign a bookmark to a user by using the user_id property. Here is an example of how to assign a bookmark to a user model.

bmark = Bookmark.new(:title => someTitle, :user_id => session[:user].id)

You have two options to retrieve the bookmarks for a given user. You can look up all the bookmarks for the given user that are of a certain bookmarkable type. Lets say I want to find all posts that have been bookmarked by the logged in user. To accomplish this I can do the following:

bmarks = Post.find_bookmarks_by_user(session[:user])

If you want all bookmarks for a given user, regardless of the type, then you can use the find_bookmarks_by_user method available from the Bookmark class.

bmarks = Bookmark.find_bookmarks_by_user(session[:user])

Technorati Tags: , , , , , ,