Karol Galanciak - Ruby on Rails and Ember.js consultant

Indexes on Rails: How to Make the Most of Your Postgres Database

Optimizing database queries is arguably one of the fastest ways to improve the performance of the Rails applications. There are multiple ways how you can approach it, depending on the kind of a problem. N+1 queries seem to be a pretty common issue, which is, fortunately, easy to address. However, sometimes you have some relatively simple-looking queries that seem to take way longer than they should be, indicating that they might require some optimization. The best way to improve such queries is adding a proper index.

But what does “proper index” mean? How to figure out what kind of index is exactly needed for a given query? Here are some essential facts and tips that should cover a majority of the queries you may encounter and make your database no longer a bottleneck.

Trolling in Ruby - Implementing JavaScript-like Maths With Implicit Conversion Hijacking

If you’ve ever worked with JavaScript, especially in pre-SPA/pre-frameworks era with just jQuery, you probably had a chance to see an “exotic” maths in action that looks similar to this:

1
2
"3" + 4
// => "34"

That kind of behavior usually comes as a big surprise and due to that fact, JavaScript has gotten some bad reputation (even though there is a rationale behind it). If we tried that in Ruby, we would get an obvious TypeError:

1
2
"3" + 4
# => TypeError (no implicit conversion of Integer into String)

Would it be possible though to obtain the same result somehow in Ruby?

Explicit Conversion vs. Implicit Conversion

The answer is yes! But before we get to the actual implementation of that concept, let’s make sure that we understand some essential concepts in Ruby that will lead us there: explicit conversion and implicit conversion.

You’ve probably used methods like to_s, to_i, to_d, to_a etc. for explicit typecasting. That way, we can get the closest representation of a given object in a different type.

However, there is also a second type of conversion in Ruby, which is implicit conversion. Those are the methods like to_str, to_int, to_hash, to_ary. In most cases, you should not use those methods unless you are implementing an object that kind of behaves like some type, so, e.g., all numeric objects could (and they actually do!) implement to_int method as they are kind of the same type. For the same reason, if we were implementing some type of collection, we could implement to_ary method that would just return the same result as to_a which would be an instance of Array, but that we way put extra emphasis on the fact that this object behaves like an array.

We could also take advantage of implicit conversion to put some extra boundaries on the collaborating objects. Implicit conversion is widely used in Ruby for that purpose. When you are adding a string to a string like this:

1
"3" + "4"

Ruby under the hood calls “4”.to_str to get the string representation of that object (which is already a string) to make + method more flexible, but at the same time, it makes sure that only string-like objects are permitted as arguments.

Hijacking Implicit Conversion

Let’s get back to the original problem which was: how to get the following result in Ruby?

1
2
"3" + 4
# => "34"

Based on what we’ve just learned about implicit conversion, we just need to make sure that integers become somehow string-like objects. Let’s monkey patch Integer class and add to_str method that would be an alias to to_s:

1
2
3
4
5
class Integer
  def to_str
    to_s
  end
end

Let’s try out crazy maths again:

1
2
"3" + 4
=> "34"

Try the same for JavaScript and compare the results, it should be exactly the same.

Wrapping up

Ruby is an extremely flexible language which makes is it easy to do crazy things, just like it is the case with some operations in JavaScript ;).

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:

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.