From 835af696703484208882a70cc5dd47c5838ecf58 Mon Sep 17 00:00:00 2001 From: Star Rauchenberger Date: Thu, 12 Oct 2023 17:10:34 -0400 Subject: Added blog post commenting --- app/controllers/comments_controller.rb | 59 ++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 app/controllers/comments_controller.rb (limited to 'app/controllers') diff --git a/app/controllers/comments_controller.rb b/app/controllers/comments_controller.rb new file mode 100644 index 0000000..60c8f6a --- /dev/null +++ b/app/controllers/comments_controller.rb @@ -0,0 +1,59 @@ +class CommentsController < ApplicationController + def create + @blog = Blog.find_by_slug(params[:slug]) + + raise ActiveRecord::RecordNotFound unless @blog + raise ActiveRecord::RecordNotFound unless @blog.published + + @comment = @blog.comments.new(comment_params) + + unless @comment.valid? + flash.alert = "Error posting comment." + render "blogs/show" + return + end + + akismet_vars = %w{ HTTP_ACCEPT HTTP_ACCEPT_ENCODING } + akismet_params = { + type: "comment", + text: @comment.body, + created_at: DateTime.now, + author: @comment.username, + author_email: @comment.email, + author_url: @comment.website, + post_url: url_for(@comment.blog), + post_modified_at: @comment.blog.updated_at, + referrer: request.referrer, + env: request.env.slice(*akismet_vars) + } + + is_spam, is_blatant = Akismet.check(request.ip, request.user_agent, akismet_params) + + if is_blatant + # I am lying. + flash.notice = "Comment submitted successfully! It will need to be moderated before it shows up on the blog." + else + if is_spam + @comment.status = :pending + flash_message = "Comment submitted successfully! It will need to be moderated before it shows up on the blog." + else + @comment.status = :published + flash_message = "Comment posted successfully!" + end + + if @comment.save + flash.notice = flash_message + else + flash.alert = "Error posting comment." + end + end + + redirect_to @comment.blog + end + + private + + def comment_params + params.require(:comment).permit(:username, :email, :website, :body) + end +end -- cgit 1.4.1