Skip to main content

Posts

Showing posts with the label ruby on rails development tips

Virtual Studio Code for Ruby on Rails Development

Introduction to Vscode (Visual Studio Code) Visual Studio Code i.e. Vscode is a modern and robust code editor developed by Microsoft. We can use it for setting up Ruby on Rails development environment. It combines the simplicity of code editor with powerful tools like IntelliSense, code completion, debugging and built-in Git support. One of the beauties of Vscode it's free and open source. It is available for Windows, Mac, and Linux with huge community support.  How to Install Vscode? Installation steps of Vscode are pretty simple, go to  Visual Studio  it will automatically detect the operating system you are using and provides a download link. After installation, you are ready to start customizing Vscode for Rails development. How do you set up Vscode for Rails? ·  Ruby extension: The first thing you have to install the ruby extension in Vscode. Press  f1 , type  ext install  then sea...
Being a Rails developer we are familiar with ActiveRecord queries, but not so much with Arel. Arel is a library which allows us to customize our queries in an object-oriented manner without having to use manual SQL and string interpolation. We often use where a method for querying the database. Where method can handle equality, null, arrays and now in Rails 4 it is also able to handle inequality condition with not method. But when there is a requirement of writing queries with OR statement or greater-than or less-than conditions most developers opt for writing SQL string queries. We have a better way to handle this situation using Arel. For example: If you want to select students having the date of birth greater than today’s date or date of birth less-than or equals to today’s date, usually a developer will write the query like this Student.where("date_of_birth> ?", Date.today) or Student.where("date_of_birth<= ?", Date.today) But this is not a go...

How to Track Page Impressions in Ruby on Rails?

Many times, we need to track the page views of any page such as profile page, shopping sites page in a Ruby on Rails applications, for which we can make use of Impressionist gem to track those page details easily. It is a lightweight plugin that logs impressions per action or manually per model. We can log impressions multiple times per request. And we can also attach it to a model. Below are the simple steps needed to follow to implement it: Step 1: Create a sample app using scaffold. Step 2: Add “gem ‘impressionist’” gem to the Gemfile and install it by running bundle install command. gem ‘impressionist’, git: ‘https://github.com/jordanhudgens/impressionist’ Step 3: Nowgenerate the impressions table migration by running the below commands: rails g impressionist rake db:migrate Step 4: Now we need to update our controller that we want to add the impression or page views counting system. So first we have add the following method in our controller with men...

GraphQL With Ruby

Now a day’s most of the web or mobile applications fetch data from server which is stored in a database. REST API provides an interface to stored data that require by the applications. GraphQL is a query language for REST API's not for server databases. It is database agnostic and effectively can be used in any context where an API is used. GraphQL provide platform for declarative data fetching where client need to specify what data needs from API in response. Instead of multiple endpoints that return fixed data structures, a GraphQL server only exposes a single endpoint and responds with precisely the data a client asked for. GraphQL minimizes the amount of data that needs to be transferred over the network and improves applications operating under these conditions. Introduction to GraphQL API on Ruby on Rails Start with adding gem in Gemfile gem ‘graphql’ Run command bundle install Run command rails generate graphql:install Above command will add gr...

Data Searchning in Ruby on Rails using SearchKick Gem

