Ragav Y
Ragav Y

Reputation: 1872

uninitialized constant Recaptcha (NameError) while using recaptcha gem for rails app

I'm working on a Rails 5.0.3 app (with Ruby 2.4.1) and am trying to install a Recaptcha v2 feature on the contact us form on my site.

I am getting the following error:-

/config/initializers/recaptcha.rb:1:in `<top (required)>': uninitialized constant Recaptcha (NameError)
    from /home/[$user]/.rvm/gems/ruby-2.4.1/gems/railties-5.0.3/lib/rails/engine.rb:648:in `block in load_config_initializer'

To implement the feature I followed the documentation for the recaptcha gem here https://github.com/ambethia/recaptcha

In my gemfile I have:-

gem 'dotenv-rails', require: 'dotenv/rails-now'
gem 'recaptcha', require: 'recaptcha/rails'

In my .env file (which is in the root folder) I have this:-

RECAPTCHA_SITE_KEY= xxxxxxxxxxxxxxxxxxxxxxxxxx
RECAPTCHA_SECRET_KEY= xxxxxxxxxxxxxxxxxxxxxxxxx

And I have this in the config/initializers/recaptcha.rb:-

Recaptcha.configure do |config|
  config.site_key  = ENV['RECAPTCHA_SITE_KEY']
  config.secret_key = ENV['RECAPTCHA_SECRET_KEY']
end

In the view I have this:-

    .
    .
    .
    <%= f.label :content %>
    <%= f.text_area :content, class: 'form-control' %>
    <br>
    <%= recaptcha_tags %>
    <br>
    <div class="actions">
      <%= f.submit "Send", class: "btn btn-primary center-block" %>
    </div>
  <% end %>
  .
  .
  .

In my controller I have this:-

  def create
    @message = Message.new(message_params)
    if !verify_recaptcha(model: @message) && @message.valid?
    .
    .
    .

As I can see from the error, the initializer isn't loading. I am not an expert on initializers so I have no clue as to how they are loaded or what I need to do to get them to load.

Upvotes: 1

Views: 1210

Answers (1)

radha
radha

Reputation: 478

But you dont need a gem. You render the recaptcha like this 1) import the Google script

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

2) put a div with the proper class inside the form you are interest like this

<form action="?" method="POST">
      <div class="g-recaptcha" data-sitekey="
<%=Rails.secrets.recaptcha_key%>"></div>
      <br/>
      <input type="submit" value="Submit">
</form>

Then to validate in your controller, just make a post request

if valid_captcha?(params['g-recaptcha-response']) && @user.save

where

def valid_captcha?(recaptcha_response)
    return true if Rails.env.test?

    HTTParty.post(
      Rails.application.secrets.recaptcha_url,
      body: {
        secret: Rails.application.secrets.recaptcha_secret_key,
       response: recaptcha_response
    })["success"]
end

Upvotes: 3

Related Questions