Rails i18n pluralization

Sometimes we need to show different text based on some count. Like for example: if box_count == 0 message = "No boxes present" elsif box_count == 1 message = "Only 1 box present" else message = "There are #{box_count} boxes" end You can refactor this to make use of i18n locales power. In en.yml you can do - en: boxes: message: zero: No boxes present one: Only 1 box present other: There are %{count} boxes And in view we can use: <%= t('boxes.message', count: 2) %>

Access files from sftp server

In one of the feature, we had to import xlsx which was exported from sqlite database dump. The rows had few image names which was uploaded to sftp server. We had to upload those to images on S3. Importing xlsx row data was simple but the challenge was how to upload images from sftp server to S3. This is where net-sftp gem came to our rescue (though its not managed anymore). To get this working, we need 4 things: host, username and password using which we are going to login to sftp server and path where images are uploaded. We

Protection from abusive clients and malicious scripts

Many times websites get hit by unreliable sources which can mainly be automated scripts that continuously hits a web url which can cause DOS(Denial of Service) attack. In Rails, we are handle such types of attacks by restricting the requests at Rack level. Rack is a middleware which can serve as "a way to filter a request and response". For this, we can use [rack-attack][1]. Example: Rack::Attack.blacklist('allow2ban rapid send_verification_code') do |req| if req.post? && req.path == '/api/v1/verification/send_verification_code.json' Rack::Attack::Allow2Ban.filter(req.ip, maxretry:

Prepared statements in Rails

Rails 3.1 and above has an awesome feature of prepared_statements. The basic idea behind prepared statements is to compile SQL statements once and cached for it future use. In other words - The benefit to prepared statements is that the database does not have to compile a query plan for every piece of SQL sent to it, potentially saving a lot of time. Checkout an excellent blog(blog) to know more on prepared_statements. Recently, I had to get raw sql from AR object so that I can pass it to EXPLAIN statement to get total number of

Configuring database_cleaner

Recently I added few integration tests in my projects using Capybara and Selenium webdriver and ran into banging my head against inconsistencies with test database. I create some records in test DB which were completely invisible to Selenium-driven browser-based tests. The problem is: the tests are being wrapped in database transactions, so any code running outside the actual test process (like, say, a server process servicing a Selenium-driven browser request) does not see the database records. Here are the steps to fix this problem - First of all, and this is very important, go into spec/spec_helper.rb and

Access Rails locale in Javascript

For displaying flash messages and other informative messages, we generally use Internationalization (I18n) in rails. Sometimes we also need to write similar messages again in javascript/coffeescripts which can be difficult to manage if these message changes. And also it doesnt follow the concept of DRY. To follow DRY, we need to make rails locales available in javascript. One way to do it is to declare a global variable and have all locales saved to it as Javascript Object. This is what we did in our project: Added following code in application layout: For HAML - window.I18n = #{I18n.backend.

Rails best practices

Please find attached pdf file for Coding Standards. Also, refer following git repo for all Ruby idoms: https://github.com/bbatsov/ruby-style-guide Gem you should consider for refactoring and code formatting: rubocop cane rails_best_practices For code complexity use flog gem. Refer post [here][1] for more details. Happy Refactoring :) [1]: http://knowbuddy.kiprosh-app.com/kyu_entries/ruby-code-quality-metrics-and-security

Recurring Sidekiq jobs

In most of our apps, we probably need to execute few background tasks more often, like every 10 minutes, once a week, etc. For scheduling these jobs, we need a scheduler that can re-run these tasks on specified intervals. There are few schedulers like whenever, resque-scheduler, rufus-scheduler, etc that can do the job. However, these gems are not compatible Sidekiq and with apps deployed on Heroku. There are 2 ways to make it work on Heroku. 1/ Using Heroku Scheduler addon. Steps: i) Create sidekiq job. ii) Create a rake task that will triggers that worker. iii) In Heroku Scheduler

Reload or Add routes at runtime in Rails 3

In one of our eCommerce app, we needed SEO friendly Menu urls like /brandy/cognac. For this, we added a generic route /:parent/:child/:grandchild at the bottom of config/routes.rb. With this approach, there was an issue with invalid urls like /this/is/wrong being redirected to specified controller action. To fix this, we used Menu names to generate specific urls. But the routes would become invalid if Admin changes the menu name. So we needed a way to reload routes once the menu is updated. I found a hack mentioned in [this blog(Blog)][1] that allow

Ruby Code Quality Metrics and Security

Code Climate is a great web-tool to check code complexity, duplications and security vulnerabilities. Internally, code climate uses Flog to calculate code complexity and BrakeMan for security vulnerabilities. But it checks only when we commit code to Git. We can check code complexity and security issues before committing to git. For code complexity: install flog gem install flog Goto project root path and run command: find path_of_file -name *.rb | xargs flog For example: find app/controllers/application_controller.rb -name *.rb | xargs flog It will display the total complexity for the class, complexity per method and complexity of