Rishi talks about writing clean code and avoid conditional blocks whenever and wherever feasible using Null Object Pattern.
Category: General
Things To Remember While Working With Uniqueness In Rails
validation_uniqueness_of does not guarantee uniqueness. Interesting write-up by Yogesh about things to remember while working with uniqueness in Rails.
♦ The Problem
Consider the following relation where poll is having many options and each option of the poll must be having a unique description,
Now, when trying to create a poll with its options using nested attributes, uniqueness validation is not getting applied due to race condition.
> poll = Poll.new(options_attributes: [ { description: 'test' }, { description: 'test' } ])
> poll.save
=> true
>
> poll.options
=> [#<Option id: 1, description: "test">, #<Option id: 2, description: "test">]
♦ Why it is occurring ?
There is a section in UniquenessValidator class, which mentions that the ActiveRecord::Validations#save does not guarantee the prevention of duplicates because, uniqueness checks are performed at application level which are prone to race condition when creating/updating records at the same time. Also, while saving the records, UniquenessValidator is checking uniqueness against the records which are in database only, but not for the records which are…
View original post 128 more words
How The Use Of Service Classes Enhances Code-quality
Good post from Rishi on how to refactor code into Service Objects to improve code maintainability and quality.
Learning shall never stop..!!!
ServiceClasses are nothing but plain old ruby classes. But they go a long way to keep your controllers thin and models thin. To show what I mean by this, lets look at some code. This is the code in controller to download data following some set of rules.
This is bad. The controller should not look like this. Comes in Service classes.
The ideology behind service classes is that it should have only one purpose to serve and nothing else.
And I can clearly see a purpose which our new service class should serve and that is to provide the data for our template download and nothing else. I keep the service classes under app/services folder. Also I do not think I need to iterate much on the importance of the name of the service class you choose. It goes without saying that the name should tell the purpose it…
View original post 237 more words
