Search code examples
ruby-on-railsrubyvalidationruby-on-rails-4recaptcha

Working example of new recaptcha with Rails?


Does anyone have a working example of Google's new recaptcha in a Rails app? Every guide I try to follow is either unclear or incomplete, and seems to use a different method.

Hand-rolled code would be preferable.


Work in Progress:

config/environments/production.rb:

  #...
  recaptcha_public_key= "[PUBLIC KEY]"
  recaptcha_private_key= "[PRIVATE KEY]"
end

config/environments/development.rb:

  #...
  recaptcha_public_key= "[PUBLIC KEY]"
  recaptcha_private_key= "[PRIVATE KEY]"
end

config/initializers/recaptcha.rb

Recaptcha.configure do |config|
  config.public_key  = Rails.application.secrets.recaptcha_public_key
  config.private_key = Rails.application.secrets.recaptcha_secret_key
  config.api_version = 'v2'
end

Solution

  • Using the recaptcha gem, I created an example that uses the check box method.

    Code available here: https://github.com/sunnyrjuneja/recaptcha_example

    The commits should be very easy to follow. Let me know if you have anymore questions.

    Example application here: https://recaptcha-checkbox.herokuapp.com/

    UPDATE:

    Here's a way to do it without secrets.yml.

    Change your initializer to look like this:

    Recaptcha.configure do |config|
      config.public_key  = ENV['RECAPTCHA_PUBLIC_KEY']
      config.private_key = ENV['RECAPTCHA_PRIVATE_KEY']
    end
    

    In your development or production environment, add this to your .bashrc or .zshrc.

    export RECAPTCHA_PUBLIC_KEY="YOURPUBLICKEY"
    export RECAPTCHA_PRIVATE_KEY="YOURPRIVATEKEY"
    

    If you're using Heroku to deploy do this on your command line:

    heroku config:set RECAPTCHA_PUBLIC_KEY="YOURPUBLICKEY"
    heroku config:set RECAPTCHA_PRIVATE_KEY="YOURPRIVATEKEY"
    

    UPDATE 2:

    The recaptcha gem now uses different method names for setting the keys.

    Recaptcha.configure do |config| config.site_key = 'YOUR_SITE_KEY_HERE' config.secret_key = 'YOUR_SECRET_KEY_HERE' # Uncomment the following line if you are using a proxy server: # config.proxy = 'http://myproxy.com.au:8080' end