module TurboGoogleRecaptcha::ViewExt

Public Instance Methods

include_recaptcha_js() click to toggle source
# File lib/turbo_google_recaptcha/view_ext.rb, line 5
def include_recaptcha_js
  generate_recaptcha_callback + javascript_include_tag("https://www.google.com/recaptcha/api.js?render=#{TurboGoogleRecaptcha.site_key}&onload=newGoogleRecaptchaCallback", defer: true, 'data-turbolinks-track': 'reload')
end
recaptcha_action(action) click to toggle source
# File lib/turbo_google_recaptcha/view_ext.rb, line 9
def recaptcha_action(action)
  id = "turbo_google_recaptcha_token_#{SecureRandom.hex(10)}"
  hidden_field_tag(
    'new_recaptcha_token',
    nil,
    readonly: true,
    'data-google-recaptcha-action' => action,
    id: id
  )
end

Private Instance Methods

generate_recaptcha_callback() click to toggle source
# File lib/turbo_google_recaptcha/view_ext.rb, line 22
def generate_recaptcha_callback
  javascript_tag %(
    function newGoogleRecaptchaCallback () {
      grecaptcha.ready(function () {
        var elements = document.querySelectorAll('[data-google-recaptcha-action]')
        Array.prototype.slice.call(elements).forEach(function (el) {
          var action = el.dataset.googleRecaptchaAction
          if (!action) return
          grecaptcha
            .execute("#{TurboGoogleRecaptcha.site_key}", { action: action })
            .then(function (token) {
              el.value = token
            })
        })
      })
    }
  )
end