to_json vs as_json in Rails API


Bookmark and Share

Recently we have been working on Rails API. During that time, we were curious about the difference between as_json and to_json. In this article, we are sharing the difference we learned.

to_json in Rails API

Let’s discuss how we started out building our APIs using ‘to_json’. to_json will return JSON string representing the hash. Option are passed to each element.

In to_json without any option,  the returned JSON string will include all the model attributes

to_json had some great options of ActiveRecord objects. We could just tell the method to only render certain attributes, or to include association or method calls. We had:

  • only – Only show column names in the output as specified in the list
  • except – Show all column names except the ones specified in the list

to_json works fine and seamlessly ok, as long as the database schema is deeply coupled with the API output.When it takes the next level where we want to render a certain attribute in json it start to break.

This will start to generate a bit load to controllers. Such methods of generating json don’t feel quite right and begin to break down. This is because the to_json is interested in ‘serializing’ a …

Read More

Authorization with Pundit gem


Bookmark and Share

Security is an important aspect of application development. Two main components of security are Authentication (Who are you?) and Authorization (are you supposed to be here?). Authentication verifies the user’s identity while authorization verifies whether that user has access rights on certain resources to perform actions on them.

Two popular gems for authorization in the rails world are CanCanCan and Pundit, we at Red Panthers prefers pundit over CanCanCan we get to write Pure Ruby Objects and keep the logic for each part separate.

The gem CanCanCan isolates (encourages) all authorization logic into a single class. It is a drawback when the complexity of application increases. Pundit gem provides object oriented design patterns to build our own authorization system that meets project’s requirements. It enables us to keep the models and controllers free from authorization code and allows to keep the resource logic separately. This flexibility and simplicity of Pundit gem help to use it with ease.

To start with Pundit

Add Pundit gem to your gem file and run bundle install.

Integrate Pundit to Rails application by adding the following line to ApplicationController.

If you run the Pundit’s generator as below, it will generate app/policies folder which contains …

Read More

Rack::Attack – secure you rails app for the real world


Bookmark and Share

Are you worried about the security issues in your Rails app? The rack-attack gem, can help you. Rack::Attack is a rack middleware which provides security to our rails application. It allows us to safelist, blacklist, throttle and to track requests.

  • If the request matches any safelist, it is allowed.
  • If the request matches any blocklist, it is blocked.
  • If the request matches any throttle, a counter is incremented in the Rack::Attack.cache. If any throttle’s limit is exceeded, the request is blocked.
  • Otherwise, all tracks are checked, and the request is allowed.

Implementation

Install the rack-attack gem, or add it to you Gemfile as:

Then tell your app to use the Rack::Attack middleware. For Rails 3+ apps:

Or you can use it in Rackup file as

By default, Rack Attack uses Rails cache. You can override that by setting the Rack::Attack.cache.store value. It is used for throttling. If you want to create use a custom adapter, for example, memory store,  create a file called rack_attack.rb in config/initializers to configure Rack Attack and put the following code in the file:

Throttle

Here we are limiting the request per seconds from the same IP address. Here we are limiting only 3 requests in 10 sec.

Safelist

Above example always …

Read More

Fixtures in Rails Tests


Bookmark and Share

Fixtures  are one of the important thing in Rails testing. Testing the application helps to debug it more efficiently and ensures the desired functionality to the application. Let’s have a look on them.

It is used to manage the test data. It tests against the real data and is written in YAML files. For each model in the application, there is a .yml file in the test/fixtures directory. When we generate the model using rails g it will automatically create the .yml file also. Here you can see an example,

Here ‘Matz’ is the fixture name. And the name and message are the fields in the User model.

Fixtures come in 3 flavours:

  • YAML fixtures: It is a file format which describes data structures in human-readable format.These are stored in a single file per model(above example is in yaml format).
  • CSV fixtures: Here values are kept in the Comma Separated Value (CSV) format. These are stored in a single file but instead end with the .csv file extension.

Eg:

  • Single-file fixtures: These are the original format for Active Record.

Eg:

Creating multiple/random items in fixtures

You can create multiple items as:

When you add fixtures, they get IDs based on …

Read More

Spice up your boring IRB (Irbtools)


Bookmark and Share

IRB stands for interactive ruby, it is a tool for interactively executing ruby expressions read from a standard input. To invoke it, type irb at the shell or command prompt, and begin entering Ruby statements and expressions. But it has some limitations. A solution to this is called ‘irbtools‘, which make using irb easier and more fun. It improves Ruby’s irb console like colored output and lots of helpful methods.

Setup

Install the gem by using:

or

Add it to your project’s Gemfile:

Usage

IRB executes code in ~/.irbrc on start-up.To use irbtools, put the following code in ~/.irbrc file:

We can start IRB directly from the code by calling,

When installing irbtools, some gems will not be installed. For example, the bond gem for better auto-completion. These are packaged as irbtools-more (requires ruby version >= 2.4). To use irbtools-more, change the .irbrc to:

and edit Gemfile as

For example, the output looks like:

Irbtools

