redirect_to(options = {}, response_status = {}) protected

2017-10-02 21:25:18 +0000

Redirects the browser to the target specified in options. This parameter can take one of three forms:

  • Hash - The URL will be generated by calling url_for with the options.
  • Record - The URL will be generated by calling url_for with the options, which will reference a named URL for that record.
  • String starting with protocol:// (like http://) - Is passed straight through as the target for redirection.
  • String not containing a protocol - The current protocol and host is prepended to the string.
  • :back - Back to the page that issued the request. Useful for forms that are triggered from multiple places. Short-hand for redirect_to(request.env["HTTP_REFERER"])


 redirect_to :action => "show", :id => 5
  redirect_to post
  redirect_to ""
  redirect_to "/images/screenshot.jpg"
  redirect_to articles_url
  redirect_to :back

The redirection happens as a “302 Moved” header unless otherwise specified.


redirect_to post_url(@post), :status => :found
  redirect_to :action=>'atom', :status => :moved_permanently
  redirect_to post_url(@post), :status => 301
  redirect_to :action=>'atom', :status => 302

It is also possible to assign a flash message as part of the redirection. There are two special accessors for commonly used the flash names alert and notice as well as a general purpose flash bucket.


  redirect_to post_url(@post), :alert => "Watch it, mister!"
  redirect_to post_url(@post), :status=> :found, :notice => "Pay attention to the road"
  redirect_to post_url(@post), :status => 301, :flash => { :updated_post_id => }
  redirect_to { :action=>'atom' }, :alert => "Something serious happened"

When using redirect_to :back, if there is no referrer, RedirectBackError will be raised. You may specify some fallback behavior for this case by rescuing RedirectBackError.

Using Delayed Jobs in Rails

2017-09-26 09:00:40 +0000

When creating a web application sometimes need arises that we have to schedule some jobs during the execution of a particular method. Due to these job the render of the page has to wait until the task gets over. This waiting can be sometimes annoying because a user who is waiting for a job to get completed will have to wait for a lot of time if the number of jobs to be performed is more. For example if we take the scenario of sending mails to the user. Now for this if we have large number of users to whom we want to send a mail from our application so it will take a lot of time to get completed which no one will like to wait. So by using delayed jobs what we can do is we can execute the processes in the background and user wont have to wait till all the processes are completed. For that we will be using a gem called

gem 'delayed_job_active_record'

place this gem in your gemfile and run bundle install. Now after done with this we need to add the generator of this gem because active record actice records backend requires a job table in which the jobs will be stored in a queue. You can create the table by running the following command

rails generate delayed_job:active_record

and then run rake db:migrate Now when using this in development mode we need to set the queue_adapter in config/application.rb

config.active_job.queue_adapter = :delayed_job

with the help of this queue adapter we dont need to restart delayed Job every time we update our code in development. Now once done with this we will have to start the rake job in our console which will allow the jobs to run in the background without having the need to restart it again and again. We need to write this in console

rake jobs:work

This will start the rake job thread and will wait for a process or a task to come to it. Now last thing which we need to do is call the delay method where we actually need our jobs to be processed in background without affecting the current execution. Suppose oif you are sending a mail to all the users who have subscribed for a magazine so the users wont have to wait until the mail is sent to all the users. we will just add the delay method like this


Here notification mailer is the name of the mailer and notification_email is the method through which the mail is being sent. Now the mail will be sent to all users in the background and the execution of the method wont be delayed.

Before_validation and after_touch callbacks in Rails

2017-09-26 09:00:40 +0000

Rails provide us with some pre-defined methods or hooks which can be invoked after or before the execution of a certain method in the object life cycle. Callbacks are called in certain moments of object’s life cycle which we will get to know in this blog. Today we will be studying about three callbacks as follows : before_validation As the name suggests, this method is called before validation of all the fields of the form. For example, there is a registration form which has an email field, so as soon as the user will fill the email field and submit the form before the value gets saved into the database we have to make sure that all characters in the email should be down case. So in this case, we will invoke a before_validation callback in which we will define a method to be called before the create method is called. In this method, we will convert the whole string into down case and after that, the create method will be called like this.

class Employee < ApplicationRecord
  before_validation :normalize_email, on: :create
  # :on takes an array as well
  def create
    def normalize_email = email.downcase.titleize

after_touch Whenever an object is being touched the after_touch callback is called . For example We create an employee object and as soon as we touch the object the after_touch callback is invoked.

class Employee < ApplicationRecord
  after_touch do |employee|
    puts "The object has been touched"
