- 09 October 2016
- Patterns Ruby Design
- Ruby - Strategy Pattern
Recently I wrote about template pattern. Today I would like to talk about another useful pattern - decorator.
Today I would like to show by simple example how to use template pattern in Ruby.
I'm sure you will find many ways of using that pattern in your application.
Hi. Today I would like to talk about memoization in Ruby.
But to begin, let's consider some abilities of Ruby. Often, we want to assign result of execution of function to some variable. If result of execution is false
or nil
we would like to assign some default value.
After couple of theoretical posts (Tell, Don't Ask and Law of Demeter) I want to write about more practical things.
About something that we use on everyday's job dealing with arrays and hashes.
There is a great principle in object-oriented programming which says: "Tell, Don't Ask".
This principle tells that we should not ask object about their state, make decision and only then tell them what to do. Rather we should send commands.
There is a good quote about that:
Today's post will be more about Ruby On Rails and ActiveRecord. But first things first. If you didn't hear about Law of Demeter, I really recommend to read about it.
In general - it's a set of rules which bounds knowledge of modules about each other and allows you to reduce coupling of your system.
Here is how Wikipedia describes it:
Refinements has been added to Ruby to replace popular, but bad approach called Monkey Patching.
Let's check what Monkey Patching is and why it is bad.
For example, we have a class User
, which has method to_s
:
The best way to understand how Module#prepend
works is to figure out method lookup process in Ruby.
If it's a simple inheritance and method is present in parent class but not in a main class:
Ruby is not a strong typed programming language, so methods can accept arguments of any type. But sometimes we want to make sure that value we accept is an Array.
I've seen many times that developers do something like that: