Spam is irritating.

It’s been especially irritating on a blog I created for a Sinatra tutorial hosted on Heroku where the database was filling up so quickly I had to run a script to delete all rows once a week. Ugh.

So, let’s add a captcha to our blog in just five simple steps that will take less than five minutes element in order to help prevent so much spam.



1. Add the following gem to your Gemfile:

gem 'sinatra-captcha'

2. Update your gems and their dependencies:

$ bundle install

3. Update app.rb:


require 'sinatra/captcha'


post "/posts" do
  redirect "posts/create", :error => 'Invalid captcha' unless captcha_pass?
  @post =[:post])
    redirect "posts/#{}", :notice => 'Congrats! Love the new post. (This message will disapear in 4 seconds.)'
    redirect "posts/create", :error => 'Something went wrong. Try again. (This message will disapear in 4 seconds.)'


4. Update the form in the create.erb view:

<form action="/posts" method="post"role="form">
<div class="form-group">
  <label for="post_title">Title:</label>
  <input id="post_title" class="form-control" name="post[title]" type="text" value="<%= @post.title %>" style="width=90%"/>
<div class="form-group">
  <label for="post_body">Body:</label>
  <textarea id="post_body" name="post[body]" class="form-control" rows="10"><%= @post.body %></textarea>
  <div><%= captcha_image_tag %></div>
  <%= captcha_answer_tag %>
<button type="submit" class="btn btn-success">Submit</button>

5. Preview locally before updating Heroku:

$ ruby app.rb

Navigate to http://localhost:4567/posts/create and you should see:



From now on to post a new post, visitors have to complete the word verification. Keep in mind that this won’t completely halt all spam - but it will greatly reduce it.