>> e = Employee.create(name: 'Tom')
=> #<Employee id: 1, name: "Tom", created_at: "2013-11-25 12:17:49", updated_at: "2013-11-25 12:17:49">
>> e.touch
The object has been touched
=> true

So hope this article was helpful to understand both the callbacks.

Creating a random string on Rails

2017-09-26 00:49:08 +0000

As we know that in almost all web applications we have to ammend functionalities in which we need to create a random string. This string can contain some alpha numeric characters, numbers, lower case alphabets, upper case alphabets and etc. This random string or token can be generated for many purposes like OTP ( one time password), recovery code etc. Today we will see how to generate an eight character token with the help of arrays. This token will have some numbers, upper case alphabets and lower case alphabets in all jumbled up manner. Here is how we can do it…

token = (('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a).shuffle.first(8).join

now as we can see we have taken a variable token in which we are storing numbers from 0 to 9 in the second bracket we have taken all the lower case alphabets. in the third bracket we have taken all the upper case alphabets. and converted them all into array through to_a method. the plus sign concatenates all the arrays into one then finally the .shuffle method will jumble up the whole string and first(8) method will take the first 8 characters from that jumbled up string hence giving us the required token. Now everytime we will call this method it will generate a random string like this as seen in the picture below:

2.2.5 :002 > token = (('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a).shuffle.first(8).join
 => "a9bIGCwP" 
2.2.5 :003 > token = (('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a).shuffle.first(8).join
 => "OZimKuqJ" 
2.2.5 :004 > token = (('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a).shuffle.first(8).join
 => "c09NCv8Z" 
2.2.5 :005 > token = (('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a).shuffle.first(8).join
 => "SyVPNqso" 
2.2.5 :006 > token = (('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a).shuffle.first(8).join
 => "mLhlOeQT" 
2.2.5 :007 > 

So I hope this blog was helpful to create a random string for multi purposes..!!

Working with GREP in Ruby

2017-07-19 03:32:51 +0000

using GREP method in RUBY

Using grep in RUBY..!!!

As we know that ruby contains a lot of built in modules, in which one of this is the Enumerable module. So before preceddingon what GREP is and How it works, first lets study a little info about Enumerable module.

The Enumerable module provide us a lot of traversal and searching methods which also gives us the ability to do sorting. This module basically provides us simpler methods to manipulate collections with the help of searching, traversing and sorting. The class provides the each method which yields all the successive members of the collection. Enumerable module is included in the class as follows:

class dogs
  include Enumerable
  def breeds


GRIP First of all GREP is a powerful UNIX command. GREP is a fantastic and a very useful method which comes along with the enumerable module in Ruby. Using GREP is very handy and useful when it comes to manipulate collections instead of using a map or select methods. Along with, Grep is very useful in customizing the filtering, lets see how we can customize the filters. Firstly, put the categorization logic as case equal(“===”) in a class once it is done after that the instance of that class will be easily filtered out from an Enumerable object using GREP method. In the ruby methods of enumerable, we use “select” method for filtering and use “map” method for bulk transforming, but grep act as a combination of both these methods.

How does GREP work? To filter the elements in an enumerable object most of the time Select method is usedand it is done by passing a block in it, lets see an example how it is done:

["man", "van", "can", "dude", "pan", "fat"].select{|word| word.include?("an")}

This is a result in


The same thing with less complicated code and syntax can be achieved with this very useful method GREP as follows

["man", "van", "can", "dude", "pan", "fat"].grep(/an/)

which will also return the same result as above but now with a less complicated code. In the above example, what GREP did was it traversed through the array on which it was fired and it took out all the elements which had ‘an’ in them and gave us the resulting array. Grep returns an array for each element in the enum in which the pattern is exactly equal to the elements passed in the array. Grep works with regular expressions and all the other objects such as class and ranges.

Example of GREP are as follows:

 # this will result in  
 # => [2, 20, 200]

In the above example what grep did was it traversed through the array and picked up all the numbers between 2 to 200 and gave us the resulting array.

Lets see one more example

 # This will result in
 # => [4,5,6]

the same exampple for string :

 # This will result in
 # => ["a", "b", "c"]

and another example with join

 => "abc"
 => "a,b,c"

In this above example what grep did was it pulled out all the integers from the main array on which we fired the method and gave us all the integers in the resulting array. So, now I hope that the people reading this article would be through with what is GREP, How its used and how useful and handy it is when it comes to manipulate collections.

If you have any inputs or queries please feel free to post in comment section below

subscribe via RSS