Url Shortner location Ruby On Rails

Total Blog Views: 48

Blog Status: publish

Created By: swazahmad Created at: 08-14-2021

Tags: ruby on rails url-shortner track location

How To track location In ruby On Rais?

How To Create Short URL In Ruby On Rails?

Today We Learn How To make URL short In Ruby On Rails

First Of We will create New Rails Application and configure DB

 

 rails new new_sample_url_shortner_with_location

Add Below Gem In GemFile

gem 'devise', '~> 4.7', '>= 4.7.2'
gem 'shortener'
Then We Will run Below Command And Install devise Gem
bundle install
rails generate devise:install
rails generate devise User

Run Below Command

 

rails generate shortener
rails g scaffold UrlShort link:text
rails g Model Country name:string ip:string url_id:integer

Update Some UI part

home/index.html.erb

<div class="container">
  <div class="row">
    <div class="col-sm-10 col-lg-10 col-md-10">
      <p id="notice"><%= notice %></p>
      <h1>All Links</h1>
      <table class="table table-striped">
        <thead>
          <tr>
            <th>Long url</th>
            <th>Short URL</th>
          </tr>
        </thead>
        <%  @urls = current_user.shortened_urls.each do |data| %>
         <tr>
          <td><%= data.url %></td>
          <td><%= link_to "#{ENV["DEFAULT_URL_PROD"]}/#{data.unique_key}", "#{ENV["DEFAULT_URL_PROD"]}/#{data.unique_key}" %></td>
        </tr>
        <% end %></tbody>
        </table>
      <br>
    <%= link_to 'New Url Short', new_url_short_path %>
    </div>
  </div>
</div>

update home/stats.html.erb

 

<div class="container">
  <div class="row">
    <div class="col-sm-10 col-lg-10 col-md-10">
      <p id="notice"><%= notice %></p>
      <h1>All Links</h1>
      <table class="table table-striped">
        <thead>
          <tr>
            <th>URL</th>
            <th>Short Link</th>
            <th>Total clicks</th>
            <th>Top countries</th>
          </tr>
        </thead>
        <tbody>
<% @stats_all.each do |data| %>
            <tr>
            <td><%= data.url %></td>
            <td><%= link_to "#{ENV["DEFAULT_URL_PROD"]}/#{data.unique_key}", "#{config.default_host}/#{data.unique_key}" %></td>
            <td><%= data.use_count %></td>
            <td><% get_all_top_country(data) %>
             <%= @data %>
            </td>
            </tr>
          <% end %>
        </tbody>
      </table>
      <br>
      <%= link_to 'New Url Short', new_url_short_path %>
    </div>
  </div>
</div>
Update url_shorts/_form.html.erb
 
<%= form_for(@url_short,:html=>{:id=>"your_form_id",:multipart => true,:remote=>true}) do |form |%>
  <div class="field">
    <%= form.label :link %>
    <%= form.text_area :link %>
  </div>
  <div class="actions">
    <%= form.submit "shorten" %>
  </div>
  <div id="message-response">Here is your short URL</div>
  <div id="message-value"></div>
<% end %>
<script type="text/javascript">
  $('#message-response,#message-value').hide();
</script>

Update config/initilalizers/shortner.rb

 

Shortener.unique_key_length = 5
Shortener.charset = ('a'..'z').to_a + (0..9).to_a
 

Then We will Add The controller For Generate The URL

 # frozen_string_literal: true
class UrlShortsController < ApplicationController
  
  # GET /url_shorts/new
  def new
    @url_short = UrlShort.new
  end
  
  # POST /url_shorts or /url_shorts.json
  def create
    @data = if current_user.present?
              Shortener::ShortenedUrl.generate(params[:url_short][:link], owner: current_user,
                                                                          expires_at: 24.hours.since)
            else
              Shortener::ShortenedUrl.generate(params[:url_short][:link], expires_at: 24.hours.since)
            end
    respond_to do |format|
      format.js { render 'url_shorts/status' }
    end
  rescue Exception => e
    @error = true
    @error_data = e
    respond_to do |format|
      format.js { render 'url_shorts/status' }
    end
  end
  
  private
  
  # Only allow a list of trusted parameters through.
  def url_short_params
    params.require(:url_short).permit(:link)
  end
end

Then We will Add The Home Controller To list the URL created by current user

 

class HomeController < ApplicationController
  before_action :authenticate_user!, except: %i[show stats]
  
  # Get all currebt user shorten urls
  def index
    @urls = current_user.shortened_urls
  end
  
  # Redirect to shorten url
  def show
    token = ::Shortener::ShortenedUrl.extract_token(params[:id])
    url = ::Shortener::ShortenedUrl.fetch_with_token(token: token, additional_params: params)
    # do some logging, store some stats
    redirect_to url[:url], status: :moved_permanently
  end
  
  # To show statics all
  def stats
    @stats_all = Shortener::ShortenedUrl.all
  end
end
Add New File app/controllers/shortner/shortened_urls_controller.rb
 
module Shortener
  class ShortenedUrlsController < ActionController::Metal
    include ActionController::StrongParameters
    include ActionController::Redirecting
    include ActionController::Instrumentation
    include Rails.application.routes.url_helpers
    include Shortener
    # Update the country and IP address while visit links
    def show
      token = ::Shortener::ShortenedUrl.extract_token(params[:id])
      track = Shortener.ignore_robots.blank? || request.human?
      url   = ::Shortener::ShortenedUrl.fetch_with_token(token: token, additional_params: params, track: track)
      country = ISO3166::Country[request.location.country]
      name = begin
        (country.translations[I18n.locale.to_s] || country.name)
      rescue StandardError
        ''
      end
      Country.create(url_id: url[:shortened_url]&.id, name: country, ip: request.location.ip)
      redirect_to url[:url], status: :moved_permanently
    end
  end
end
Update User.rb Model File
 
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_shortened_urls
end

Run rake db:migrate

Now You can run and test Your application

All complete code present IN Link

Working Demo App

If You do have some suggestion and queries Please Let us know In comments

 


swazahmad

Swaz is Practice Lead of ROR Developer. he's a Blogger, Mentor, and Rubyst. He has expertise in Javascript also . he's highly skilled in designing, developing and testing web applications. He enjoys being challenged and interesting with projects that need him to



Comments



  • asad | over 3 years ago
    Great information
  • swazahmad | over 3 years ago
    Awesome Information Thanks For Sharing
Buy traffic for your website

About Shadbox

we have the “Get things executed” lifestyle at our place of work. There are not any excuses, no if’s or however’s in our dictionary. committed to navigating the ship of creativity to create cell answers, we resolve the real-lifestyles troubles of our clients and their clients. Our passion for work has won us many awards, year after 12 months.

Services

Downloads