Subscribe to the MPC blog rss feed feed-icon-14x14
 

Incorporating Akismet



Posted on 03:25PM on 10/23/2008
Tags: Akismet, blog

I decided today that I wanted to incorporate Akismet functionality into this site. I do currently use Captchas as a way to ensure that only real comments get submitted, but Akismet seems to provide an extra layer of security. Plus, I was bored ;)

What is Akismet? According to the site:

"When a new comment, trackback, or pingback comes to your blog it is submitted to the Akismet web service which runs hundreds of tests on the comment and returns a thumbs up or thumbs down."

Pretty cool.

There are plenty of plugins and libraries for Akismet, but not one specifically for Sinatra, which is what this site is built on. I decided to use Ruby Akismet API, by David Czarnecki. It's a nice, simple, small library that does what I need. Basically, it posts data to the Akismet API and returns true if the comment has been evaluated as spam.

So my controller action looks more or less like this now:

  post "/blog/create/comment/:slug" do
    @post = Post.find_by_slug(params["slug"])
    raise_post_not_found(params["slug"]) unless @post
    @comment = Comment.new(params[:post])
    errors = @comment.validation_errors || []
    unless Captcha.valid?
      errors << "Invalid captcha. Please try again." 
    end
    unless AkismetWrapper.valid?(@comment, {
        :ip => user_ip, :referrer => user_referrer, :user_agent => user_agent}
      )
      errors << "Your comment appears to be spam. Please try again."
    end
    if errors.empty?
      @comment.save
      redirect "/blog"
    else
      @errors = errors.join("<br />")
      erb :new_comment
  end

I created a module called AkismetWrapper simply because I didn't want to use the Akismet API class directly from my controller code. Additionally, it'll help me with testing since I can just stub the method on the simple wrapper module.

So now I've got a dual layer of protection: Captchas and Akismet. Is it necessary? I don't know. Did I learn something from it? You bet! That's all I really set out to do anyway.

1 Comment (Show) (Comments are closed for this post)

 
Please note that I am currently unavailable for any large, long term work.