Confident Ruby makes the case that writing code is like telling a story, and reading code littered with error handling, edge cases, and nil checks is like listening to a bad story. The book presents techniques and patterns to write more expressive code with less noiseâ€”to tell a better story.
And, My favorite in the review list is BRE GTFO LOL where “BRE” stands for
In our day to day Rails coding routine, we come across lot of methods which use Rails arel methods directly like
update_all etc. and sometimes the code story telling gets a back step in logic of arel chaining.
Here is a way which I came across to surface it up right in front and that too without loosing the coolness of arel chaining.
class Post # update callback def refresh_cache if publishability_changed? refresh_categories_cache_timestamp end end def refresh_categories_cache_timestamp categories.update_all(last_cache_refreshed_at: Time.current) end end
Here, reading code littered with
update_all breaks the story telling flow, yet again, and could be better expressed with below snippet.
class Post # update callback def refresh_cache if publishability_changed? refresh_categories_cache_timestamp end end def refresh_categories_cache_timestamp categories.refresh_cache_timestamp! end end
class Category def self.refresh_cache_timestamp! update_all(last_cache_refreshed_at: Time.current) end end
Comparing the two snippets, After scores extra points on story telling as compared to Before.
We would be happy to respond to queries/questions in comments.
Tried on: Rails 3.2.16 with Ruby 1.9.3