Features

  • Colorized and output as comment by wirb and fancy_irb
  • Nice IRB prompt and IRB’s auto indention
  • Includes stdlib’s FileUtils: ls, cd, pwd, ln_s, rm, mkdir, touch, cat
  • Many debugging helpers:
    • ap – awesome_print
    • q –like p, but on …
  • Read More

    Disabling transaction block during migration


    Bookmark and Share

    Migrations are used to modify your database. By default, all migrations run inside a transaction. You can disable the transaction during migration. Let’s have a look on how to disable transaction block!

    Migrations can manage the evolution of a schema used by several physical databases. It’s a solution to the common problem of adding a field to make a new feature work in your local database, but being unsure of how to push that change to other developers and to the production server. With migrations, you can describe the transformations in self-contained classes that can be checked into version control systems and executed against another database that might be one, two, or five versions behind.

    In Rails, transactions are protective blocks around SQL statements that ensure changes to the database only occur when all actions succeed together. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically you should use transaction block whenever you have a number of statements that must be executed together or not at all.

    Eg:

    disable_ddl_transaction!()

    DDL can’t run inside a transaction block. You can disable DDL transactions in Rails, using disable_ddl_transaction. It is used in …

    Read More

    Using gmail to send email in Ruby on Rails


    Bookmark and Share

    Emails can be sent from you Rails application through many services like mandril, sendgrid, amazon SES. In this article, we would be explaining how we can send email using a Gmail credentials. Even though we can’t use it in production scenario due to the 500 email per day limitation, it would help us in prototyping an application quickly and also for cases where you want to send actual email in your development environment. Action Mailer is the ruby library in rails that will help us to do this.

    Action Mailer allows you to send emails from your application using mailer classes and views. Mailers work very similarly to controllers. They inherit from ActionMailer::Base and live in app/mailers, and they have associated views that appear in app/views.To setup action mailer, must do the following:

    1. Configuring the mailer in your environment file
    2. Generating the mailer
    3. Defining mailer action
    4. Generating the mailer view
    5. Delivering the email

    Action Mailer Configuration

    To configure action mailer add the following to your appropriate config/environments/$RAILS_ENV.rb file:

    Eg:

    Generating the mailer

    As you generate a controller for your application, you can …

    Read More

    Deploying Sidekiq to Ubuntu 16.04


    Bookmark and Share

    Sidekiq is a popular background processing tool available in Ruby. It’s fast, robust and reliable compared to other solutions out there. Sidekiq run as a process outside of rails (but including the rails environment), which means it doesn’t start when you start your rails application. During development, we start sidekiq in another terminal (or tab) using the command

    to run it as a daemon we use the -d option

    To kill a sidekiq daemon, you need to do  the PID of the sidekiq process. When a sidekiq process starts it enters its pid to file which can be found at

    So the command to stop it would be

    But making it a daemon is not a good idea, as there is no code from sidekiq to restart the process when it fails or exits on its own. So in ubuntu, which is our favorite OS for the production server, we make sidekiq a systemd process.

    Before we make it into a service and if you are using rvm you need to create a wrapper for systemd so that ruby with all the gems are available for it.

    Once that is done you need to create a sidekiq.service file under your ‘/etc/systemd/system/‘. You can find …

    Read More

    How to write maintainable routes in rails


    Bookmark and Share

    config/routes.rb is the gateway to your ruby on rails application. All request send by your users are directed to the appropriate code by the routes.

    Example:

    When someone visits your-website.com/profiles then the request is taken to the Index action of the UsersController. Under that action you will get the index.html.erb. So using routes we have configured the UsersController to respond to the users request it is its responsibility to do it now.

    We can declare routes in various ways:

    Since there are multiple ways to declare routes (as all forms are right), its best to stick with a single method for the code to be more readable. routes.rb is going to be one of the most heavily edited file in your project as when ever you add a new page or create a new form, you need to add a route to access the page or an end-point to accept the request. So it is most likely that your routes.rb file will start to grow ugly:

    So here we will share some tips to write proper, maintainable routes:

    First important point to note is that, its best to write routes as resources
    eg:

     

    declaring resources will create the following 7 routes.

    Read More

    Mina: Faster deployment and remote server automation


    Bookmark and Share

    Even though we use CodeShip/Circle CI/Jenkins for continuous integration, we still need to write scripts to automate our deployment. We also need to write small commands to clear cache, restart queues, etc. It’s always a good practice to not have to enter the server directly but to have it done through scripts. There are many tools available for this purpose (in multiple languages) like Capistrano, Vlad, etc.

    Mina is a similar tool, but faster. The reason why it runs faster is because it generates a bash script, uploads it to the server and run there, rather than creating a new ssh session and run every command one by one. Mina is one of our default tools at Red Panthers.

    To use mina in your project, add mina to your Gemfile.

    and to get started do

     

    http://nadarei.co/mina/setting_up_a_project.html
    https://www.digitalocean.com/community/tutorials/how-to-deploy-with-mina-getting-started

     

    Having a one step deployment is an important requirement for any project so have one ready using mina or capistrano.

     

    Note:

    Assets pre-compile

     

    Run another rake task

    Run shell commands

    The syntax queue is referring to the fact that, the commands are all made into a single shell script and then later executed together.

     

    Read More