Karol Galanciak - Ruby on Rails and Ember.js consultant

Exotic Ruby: Module.class_exec, Custom JSON and Liquid Drops in Action

Ruby has quite a lot of “exotic” features that are not used that often, but when you need to utilize some metaprogramming magic, you can easily take advantage of them. One of such features is Object.instance_exec which you might be familiar with if you’ve ever built some more advanced DSL.

The great thing about Object#instance_exec is that it allows to execute code within the context of a given object but it also gives possibility to pass arguments from the current context. Thanks to that, we can build some nice DSLs and other features like this:

1
2
3
role_filter = ->(role) { where(role: role) }
role = "admin"
User.all.instance_exec(role, &role_filter) # same as User.all.where(role: "admin")

An interesting thing is that there is a class equivalent of Object#instance_execModule.class_exec. It would be easy to figure out some theoretical example how it can be used but what could be the real-world use case where this is the best approach to solve the problem?

Rails Quick Tips: Temporarily Disabling Touching With ActiveRecord.no_touching

Touching ActiveRecord models is quite a common thing in most of the Rails applications, especially useful for cache invalidation. By default, it updates updated_at timestamp with the current time, Here’s a typical example of using touch in a model:

1
2
3
4
5
# app/models/photo.rb

class Photo < ApplicationRecord
  belongs_to :user, touch: true
end

Whenever a new photo is created, or the existing one is updated/destroyed, the updated_at attribute of the associated user will be updated with the current time. In the majority of the cases, this is the desired behavior (it’s one of those rare ActiveRecord callbacks that is not that bad ;)). However, it might happen that you may not want touch to be executed for some reason. Is there any built-in solution that could solve that problem?

PostgreSQL Quick Tips: Working With Dates Using EXTRACT Function

Imagine that you are implementing an e-commerce platform and want to grab all orders from the current year. What would be the simplest way of doing it in Rails? Probably writing a query looking like this:

1
Order.where("created_at >= ? AND created_at < ?", Date.today.beginning_of_year, Date.today.beginning_of_year.next_year)

It gets the job done but requires unnatural filtering by a range for a use case generic enough that it should be handled just using some native functions. Is it possible?

Apparently, it is! We can use EXTRACT and now() functions – the former could be used for extracting the current year from a timestamp and the latter could be used for getting the current time.

With those two functions, the query could look like the following one:

1
Order.where("EXTRACT(year FROM created_at) = EXTRACT(year FROM now())")

Much cleaner! And the great thing is that you can also create a functional index for EXTRACT(year FROM created_at) to avoid sequential scanning and get much better performance.

The Aesthetics of Ruby - Kernel#itself Method

Recently, I’ve had quite a popular problem to solve: count the occurences of the given item in a collection. There are few ways to solve this problem – starting from using Enumerable#inject or Enumerable#each_with_object with an empty hash as an accumulator value and writing a code looking like this:

1
collection.each_with_object({}) { |item, accum| accum[item] = accum[item].to_i + 1 }

through a bit smarter way and taking advantage of the default hash value:

1
collection.each_with_object(Hash.new(0)) { |item, accum| accum[item] = accum[item] + 1 }

All these solutions look quite nice; however, there is one that looks particularly beautiful.

Traps on Rails - Overriding Boolean Methods in Models

One very useful feature of ActiveRecord is automatically defining attribute readers and writers for all the columns for given tables. For the ones with boolean type, however, there is one more addition – defining an alias of the method with a question mark. Sometimes it might be useful to override this method and add some extra requirements for a given condition. However, this might not be such a good idea.

The Case Against Exotic Usage of :before_validate Callbacks

It’s nothing new that ActiveRecord callbacks are abused in many projects and used for the wrong reasons for many use cases where they can be easily avoided in favor of a much better alternative, like service objects. There is one callback though that is special and quite often used for pretty exotic reasons that have nothing to do with the process when it gets executed – it’s the before_validate callback.

Do. Or Do Not. There Is No Try - Object#try Considered Harmful

Object#try is quite a commonly used method in Rails applications to cover cases where there is a possibility of dealing with a nil value or to provide flexible interface for handling cases where some kind of object doesn’t necessarily implement given method. Thanks to try, we may avoid getting NoMethodError. So it seems like it’s perfect, right? No NoMethodError exception, no problem?

Well, not really. There are some severe problems with using Object#try, and usually, it’s quite easy to implement a solution that would be much better.

5 Years of Professional Ruby and Rails Development - My Reflections

As hard as it is for me to believe, I already have over 5 years of professional experience in Ruby and Rails. Throughout all these years my attitude towards Rails has been fluctuating between going from blind love to harsh critic (ActiveRecord, I’m looking at you) ending with a bit more balanced but certainly a positive approach. Such time is long enough to have a meaningful opinion about the overall experience using any framework, so here are few points about Rails that I would particularly like to focus on in my reflections.

Ember Tips: Testing Outgoing HTTP Requests

Ember.js is a web frontend framework and it’s no surprise that majority of the applications deal with a lot of HTTP requests. But such fact has a lot of implications on the process of development of the Ember apps, especially when it comes to testing. For basic GET requests which don’t include any query params or don’t deal with pagination it’s quite straight-forward – for those we just want to fetch some data, so we can check if proper objects are present as a side-effect of these requests. What about POST, PATCH or DELETE requests, where we can’t easily test the side effects?

Fortunately, thanks to the awesome tools such as pretender and ember-cli-mirage, it’s not a big problem.

Ruby Memoization: ||= vs. Defined? Syntax

In the majority of the Rails applications or even Ruby gems you can find a lot of use cases where you need to memoize a result of some computation for performance benefits and to not compute it again if this result has already been computed. Seems like doing the assignment to some instance variable with ||= operator is the most commonly used solution for this purpose, e.g. @result ||= do_some_heavy_computation. However, there are some cases where it might not produce the expected outome and you should actually use defined? operator instead.