ROR Application Development Tips

I'm Ruby on Rails developer. I love to share my experience, technical knowledge. I work at Crypex Technologies which is developing applications in ROR for more than a decade.

A Beginner’s Guide to Angular Architecture for Front-End Development

We have gone through many web applications and mobile applications which do not reload the entire page but instead reloads only the required section. These are nothing but Single Page Applications (SPA) which are developed using Angular. A good example of SPA is Gmail where we have noticed that when we click on the inbox, it only reloads and displays that email in the e-mail list sections.

Introduction to Angular:

Angular is a TypeScript-base open-source front-end platform and framework led by the Angular Team at Google used for building client-side web applications. Angular itself is written in TypeScript, which is a superset of JavaScript and used for front-end development.

Installation:

In order to start with the installation, we first need to make sure that we have nodejs and npm installed with the latest version.

We can install nodejs on Ubuntu OS by running the following command on terminal:

  • sudo apt-get update

  • sudo apt-get install nodejs

To install npm, we run the following one-line command on terminal:

  • sudo apt-get install npm

To check the versions of Node.js and npm installed, we run following command:

  • nodejs –v

  • npm –v

Let’s install Angular CLI by running the following command:

  • npm install –g @angular/cli

IDEs for Angular:

We can use any of the IDE i.e., WebStorm, Atom, Visual Studio Code, etc. But usually, Visual Studio Code is preferred.

Architectural Blocks of Angular:

The main building blocks of an Angular application are:

  • Modules

  • Components

  • Templates

  • Metadata

  • Data binding

  • Directives

  • Services

  • Dependency injection

In this blog, we will have an overview of Angular Modules and Angular Components.

Angular Modules:

We have Angular modules or we can say NgModules which maintains the modularity of Angular apps. Every Angular app has at least one module as the root module. Conventionally, it is named as AppModule. Typically, an app contains many functional modules. In angular, any module is a class with the @NgModule decorator.

The NgModule decorator is a function that takes metadata object whose properties describe the module. The properties are as follows:

  • declarations: Here, we have to declare the classes that are related to views (i.e. The components, the directives, and the pipes that belong to this NgModule).

  • exports: Here, we have to mention the classes that should be accessible to the components of other modules.

  • imports: Here, we have to mention the modules whose classes are needed by the component of this NgModule.

  • providers: Here, we have to mention the Services present in one of the modules which are to be used in the other modules or components. Once a service is included in the providers it becomes accessible in all parts of that application

  • bootstrap: Here, we have to mention the root component which is the main view of the application. This root NgModule only has this property and it indicates the component that is to be bootstrapped.

The root module (i.e. src/app/app.module.ts) by default looks like:

 

Angular | A JavaScript Framework for Front End Development

Image: The Root Module in Angular

 

Angular Components:

Every Angular application has a root component i.e. AppComponent which is bootstrapped inside the main module. In angular, each component defines a class with the application data and logic and is associated with a view i.e. HTML template to be displayed in a target environment.

The root component (i.e. src/app/app.component.ts) by default looks like:

 

Angular | A JavaScript Framework for Front End Development

 

 

 

 

 

 

 

Image: The Root Component in Angular

 

Advantages of Angular:

  • Angular is faster, lighter and easier framework which is built to create faster performance applications that are smaller in size and easier to develop.

  • It provides high performance, offline, and zero-step installation. So, Angular is pretty much easy to work with.

  • Angular is universal that means we can use any technology with it for serving the application like node.js, .NET, PHP, Ruby on Rails and other servers.

  • Angular is productive as:

  • It generates UI templates quickly with simple and powerful template syntax.

  • Angular CLI with Command line tools.

Apart from front end development we use Ruby on Rails framework for backend development. Hope this blog would be informative to understand the basic building blocks of Angular.

Introduction to FontAwesome 5:

Font Awesome 5 is upgraded version of Font Awesome 4, It has a more attractive icon with big improvement icons as compare to Font Awesome 4

Some improved points are listed below:

 

  • FontAwesome 5 icons are drawn now with SVG.

 

  • Now we have to reference Javascript file with SVG embedded in place of CSS file ( In FontAwesome 4 we use CSS file only ).

 

