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

    application_record.rb available since rails 5


    Bookmark and Share

    Those who have been starting with Rails 5, must have noticed the new application_record.rb file present in your model folder. And all new models seems to be inheriting the application_record.rb instead of the ActiveRecord::Base. This is done so that we don’t pollute the ActiveRecord::Base namespace with our own extensions.  Before when we require something, say an extension to the ActiveRecord itself we used to have it included using the following code.

    Now the problem with this approach is that when we use rails engines this NewFeature gets added in there as well, and it could end up doing things that we didn’t expect.

    With the new application_record.rb, which would be inherited by all the models, we need to include the new module at the ApplicationRecord and it would be available as the new feature of ActiveRecord. Every new engine generated using rails plugin new would also be having their own application_reocord.rb

    One more point to note is that we can place application wide hooks in this file. So if you were to do

    it would be triggered when a new record is created in any of the models of the rails application.

    Read More

    Working with timezones in rails


    Bookmark and Share

    Ruby on Rails being an amazing framework, helps us manage the timezone of our rails application. It gives us access to a lot of helpers, to make our life easier. For example, if you want to change all the date and time of your application to the logged in users time zone, we just have to place the following code in the application_controller.

    We assume that you have stored the user’s time_zone in your database in the time_zone column.

    The application  to show  timezone can be set in your application.rb, if we don’t set a particular timezone then the application will just show the systems timezone.

    If you want to know all the timezone options available in rails, run the rake -D time command in your terminal.

    Even though rails would take care of the timezone, when we are using certain ruby commands, it gives us our systems timezone and not the one set by rails. So to avoid surprises, we should be aware of the timezones we are exposed to.

    A rails app, would always be exposed to three timezones:

    • System timezone
    • Database timezone
    • Rails applications own timezone

    All three could be different, for example your system timezone could be in …

    Read More