Let's meet on Read more

How to create the Age Gate Page in the Rails App

Average rating: 5
(17 votes)

Thanks! You’ve rated this material!

In this article, you can find information, what is the Age Gate, when you need it, and how to add Age Gate to your Ruby on Rails Application.

What is the Age Gate?

Age Gate is also known as “Adult Verification Systems’’ these are systems used by websites to confirm that users attempting to access their website are legally adults.
The use of the age gates has gained additional popularity with the rise of age-rated video gaming, online sports betting, pornography, firearms, and cannabis websites.

If you plan to create a Ruby on Rails application that has age-rated content, you should have an Adult Verification System, where users must prove their majority.

Our goal is to create the Age Gate in two ways in Rails Application, where users can prove their Age by Clicking on the yes or no buttons, and the second way by their full birth date: year, month, and day.

Let’s begin with the Age Gate that has confirmation yes or no buttons.

Create a Form Object for  Age Gate

Form Object is a handy pattern in rails ecosystem as it can address a variety of issues and antipatterns. For creating Form Object for Age Gate, we will add the ActiveModel::Model module to our class.

A GateForm class can mix in ActiveModel::Model and gain a lot of functionality, including:

  • initialization with a hash of attributes;
  • validation of attributes;
  • presentation of errors.
# frozen_string_literal: true
class GateForm
  include ActiveModel::Model
  attr_accessor :choice
  validate :user_under_age?

  def initialize(params = {})
    @choice = params[:choice]
  end

  private

  def user_under_age?
    return if casted_choice == true

    errors.add(:choice, 'You are not old enough to view this content')
  end

  def casted_choice
    ActiveModel::Type::Boolean.new.cast(@choice)
  end
end

Method user_under_age? will responding for validating user input, if the user press the “No” button, the user should receive a message that they’re not old enough to view content.

Creating the Age Gate Controller

The main logic of the Age Gate located in GateController, logic of displaying an Age Gate form and proving the age of the user.
We use the GateForm from the previous step for validating user input.

# frozen_string_literal: true
class GateController < ApplicationController
  def new 
    @gate_form = GateForm.new
  end

  def create
    @gate_form = GateForm.new(gate_params)

    if @gate_form.valid?
      cookies[:gate_passed] = { value: 1, expires: 1.year.from_now }  
      redirect_to root_path
    else
      render :new
    end
  end

  private

  def gate_params
    params.require(:gate).permit(:choice)
  end
end

valid? the method is there to guarantee that a user choice is valid before we can proceed.

As you can see we display a validation message if a user not passes an Age Gate, but can change this.

This a list of actions:

  • Redirect by Url;
  • Reload a page;
  • Display message.

Add action restrictions to ApplicationController.

If the user did not submit our Age Gate Form we should force him to do it.
So for doing it, we added method to_gate! which requires a user to submit AgeGate From.