However, version 5 is now redesigned and rewritten from scratch.

 

Now, Let us see the changes in FontAwesome 5

 

Different icon styles:

 

In Version 5, there are 3 different styles:

i) Solid Style

ii) Regular Style

iii) Light Style

 

Brand Icons” are separated out into their own style and is easy to use. Version 4 had one prefix only “-fa” and Version 5 has four prefixes. To set a style of any icon with ease, every prefix has different Javascript and SVG file. If we want to use them, we need to import Javascript and SVG file. Some as mentioned below.

 

Font Awesome 5 Prefix

Icon Style

JS+SVG Filename

Web Font

fab

Font Awesome Brands

brands.js

fa-brands-400

fas or fa

Font Awesome Solid

solid.js

fa-solid-900

far

Font Awesome Regular

regular.js

fa-regular-400

fal

Font Awesome Light

light.js

Fa-light-300

 

Table: Font Awesome 5 Details

 

Syntax

 

Version 4’s Syntax

 

1)<i class=”fa fa-rocket”></i>

 

Version 5’s Syntax

 

1)<i class=”fas fa-rocket”></i>-----------“fas ‘s’ for Solid”

2)<i class=”far fa-rocket”></i>----------- “far ‘r’ for Regular”

3)<i class=”fal fa-rocket”></i>----------- “fal ‘l’ for Light”

 

Note:- Some Icon name changed in the upgraded version.

 

How to use FontAwesome 5:

 

Step1: Add Assets for FontAwesome 5 (Version 5)

 

Download cdn which is required for version 5

 

Web Font & CSS files

  1. css/solid.css

  2. css/regular.css

  3. css/brand.css

  4. css/fontawesome.css

  5. css/light.css

  6. For all CSS, we can use css/all.css

 

JS & SVG files

 

  1. js/solid-.js

  2. js/regular.js

  3. js/brand.js

  4. js/fontawesome .js

  5. js/light.js

  6. For all js, we can use js/all.js

 

There is one more file that is “ Shims ” file.

Shim file is created to be used as band-aids until you get time to upgrade. Version 4 allows you to keep v4 icon name, aliases, and syntax while mapping Version 5. If we want to use then add below extra line to our Version 5

 

<link rel=”stylesheet” href=”https://use.fontawesome.com/releases/v5.2.0/css/v4-shim.css”>

 

v4-shim is used for both Web Fonts + CSS and SVG + JS Frameworks.

If we want to use new and fancy SVG+JS of rendering icon, then switch the “css/all.css into “js/all.js” also “css/v4-shims.cssinto “js/v4-shims.js“

 

Step2: Add syntax in your HTML file

 

For Example:

<i class=”fal fa-rocket”></i>

<i class=”far fa-rocket”></i>

<i class=”fas fa-rocket”></i>

 

An effect you can see in below image:

 

FontAwesome 5 in Web Designing

 

Image: Font Awesome 5 Comparison

 

Note: In FontAwesome 5 some icon name are changed, if we don’t want to use them then, we have to add shim file. Version 5 has lots of icon but some icons are paid, if we want to use then we need to buy PRO Version .

 

Advantages:

 

1) Icon are designed using SVG and Javascript.

2) Icon Fonts are Ligatures and auto-accessibility.

3) Icon can be re-written, redesigned using CSS and JS.

Cron job in Ruby on Rails application – A Complete Tutorial for Beginners

A scheduled task is very important in Ruby on Rails application. Ruby on Rails does not have this type of “out-of-the-box” feature, but we can use the Cron job to achieve the purpose. Cron can be scheduled to send a reminder email, or scheduling to crawl something from another website on daily basis. In this blog, let’s quickly go through how to use Cron job.

What is CRON?

Cron task is a time-based job scheduler in Unix-like computer operating systems. Cron can be used to schedule jobs to run periodically at fixed times, dates, or intervals. Cron is most suitable for scheduling repetitive tasks in Ruby on Rails applications.

Let’s take an example of sending a daily digest email to persons or users. In this case, we might have a mailer like this using crontab:

 

#STEP 1.

The user can run any method from the terminal. Here I’m running an action inside a model i.e schedule_rb_method.

