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 …

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 …
  • Read More

    PStore, a little known feature in the standard library


    Bookmark and Share

    PStore(persistent store) implements a file based persistence mechanism based on a Hash. It writes Ruby objects to an external file so it can access easily if needed. If an I/O error occurs while PStore is writing to its file, then the file will become corrupted.You can prevent this by setting pstore.ultra_safe = true. Also, it supports thread-safe and uses Marshal internally.

    To use this library, you must require it and instantiate a new object.

    Which would create a file that stores the content to be written.

    To store or retrieve data from the data store, you must open a transaction. Here transaction is a protective wrapper around SQL statements to ensure changes to the database only occur when all actions succeed together. We can access the content of database only through this transaction.

    At the end of the transaction, all changes are committed.

    Public Instance methods

    Instance methods are methods that are called on an instance of a class. We can use the below methods while using PStore instances.

    • p[name]=obj

    Stores obj in the database under the key name. When the …

    Read More
    Behind the scenes of hash table performance in ruby 2.4

    Behind the scenes of hash table performance in ruby 2.4


    Bookmark and Share

    Ruby 2.4 got released this Christmas with a lot of exciting features. One of the most underrated features in ruby 2.4 is hash table improvements. Before going into details about implementation, let’s first check the benchmark to know how this change gonna affect your ruby application.

    Some benchmarks are:

    Getting keys and values of a hash

    Output

    Ruby 2.3.3

     

    ruby 2.4.0

    Yeah, the above two operations executed ~ 3 times faster on my laptop. Though these numbers can vary with your machine and processor, the performance improvements will be significant on all modern processors. Not all operations became 3 times faster , average perfomence improvement is more than 50%

    If you are a ruby developer and excited to know what are the new features in ruby 2.4, then this feature gonna make your application faster and you don’t have to change anything in the code for that. Because these changes are backward compatible. If you are curious to know what happened behind the scenes of this performance boost, then continue reading.

    Hash Table

    In computing, hash table (hash map) is a data structure that is used to implement an associative array, a …

    Read More

    Chartkick: data visualization made easy with Ruby


    Bookmark and Share

    Recently, I’ve been using Highcharts, Google charts and Chart Js for visualizing dynamic data in my projects. But it was difficult to integrate it with the rails application. However, for every problem in Ruby, there is a gem out there to save your day and Chartkick, a Ruby gem exclusively available for data visualization is truly a savior. Chartkick can work with Highcharts, Chart.js and Google charts to create dynamic and interactive charts that draw data from the Rails application. And the best part, you just need to write one single line of Ruby code. Isn’t that amazing and powerful!

    Let’s begin with Installation

    For installation, all you have to do is adding this line to your application’s Gemfile:

    Then you have to choose your charting library.
    In case, if more than one charting library is loaded, choose between them with the following code:

    P.S:- highcharts is the default adapter is nothing else is defined.

    Using Chartkick

    Once it’s installed, you can start playing around with chartkick. For example:

    In the above example, I have just shown you how we can make a line chart.Similarly, you can create Pie chart, Column chart, Bar chart, Area …

    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 …

    Read More

    Lambda vs Proc Vs Blocks


    Bookmark and Share

    The difference between these three is one of the most baffling concepts to grasp while anyone starts to learn ruby. Since at Red Panthers we recruit and build our own team from freshers, we too will be blogging about it here to make it easy for the beginners.

    But before we state the difference between the three, let me explain what all these three does to make it easy for you.

    Blocks: They are called closures in other languages, it is a way of grouping code/statements. In ruby single line blocks are written in {} and multi-line blocks are represented using do..end

    An interesting fact about ruby is that all methods in ruby accept a block, even if you don’t declare a variable to accept it. So for example, take the method below

    It can accept a block as below

    The code is valid, but the output will have only puts “Hello World”.

    Why? because we passed in the block but it is not getting called. To run the block passed within your method you need to use the yield command.

    Now it will print

    But since we placed yield, it would now be expecting a block to be always passed in. …

    Read More

    Lazy enumerator to handle huge files


    Bookmark and Share

    Lazy evaluation, or call-by-need is an evaluation strategy which delays the evaluation of an expression until its value is needed. It’s frequently seen in functional languages, ruby introduced the lazy method in Ruby 2.0. For those who don’t know what are enumerators: enumerators are something that can be counted. So a collection of elements, files (file is an collection of lines of string), etc can be treated as an enumerator.

    In ruby we need to make something countable into an enumerator object, which is done by applying .each and .map on it.

    Ruby has a wide range of operations we can do over a collection, it’s one of those features that makes Ruby such a powerful dynamic language. An enumerator can be used to generate series like the Fibonacci series.

    But when we do a .map / .each with a code block, then it would try to realize the enumerator fully and then apply the block over it.

    That would be fine when we are working on something small like:

    But when we take the above fib enumerator, which will grow into an infinite series, adding a .map would lead the code to an infinite loop. If you are crazy …

    Read More

    Counter Cache: How to get started

    Displaying the number of tasks under a project or the number of comments in a post or the number of users in an organization or anything similar is a common requirement in most rails applications. The code for doing it is also simple- @project.tasks.count; but the problem with this code is that every time you run it, you are counting the number of tasks of that project one by one. So, the speed of execution decreases with more number of rows. This code will slow down your page load, if you are displaying the details of more than one project in your page as shown below.

    project_list

    To speed this up, rails gives you an in-build mechanism called “Counter Cache“. As the name suggests, it literally means to cache the number of referenced rows it has (number of tasks a project has).

    Example code definition

    To implement counter_cache, you need to pass in the counter_cache: true option along with the belongs_to relationship. You also need to add a migration to add an extra column called tasks_count to store the count. This needs to be added to the other model, which has the has_many reference.

    Migration

    If you are adding counter cache to an existing system, you need to update your tasks_count with the existing counts. To do that, one can use the code given below. Either place the code along with the migration or run it in console in both production/development environments.

    Also note that the tasks_count is just the default column name; if you wish to change it with another name, just pass that name along with the :counter_cache option as below.

    Now, to use the counter cache in your calculations, you should use the method “size” instead of “count”. The method “size” will use the counter_cache if its present, where as using “.count” itself would do the actual sql count.

    Points to Remember

    • :counter_cache is the …
    Read More

    Experience Attending RubyConf India for the first time


    Bookmark and Share

    We (the team) at Red Panthers were happy to sponsor a student, Neethu Sajeevan from Cochin University, to attend RubyConf India this year. We hope to support more students in the coming years. You can find the article she wrote about her experience re-blogged below.

    Re-Blogged from:

    I attended the RubyConf India Conference that took place from 19th March to the 20th March 2016 at the Le Meridien Kochi in Kochi, India.I express my heart-felt-gratitude to Red Panthers https://redpanthers.co/, the digital sponsor for RubyConf India2016 who sponsored my ticket. Attending the conference was a very valuable and engaging experience for me, to hear from passionate and creative people speak about their work.
    The conference covered areas like Ruby Language, Framework and Tools and well known speakers from international Ruby community. We (Anila Anne George and me myself ) thank our sponsors for giving us this great opportunity. As students this was the first professional conference that we attended.

    Read the full article at: https://medium.com/@neethusajeevan/rubyconf-india2016-experience-of-a-first-timer-cc8c95f34781#.sd744qmsb

    Read More