DEV Community

Cover image for Uncovering tiny little magic in Rails
Soo Yang, Tan
Soo Yang, Tan

Posted on

Uncovering tiny little magic in Rails

Recently I got really curious with one of the magical things in Ruby on Rails framework. Let's take a look at the following code:

class User < ActiveRecord::Base
  validates_presence_of :name
end

As a Rails developer, we understand that validates_presence_of :name helps us to easily perform a modal validation to ensure that the name attribute must be present. BUT wait a minute.. where does this come from?

The beauty of Rails is that the framework provides a bunch of methods we could conveniently use out-of-the-box to perform difficult things easily. Back to our example, we can find this magical method validates_presence_of being defined inside the rails sourcecode. This magic is just another class method.

You may be curious on how did I manage to find the method in the source code. A good starting point to look at the rails sourcecode would be under activerecord since our model inherits from ActiveRecord::Base.

This is quite a common pattern in the Rails world. Some other examples would be has_many, acts-as-taggable, has_paper_trail and etc.

You can easily implement this pattern in your project. All you have to do is to define a class method in your parent class. You sub class will be able to use the method right away. Below is a simple code sample to demonstrate on how you can write it yourself.

class Employee
  def self.onboarding_pack(department)
    # Insert any complex logic here. For simplicity, this sample only prints a sentence. 
    puts "Onboarding pack for #{department} employees"
  end
end

class Developer < Employee
  onboarding_pack "Developer"
end

class Clerk < Employee
  onboarding_pack "General"
end

puts Developer.new # Onboarding pack for Developer employees
puts Clerk.new # Onboarding pack for General employees

Takeaway

Alot of convenient things (methods, generators and etc) provided by Rails will seem like magic on the surface. If we stay curious and take a dive into the rails sourcecode, you will be able to uncover its magic.

Top comments (2)

Collapse
 
panoscodes profile image
Panos Dalitsouris

Cool article 🎉 There is also a great talk on how to dive into rails core !!!

Collapse
 
sooyang profile image
Soo Yang, Tan

Thanks for the share. Great talk!