I’ve finally got some time to work on my blog application. I always wanted to remove duplicate code for comment management from the post controller and photo controller. So today I sat down and extracted common code form both controllers and “CommentController” was born.
Here is the code if you are curious.
class CommentController < ApplicationController
include Akismet
def add_comment
if request.post?
params[:comment][:ip_address] = request.remote_ip
comment = Comment.new(params[:comment])
commentable_type = find_commentable_type(
comment.commentable_type,
comment.commentable_id)
if comment.valid?
params[:comment][:is_spam] =
comment_is_spam?(comment)
commentable_type.comments.create(params[:comment])
end
end
count = comment.errors.count
unless count == 0
flash[:errors] = comment.errors.full_messages.join('|')
end
redirect_to_commentable_type(commentable_type)
end
def delete_comment
if request.post?
comment = Comment.find(params[:id])
comment.destroy
end
redirect_to_commentable_type(
find_commentable_type(comment.commentable_type,
params[:commentable_id].to_i))
end
def comment_report_spam
comment = Comment.find(params[:id])
comment.is_spam = true
comment.save
submit_spam(:comment_author => comment.author_name,
:comment_content => comment.comment,
:user_ip => comment.ip_address,
:user_agent => request.user_agent,
:referer => request.env['HTTP_REFERER'])
redirect_to_commentable_type(
find_commentable_type(comment.commentable_type,
comment.commentable_id))
end
protected
def comment_is_spam?(comment)
is_spam?(:comment_author => comment.author_name,
:comment_content => comment.comment,
:user_ip => comment.ip_address,
:user_agent => request.user_agent,
:referrer => request.env['HTTP_REFERER'])
end
private
def find_commentable_type(commentable_type, commentable_id)
case commentable_type
when Post.class_name
result = Post.find(commentable_id)
when Photo.class_name
result = Photo.find(commentable_id)
else
throw "Wrong commentable type"
end
result
end
def redirect_to_commentable_type(commentable_type)
case commentable_type.class.class_name
when Post.class_name
redirect_to article_comments_url(commentable_type)
when Photo.class_name
redirect_to :action => "show_comments",
:controller => "photo",
:id => commentable_type
else
throw "Wrong commentable type"
end
end
def article_comments_url(post)
"#{article_url(:year => post.created_on.year,
:month => post.created_on.month,
:day => post.created_on.day,
:permalink => post.permalink)
}#comment_form"
end
end
Posted in Rails,
0 Comments
Comments
COMMENTS ARE DISABLED

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