# frozen_string_literal: true
class ApplicationController < ActionController::Base
  before_action :to_gate!

  def to_gate!
    return if crawler_request?

    redirect_to age_gate_path unless cookies[:gate_passed] == true || controller_name == 'gate'
  end


  private

  def crawler_request?
    if request.env["HTTP_USER_AGENT"].nil?
      false
    else
      request.env["HTTP_USER_AGENT"].match(/(.*https?://.*)/)
    end
  end
end

View for Gate Form

On the view side of our application, we use the ActiveModel object @gate_form in the form that gives us the capability to have validations errors that will display inline within the form just like ActiveRecord.

<%= form_for @gate_form, method: :post do |f| %>
  <h1> Welcome to our website </div>
  <p>Please, verify your age to enter.</p>

  <div>
    <% if @gate_form.errors[:choice].any? %>
        <p><%= @gate_form.errors[:choice].to_sentence.html_safe %></p>
    <% end %>
  </div>  

  <div>
    <div style='display: inline-block;'>
      <%= button_tag 'I am over 21', name: 'gate[choice]', value: '1' %>
    </div>
    <div style='display: inline-block;'>
      <%= button_tag 'I am under 21', name: 'gate[choice]', value: '0' %>
    </div> 
  </div>
<% end %>

Specifying Routes

Open your config/routes.rb file and add the following lines of code for our GateController.

Rails.application.routes.draw do
  # you can specify own root path
  root to: 'welcome#new'

  get '/gate', to: 'gate#new'
  post '/gate', to: 'gate#create'
end

Result Age Gate Form

Result of our work, you can see on picture 1.1.

Picture 1.1

Age Gate With Birthday Entering

Form Object for our Age Gate, where we validate user birthday. We use ActiveRecord::AttributeAssignment because this module can parse raw user input. Method assign_attributes takes parameters from controller {“birthdate(2i)”=>”3”, “birthdate(3i)”=>”7”, “birthdate(1i)”=>”1996”}, and transform to readble hash {2=>3, 3=>7, 1=>1996} .

# frozen_string_literal: true

class AgeGateForm
  include ActiveModel::Model
  include ActiveRecord::AttributeAssignment
  attr_accessor :birthdate
  
  validate :filled_properly?

  def initialize(*params)
    assign_attributes(*params) if params.present?
  end

  private

  def filled_properly?
    if casted_birthdate.nil?
      errors.add(:birthdate, 'You entered an incomplete date.')
    elsif ((casted_birthdate + 21.years) > Time.current)
      errors.add(:birthdate, 'You must be 21 years of age or older to access this site.')
    end
  end

  def casted_birthdate
    ActiveModel::Type::Date.new.cast(@birthdate)
  end
end

This controller does the same thing as in the previous example. It’s displaying an Age Gate form and check an age of user.

# frozen_string_literal: true
class AgeGateController < ApplicationController
  def new
    @age_gate_form = AgeGateForm.new
  end

  def create
    @age_gate_form = AgeGateForm.new(age_gate_params)

    if @age_gate_form.valid?
      cookies[:age_gate_passed] = { value: 1, expires: 1.year.from_now }  
      redirect_to root_path
    else
      render :new
    end
  end

  private

  def age_gate_params
    params.require(:age_gate_form).permit(:birthdate)
  end
end

View for Age Gate Form with Date of Birth.

Ruby on Rails has a cool helper method date_select, which gives us a set of select tags (one for a year, month, and day).

<%= form_for @age_gate_form, method: :post do |f| %>
  <h1> Are you over the age of 21? </h1>
  <div>
    <%= f.date_select :birthdate, { start_year: Date.today.year, end_year: 1900, use_two_digit_numbers: true, order: [:month, :day, :year], prompt: { month: 'Month', day: 'Day', year: 'Year' }, default: Date.today, with_css_classes: true } %>
    
    <% if @age_gate_form.errors[:birthdate].any? %>
        <%= @age_gate_form.errors[:birthdate].to_sentence.html_safe %>
    <% end %>
  </div>
  <div >
    <%= f.submit 'SUBMIT' %>
  </div>
<% end %>

Result Form

On Picture 1.2 you can see Age Gate Form with select a birthdate.

Picture 1.2

Conclusion

In this tutorial, we have discovered what Age Gate is, and when you have to it, created the Age Gate in two ways in Rails Application, by proving their Age by clicking on the yes or no buttons, and the second way by entering their full date of birth: year, month, and day.


Thank you for going through this tutorial with me. I hope it was helpful and you like it!

Rate this article, if you like it

Thanks! You’ve rated this material!

Got a project? Let's discuss it!

    Kyiv Sofiivska 1/2a, 01001, Kyiv, Ukraine
    Dnipro Hlinky 2, of. 1003, 49000, Dnipro, Ukraine
    Kharkiv Otakara Yarosha 22, 61000, Kharkiv, Ukraine
    Email info@syndicode.com