ActsAsCommentable is an acts_as plugin that is used to enable commenting on your ActiveRecord models. The plugin is intentionally simple because I wanted this plugin to be as customizable as possible without the user ever touching the plugins code.
script/plugin install http://svn.munitic.com.hr/plugins/acts_as_commentable
In the model you want to be commentable add acts_as_commentable
class Post < ActiveRecord::Base
acts_as_commentable
# or if you want to add some methods to the comments association
# acts_as_commentable do
# def find_by_date(date, options = {})
# with_scope :find => options do
# # CODE GOES HERE
# end
# end
# end
...
end
Create the comments table. The only requirement are the commentable_type and commentable_id fields. On my blog I have something like this
create_table "comments", :force => true do |t|
t.column "author_name", :string
t.column "comment", :text
t.column "ip_address", :string
t.column "is_spam", :boolean, :default => false
t.column "commentable_type", :string
t.column "commentable_id", :integer
t.column "created_on", :datetime
end
If you want to add methods to the comment model you can do this using mixins. Here is what I use:
module Mixins; module Comment; end; end;
module Mixins::Comment::Spamable
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def count_by_spam(spam)
count :all, :conditions => ['is_spam = ?', spam]
end
def count_by_spam_and_commentable(spam, type, id)
count :all, :conditions => ['is_spam = ? and
commentable_type = ? and commentable_id = ?',
spam, type, id]
end
def find_for_post_comments_feed(options = {})
with_scope :find => options do
find :all, :conditions => ['is_spam = ? and
commentable_type = ?', false, Post.class_name],
:order => 'created_on DESC'
end
end
end
end
Comment.send :include, Mixins::Comment::Spamable
# If you want to add validation you can do that like this:
Comment.send :validates_presence_of, :author_name, :comment
I have this code in lib/mixins/spammable.rb and i require it in the config/environment.rb file. After that i have these methods in the comment model.
UPDATE: I’ve moved the code to google. So now you can get the latest version with:
script/plugin install http://acts-as-commentable.googlecode.com/svn/trunk
Enjoy!
Posted in Rails, 0 Comments
Comments
COMMENTS ARE DISABLED

Full name: Ivica Munitic
Age: 28
Profession: Developer
Email: ivica@munitic.com.hr