Karol Galanciak - Distributed Systems Architect and Ruby on Rails expert

Rails and Conditional Validations in Models

Adding consents for accepting Terms of Service/Privacy Policies must have been a top popular feature in the majority of the applications due to enforcement of GDPR in May ;). From the technical aspects that GDPR requires, there is a proof of consent for processing the personal information. In that case, you need to have some actual attributes in the database that would confirm the fact that some user has indeed accepted Terms of Service/Privacy Policy.

That makes a significant impact on how we approach this kind of features. However, in the past, such things were quite often not stored in a database at all – it just took some UI acceptance validation or maybe a validation of the virtual attribute on the backend to be on the safe side.

Let’s focus on the latter case where we don’t need to store anything in DB and see what the possible solutions to that problems are. As trivial as this problem initially sounds, it will get quite interesting ;).

The Case for Before_validation Callback: Complex State Normalization

Few months ago I wrote a blog post about ActiveRecord before_validation callback and how it is used for wrong reasons and concluded that in most cases this is not something we should be using routinely. However, I missed one appropriate use case for it which might be quite common in Rails apps, so this might be an excellent opportunity to get back to before_validation callback and show its other side.

Advanced Ember Data Customization - Different Model Types in Ember App and API for the Same Resource

A great advantage of using Ember Data with JSONAPI-compliant adapters/serializers is that there is almost nothing extra needed to work with the data layer – just create the models with names matching the types of the resources returned by the API and you are good to go! However, sometimes you may need to customize the naming which means that the names of the models in the Ember application will be different than the ones expected by the API and their corresponding types. What are the steps required to make it work in Ember Data?

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:

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:

# app/models/photo.rb

class Photo < ApplicationRecord
  belongs_to :user, touch: true

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:

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:

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:

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:

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.