Acts As Commentable Plugin
I am happy to announce that I have released the acts_as_commentable plugin, my first Ruby on Rails plugin. The Acts As Commentable plugin allows for comments to be added to your Rails ActiveRecord classes.
To install the Acts As Commentable plugin run the following command:
script/plugin install http://juixe.com/svn/acts_as_commentable
The installation process will add several ruby scripts 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 :comments, :force => true do |t| t.column :title, :string, :limit => 50, :default => "" t.column :comment, :string, :default => "" t.column :created_at, :datetime, :null => false t.column :commentable_id, :integer, :default => 0, :null => false t.column :commentable_type, :string, :limit => 15, :default => "", :null => false t.column :user_id, :integer, :default => 0, :null => false end add_index :comments, ["user_id"], :name => "fk_comments_user" end def self.down drop_table :comments end
Once you have installed the plugin you can start using it in your ActiveRecord class simply by calling the acts_as_commentable method.
class Post < ActiveRecord::Base acts_as_commentable end
To add a comment to a post object you can do the following:
comment = Comment.new(:title => titleStr, :comment => commentStr) logger << "COMMENT #{comment.comment}\n" post.comments << comment
Or you could have use the add_comment method on post.
post.add_comment comment
You can also use the post’s comments property to read all comments for the given post. Once a comment has been added to a post you can always reference the post object using the comment’s commentable property.
comment.commentable # references the post
One note, the default implementation of Acts As Commentable requires you to use a user model to link all comments to a user. This requirement can easily be removed or enhanced in the Comment class. But if you have a user model you can retrieve all comments for a user by executing the following statement:
comments = Comment.find_comments_by_user(userInstance)
If you want to retrieve only the comments for a user for a particular model you can do something like:
postComments = Post.find_comments_by_user(userInstance)
If you have any comments, questions, and/or suggestions please don’t hesitate to drop me a line.