Open “app/models/reminder.rb” and then add the method for running an action as shown below.

 

Cron Job in Ruby on Rails Application

 

Run rails runner “Reminder.schedule_rb_method” command inside the project path on the terminal, to check method is running or not.

 

#STEP 2.

 

Set the default rvm to the project.

run rvm --default use 2.5.0

 

#STEP 3.

 

Creating a Crontab:

Cron is driven by a crontab (cron table) file, a configuration file that specifies shell commands to run periodically on a given schedule.

Users can have their own individual Crontab files in the system.

It’s pretty easy to start working with cron jobs in rails. You can start editing your cron tasks using the crontab command on your terminal:

Open your terminal: run crontab -e

This command will open a text file in your terminal’s default editor.

 

#STEP 4.

 

We are going to enter a line into this crontab file. It will have the following structure:

[timings] [switch to your app directory] && [path to ruby] script/runner -e [environment] “[model class name] . [ (run method name) path to cron log]”


By looking at the above line to understand: Run a task every day at 10 am.

 

Rails Cron Job Tutorials for Beginners

 

  1. If you try and save your crontab and you receive errors, make sure the whole command is in one line on your terminal.

  2. If your model method runs OK, you should either get some mail as mentioned in the cron. However, if there is an error, you must check your cron method to check the log you created in rails to understand the error.

     

Crontab Syntax:

Once you’re in the editor, you can start creating and editing cron tasks in rails. To schedule a cron task, you need to define when the task will run, then define the command to trigger that task.

There are 5 variables that can be changed inside a cron task in Ruby on Rails application:

  • 1st variable: Minute, which can be specified from 0 to 59 min

  • 2nd variable: Hour, which can be specified from 0 to 23 hr

  • 3rd variable: Day of Month, which can be specified from 1 to 23 day

  • 4th variable: Month, which can be specified from 1 to 12 month

  • 5th variable: Day of Week, which can be specified from 0 - 6 (Sunday = 0) week days

If the variable is a “*” it means for all.

If the variable is a series of number split by a comma “,”, it means OR condition on each of the specified number in Cronjobs.

 

Example:

Timing Format: 
minute   hour   day   month   weekday
0,30      *      *      *      *   example command to be executed 

 

Cron job Crontab in rails application

 

While cron jobs are useful and can get the job done in many instances, you should be careful in your decision of how to implement scheduled and delayed tasks in Ruby on Rails application.

In rails, Cronjobs are best for tasks that are not highly critical or essential to your application’s functionality or performance. They should also execute in a reasonably short amount of time so that they don’t bog down your rails server(s).

Simplifying Admission Procedures using Ruby on Rails Technology

Every University has thousands of applications streaming in for each course. A single application has a minimum of three stages – the document submitted by the student, his/her interview and finally, uploading the financial proof. Managing all of this singularly is a huge challenge.

There is a strong need for providing a common platform for application management. Offshore System for Student Management, a software developed and managed by Cryptex Technologies, India is the perfect one-stop solution for this. This application is developed using Ruby on Rails technology.

It is integrated with a dashboard showcasing the various features of this application, you can easily navigate around to make your work easier.

The dashboard has options for viewing the student application checklist, interview scheduling and feedback, advanced search functionality, along with the financial document submission and COE.

A database of a thousand and more entries can be filtered according to the search requirement. You can generate reports for specified time durations in the form of graphs and charts.

An export data feature is introduced in this to export the online data directly to your desktop.

Another added feature of OSSM is that of accessing the information of the agent via whom the student has applied. This helps during future decision making, giving a constructive insight into the work done by each of the agents.

Having a consolidated application for admission procedure is a one-time solution for eliminating all the manual efforts and errors.

 

Student Management Software using Ruby on Rails

 

How to deploy Ruby on Rails Code on production server with Passenger and Apache?

In this blog, you are going to learn about the deployment of rails application on the production server with its configuration setting in Apache. For this, you need to have Ruby, Rails, MySQL installed in your server system.

         

Let’s begin with the process of deploying the Rails application.

 

Step 1: Add the code copy to the server.

 

          For adding code to the server, you need to take a copy of the code on your server by login using sftp.

 

$ sftp user@yourserver.com

