Let’s imagine that you want to write your implementation of Rails where method. What for you need it? For example, if you have old RoR 2 project and you have no any wish to write where statements in pure SQL. What are the requirements of such service? You should have ability to chain where statements and transform all this into conditions for Rails 2 ActiveRecord.
You can see example of Ruby on Rails 2 ActiveRecord here. Example:
What can help us? Fluent interface. The main idea of this pattern is to return operating object on each method call.
For out implementation we will use two arrays, conditions and arguments to store corrseponding values. Additionaly we need a grammatical conjunction keyword to concatenate statements.
Then we need where method that will collect our conditions. As I said before there is no any magick, just store fields, arguments and return self.
When we have all this we need to transform conditions into RoR Array Condition. We will join our arguments with keyword.
And that’s all. Full code
And example of how it works.
You can easily add any kind of method that you want. For example if you are using MicrosoftSQL and you need to receive fields by date even if it stored in datetime you can realize your #where_date method. As MicrosoftSQL make some internal magick with dates escaping we will use a little trick and pass arguments directly:
And use it. If you have a lot of patience, with this technic in mind you can reailise full analog of ActiveRecord. And don’t forget to cover all this with tests.