What is SearchKick Gem? Searchkick Gem is a Ruby on Rails gem that runs on top of Elasticsearch and makes it easy searches in a Rails-friendly fashion. Searchkick supports the complete Elasticsearch Search API, as by using it our search becomes more advanced. In addition, it allows you to add more features including analytics, auto suggestions, and personalized results. The steps are required: Add the gem “gem ‘searchkick’ “ . Then run the bundle install command. Then we will generate the complete model by using Scaffold generator rails g scaffold Article name:string description:text After running the above command it will generate all the necessary files then we will run the database migration command. rake db:migrate The controller code will be modified like that Def index Query=params[:q].presence || “*” @artivles=Article.search( query, page: params[:page}, per_page: 25 ) end The model code will be modified like that searchkick def search_data { t...

How to manage postgres through command line in Ubuntu?

Step 1: First install postgres in Ubuntu system using following commands. $ sudo apt-get update $ sudo apt-get install postgresql postgresql-contrib libpq-dev To check psql (postgres) version. $  psql –version Step 2:  Now to create root user and password for psql. $  sudo -u postgres createuser -s root $  sudo -i -u  postgres Now, you are in postgres environment. postgres@admin:~$ Now, use the following command to enter and manage psql. postgres@admin:~$  psql Now, set the password for psql username “ root ”. postgres=# \password root enter password confirm Now, you can exit from psql using following command postgres=# \q Step 3:  Create new user and database in psql $ sudo su postgres $ psql -c "create user mack with password 'mack'" $ psql -c "create database mackdb owner mack" $ sudo -i -u postgres postgres@admin:~$  psql Step 4:  Give all privileges over database to a particular user. postgres=# grant all...

Best In Place Gem In Ruby On Rails Tutorial

The best_in_place gem is the easiest solution for in place editing in Ruby on Rails. This gem provides functionality of “in place editing” in ruby on rails without writing any extra ajax code. It supports text inputs, textarea, select dropdown, checkboxes, jQuery UI Datepickers, etc. Also Displays server-side validation Installation Steps of “best_in_place” Gem : Installing best_in_place is very easy and straight-forward. Just begin including the gem in your Gemfile: gem ‘best_in_place’ After that, specify the use of the jquery and best in place javascripts in your application.js, and optionally specify jquery-ui if you want to use jQuery UI datepickers: //= require jquery //= require best_in_place //= require jquery-ui //= require best_in_place.jquery-ui Then, just add a binding to prepare all best in place fields when the document is ready: $(document).ready(function() { /* Activating Best In Place */ jQuery(".best_in_place").best_in_place(); });...

Sending Emails in Rails Applications

Action Mailer is the Rails component that enables applications to send and receive emails. In Rails, emails are used by creating mailers that inherit from “ActionMailer::Base” in app/mailers. Those mailers have associated views that appear alongside controller views in app/views. Now we will build a rails application which will send an email to the user when a new user is created. Let’s create a new rails application. $ rails new sample_app $ cd sample_app $ rails generate scaffold user first_name:string last_name:string phone_number:string email:string $ rake db:migrate Action Mailer- Configuration: Following are the steps you have to follow to complete your configuration before proceeding with the actual work. We will just add following lines of code in  config/environments/development.rb config.action_mailer.delivery_method = :smtp #It tells ActionMailer that you want to use the SMTP server. Generate a Mailer : We now have a basic application, let’s make ...

Using JWT in Rails

JWT is a Json Web Token,It is a standard and has been implemented in almost all popular programming languages. Hence, they can be easily used or exchanged in systems implemented in diverse platforms. JWT has libraries for almost all platforms and Ruby is no exception. Now we will see how JWT is used in Rails: We will create a simple Rails application which uses the excellent Devise gem for authentication and the jwt gem for creating and verifying JWT tokens. Let’s create a sample Rails application : rails new rails_on_jwt Once the application is generated, create a Home controller which we will use to check our authentication. Create  home_controller.rb in the app/controllers classHomeController ApplicationController def index end end Write the route for  HomeController to /home in config/routes.rb: Rails.application.routes.draw do get 'home' => 'home#index' end Now, add Devise to our application. First, we will ...

Bulk Mailing Using Sidekiq

Introduction: Sometimes the rails application requires sending the bulk mails using action mailers on the single attempt. The user can be able to send them seamlessly. But, this task is not possible in synchronous way. This will affect whole application performance and will take a lot of time to load the respective pages. To overcome this problem rails community have enormous kinds of solutions. Among them  sidekiq is the best choice to overcome this kind of problems. The sidekiq is a full-featured background processing framework for Ruby. It aims to be simple to integrate with any modern Rails application and much higher performance than other existing solutions. The Redisis an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperlog logs and geospatial indexes with radius queries. The Action Mai...

Data scraping in Ruby on Rails using Nokogiri and Mechanize Gem

What is Data scraping? Website/Data  Scraping  is a technique to operating large amounts of  data  from websites whereby the  data  is extracted and displayed in own sites or it can be stored to a File/Database. Data scraping is basically used where the websites does not provides API. Some Applications do not provide API to collect records. For the same , Data Scraping technique is used. The data can be scraped using Nokogiri Gem. The steps are required: Add the gem “gem ‘nokogiri’, ‘~> 1.8’, ‘>= 1.8.1'” . Then run the bundle install Add the “require ‘nokogiri'” , “require ‘open-uri'” line where you will write the code for the scraping. The controller of the page will look like below: The view of the code of view page will look like : The result in our application will look like: Mechanize Gem in rails The Mechanize library is used for automating interaction with websites. Mechanize automatically stor...

How to combine data from two different tables into new rows to be displayed as one table in Rails application?

Let’s start with an example that you have two different tables called InternalEmail and ExternalEmail. internal_emails Id (integer) sender_id (integer) content (text) Subject (character varying) recipient_email (character varying) Status (character varying) created_at (timestamp without time zone) updated_at (timestamp without time zone) 1 52 internal_content_1 internal_subject_1 44 accepted 2016-10-21 00:49:24.991002 2016-10-21 00:49:24.991002 2 46 internal_content_2 internal_subject_2 43 rejected 2017-10-21 00:49:24.991002 2017-10-21 00:49:24.991002  external_emails Id (integer) sender_id (integer) content (text) Subject (character varying) receiver_id (integer) opened (boolean) created_at (timestamp without time zone) updated_at (timestamp without time zone) 1 44 external_content_1 external_subject_1 42 true 2014-10-21 00:49:24.991002 2014-10-21 00:49:24.991002 2 42 external_content_2 external_subject_2 41 ...