$ put samplecode

 

 

Step 2: Installation of project and configuration settings.

 

          Install all libraries of the project and make configuration settings including configuration of database.yml and secrets.yml by using following commands. For this, you need to login to the server using ssh and go to the project folder.

 

$ ssh user@yourserver.com

$ cd samplecode

 

          Rails app has ruby versions and you have to use that specific version to run the application. So, use the ruby version of the application.

 

$ rvm use (ruby version)

 

          Install all libraries of the project, set the database and compile assets. Rails have some specific commands to do that.

 

$ bundle install

$ rake db:create RAILS_ENV=production

$ rake db:migrate RAILS_ENV=production

$ rake assets:precompile RAILS_ENV=production

 

          Rails provide a secret key which you have to mention it into the config/secret.yml file of the application to maintain the security.

 

$ rake secret

 

Above command provide a secret key, add it to theconfig/secrets.yml file of you RoR project.

 

Step 3: Apache settings

 

          You have to do apache settings to run the application in production mode on apache server. For this first, you have to createsamplecode.conf file in etc/apache2/sites-available/ path.

 

The file content will look like as in Image 1. Where you have to mention the domain of your application like www.myapp.com and server name like myapp.com. With this, you also have to mention the path of a public folder of the application and ruby version of the application.

 

Deploying RoR Application on production server

 

Image 1: Samplecode.conf File

 

You need to create the symlink of the file samplecode.conf to the sites-enabled folder.  It is created for apache and virtual host settings. This virtual host setting will tell Apache where your application is located. Replace myapp.com with your application name and as well as mention path to ruby with the ruby version of the application into the samplecode.conf file.

 

          If you start the application on some port and not on some domain like www.myapp.com, you need to specify the port number in the conf file in place of port “80” at the top of the file. And then mention that port to the ports.conf file which is located at /etc/apache/ports.conf.

 

Deploying Ruby on Rails Application on Production Server

 

Image 2: Ports.conf File

 

In the above image, you can see how to mention port, like I have mentioned port 3000 to be heard by apache while serving the page. At last restart the apache server by using the following command. It will run the application on the link like 127.0.0.0:3000 or if it is for a domain then it will run on www.myapp.com or myapp.com.

 

$ sudo restart apache2 restart

 

In this way, you can start a rails app on the production server.

Increase your Scalability using Redis in Ruby on Rails Application

Redis is an open source very fast, non-relational, in-memory data structure store. It stores data in the form of a key-value pair. Redis has a support of data structure like sets, hashes, strings, list. Redis is mostly used for the cache store.

 

When to use Redis?

 

Redis is used when we have a performance issue related to scalability. For example when we have data in the database which is not going to change frequently then you use Redis to cache that data to remove the load from the MySql or PgSql server.

 

How to use Redis in Ruby on rails?

 

In order to use Redis in Ruby on Rails application you have to follow the steps given below:

 

Step 1:

 

Add the following gem into the Gemfile of application and run the “bundle install” command.

 

Improve performance of Rails Application using Redis

 

 

 

 

Step 2:

 

Next is to create redis.rb file in config/initializers directory and add the following code into that file 

 

Ruby on Rails Application using Redis

 

In the above code “app_name” is the Namespace of my application. Gem “redis-namespace” organize everything under one application wise namespace, when multiple applications use same Redis server.

 

Step 3:

 

Next, to instruct rails to use Redis as a cache store we have added following code into application.rb file.

 

Increase scalability of Ruby on Rails Application using Redis

 

Step 4:

 

In the below code I have written a query in booths_controller.rbfile to fetch all booths of size 16m2. And write a helper method inbooths_helper.rb to fetch the data from Redis.

 

Ruby on Rails Application using Redis

 

 

Ruby on Rails Application using Redis

 

In the above code when we call the new_booth method ofbooths_controller, it will call the fetch_booths_16 helper method.

 

In this fetch_booths_16 method, the booths_16 will get nil value because no data is pushed into redis yet. We then instruct rails to push booths_16 data into redis. Then after a subsequent call to this method, data will be fetched from redis.

 

Since we are loading data in new_booths as a json we have to change when you call @booth_size_16.name to@booth_size_16[“name”] because data is in the form of json.

 

