Passionate Development From Journeyman to Master

Learning Notes #1

Last week at work, we had to rewrite the reporting module for our application, as there were some issues with the old report and the complexity of the code makes it hard to work out the cause of the issues.
Firstly, we pair programmed until we worked out the general direction for the implementation and then I took over the implementation while my colleague working on investigating the data source.

This report work forced me to learn more about ActiveRecord scope. What’s an ActiveRecord scope? According to Rails guide: >Scoping allows you to specify commonly-used ARel queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as where, joins and includes. All scope methods will return an ActiveRecord::Relation object which will allow for further methods (such as other scopes) to be called on it.

These two Rails guides on ActiveRecord helped me quite a bit:

Given that our report query is a little bit more complex than usual - it was quite difficult to get the scoping right. But after a lot of trial and error and re-reading the guides so many times - I managed to get the code that I am happy with.

I also found out about HashWithIndifferentAccess - by accident.. Having worked with Rails for awhile, I was under the impression that a string key for a hash is interchangable with a symbol key.

This is where I got Ruby and Rails mixed up. Lucky before I spent too much time ripping out my hairs - my colleague told me that I was thinking about Rails’ special hash not Ruby’s normal hash. This magical hash is called HashWithIndifferentAccess. Thank Rails. Anyway code speaks a thousand word:

>hash = { "hello" => "world" } >p hash["hello"] => "world" >p hash[:hello] =>nil >hash = HashWithIndifferentAccess.new >hash["hello"] = "world" >p hash[:hello] => "world"

rubyruby on rails