Tuesday, February 12, 2013

SQL logs in Rails console


While working on different Rails projects, I often find it useful to see behind the scenes SQL queries in the console itself. We can the view the SQL queries in the log file itself, but I find it easier to look at the SQL queries at the console itself.

For this purpose in my Ubuntu 11.10, I have created a file called .irbrc in my home directory and have pasted the below contents in that file.

1:  require 'pp'  
2:  if ENV.include?('RAILS_ENV') && !Object.const_defined?('RAILS_DEFAULT_LOGGER')  
3:       require 'logger'  
4:        RAILS_DEFAULT_LOGGER = Logger.new(STDOUT)  
5:  end  


Now after starting the console, the output for any ActiveRecord operation shows the sql query also

Here is a simple output from the console
1:  >> User.all(:limit => 1)  
2:   User Load (0.9ms)  SELECT * FROM "users" LIMIT 1  

Not, I could test this only in Rails 2.

MailCatcher gem: Testing emails in Development mode in Rails

Well, I am writing this post after a long long time. Had some personal priorities to take care of.

Few days, back I was given a task, to develop a module where I had to write code for sending notification mails to different kind of users based on different actions/events in the application. Sending mails with ActionMailer is not that tough, but in my development environment I was not available to find  out how will the contents of the mail will actually look like when it is sent to the users.  I needed some simple way to test it.

While searching in google, I came to know about the mailcatcher gem and I am glad that I found it very easily :)

It is very easy to setup and configure mailcatcher in your project. 

First, you will add the following line in your gemfile

 gem 'mailcatcher'  
bundle install
Then you have to do the following changes in config/development.rb
 config.action_mailer.delivery_method = :smtp 
config.action_mailer.smtp_settings = { address: 'localhost', port: 1025 }
Then start/restart your rails app and mailcatcher daemon from terminal just by typing mailcatcher
saurav@saurav-Vostro-1540:~/workspace/my_project$ mailcatcher 
Starting MailCatcher 
==> smtp://127.0.0.1:1025
==> http://127.0.0.1:1080  
Now on opening http://127.0.0.1:1080 in your browser and you can see a virtual inbox and if you send some mails from your application, you will be able to see the mails in the inbox created by 'mailcatcher' gem. 

The most important feature of this gem, is that it allows you to see the HTML,Plain Text and Source view of the mails.

Thats it. Now test your mails :)