about summary refs log tree commit diff stats
path: root/app/controllers/comments_controller.rb
blob: a444dbafdd13753157da051b94b00c014f2a107c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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

        if @comment.status == :published
          CommentMailer.with(comment: @comment).new_comment_email.deliver_later
        else
          CommentMailer.with(comment: @comment).new_pending_comment_email.deliver_later
        end
      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