Advantages of using Redis:

  • Support for rich data structure types: hash, string, set, list, sorted etc.

  • Data is stored in memory and retrieve quickly: Redis store data in memory so instead of requesting data from the server it will fetch from memory and retrieve data very quickly

  • Redis is used to speed up service response.

  • Redis is a very fast non-relational and NoSQL key-value pair data store.

  • Redis allows to insert a large amount of data into its cache very easily: Sometimes a situation comes like we have to load a thousand pieces of data into cache in a short period of time. This can be done by Redis, with mass insertion feature of it.

  • Redis uses “Redis hashing” which is its own hashing mechanism: Datastore in redis in the form of key-value pair i.e. string field and a string value.

 

Redis offers efficient caching mechanism and it will take very less time to implement this cache mechanism. But outcomes of using this will get high-performing cache system in our application.

 

So this is the way you can improve the performance and increase the scalability of Rails application to a great extent.

Six rules to make Ruby On Rails code Crisp, Absolute and Clear!

In my coding lifetime, I have enhanced and improved my coding style after client feedback and guidance. I have learned over the years of time, that there aspects and points that has utmost importance in the coding of Ruby on Rails (RoR) application.

We as developers start writing code without actually analyzing and understanding the code requirement as well. A messed up code is no one’s favorite and not to be delivered.

I am sharing my thumb rules that will surely help you as it did to me.

 

Rule No. 1: Indent your code

What if you are given a much messed up code to update? I am sure you will get frustrated; in order to write very clear code keep it well indented. In Ruby on rails, though the auto-generated code is four space indented style we should use two spaces to intend our block of code as this is most widely adapted style. This improves thereadability of our code.

 

Rule No. 2: Name it well!

Naming convention should be followed as this is helpful for us to understand the purpose of it and at certain places, active record in ruby also works on the basis of names.

Active record uses the same naming convention in order to find out how the mapping between the models and database tables are created.

Say for example a class “Category”, should have a database table called “Categories”. The rails pluralization mechanism is very powerful such that it is capable of pluralizing both regular and irregular words.

When it comes to naming a variable, you should follow CamelCase form, which says that the first word should start with a small letter and the next word should start with a capital letter, e.g. “categoryOne”.

When the table name has two words, it should be separated by “_” , e.g. “book_categoryies”. When it comes to model class, it should be singular with the first letter of each word capitalization e.g. “CategoryBook”.

Similarly, the name of methods should be such that it should define the purpose of that method, for e.g. “category_list”.

 

Rule No. 3: Less If else, Less complex

If else statement is a block of condition where you check the condition if it is true or false.

Using the number of if-else statement creates makes the code bulky. It will increase the number of lines in the code, which can be reduced or should not be used at all. It also makes the code complex and not easy to understand.

 

Rule No. 4: Use of a number of variables

What do variables do in rails? It allocates the memory for which it is assigned for. When the expression can be directly assigned or can be directly passed, a variable should not be used as this will be the unnecessary allocation of memory, unnecessary declaration of a variable.

In Ruby on rails, we have four different types of variables global variables, class variables, instance variable and local variables.

Global variables are accessible globally in the application which means it can be modified from any part of the program hence it let to lack of security of our code.

Hence it is recommended not to use global variables.

Always try to replace instance variable with local variable as local variables are accessed locally which ensures the security of our code.

 

Rule No. 5: Put-up a comment there

Comments are the description written in the source code within the special character so that it should be ignored by the compiler.

What if, you get a new project with some classes having methods in it? Will you be able to understand the purpose of it?

Even, if the method name is good enough? No, sometimes only method names do not help in recognizing or understanding the main purpose of the method or how it works, hence your method should be well commented in order to let others also understand its basic purpose.

 

Rule No. 6: Don’t put too much logic in the view, make use of helpers, create them!

Views are specially meant for displaying the data hence it should not have too much logic, this can be done by making use of helpers, if the piece of code is used many times in a view, make a helper and call it in a view.

So, these are my six thumb rules while writing code, from the time that I have become the developer. These have helped me and can be taken as consideration to make your code scalable, robust and secure.

This will add sparkle to your code, which will eventually make your client happy! :)