DEV Community


Posted on

Using :source_location to unpack Rails magic 🪄🎁

I just watched Eileen Uchitelle - The Magic of Rails - Rails World 2023 and picked up a new tool... source_location

This method "Returns the Ruby source filename and line number containing this method or nil if this method was not defined in Ruby (i.e. native)." What does this mean? Well, it helps demystify some of the magic of Rails, which often has something to do with Metaprogramming 👻.

There are a lot of methods that get defined at runtime, so it can be difficult to figure out where they are coming from. Let's say we have a model Post which has_many :comments. We don't define a comments method, we just say there is a 1 to many relationship. We can use source_location to dig a little deeper and find exactly how that method is defined.

post = Post.first
=> ["rails/activerecord/lib/active_record/associations/builder/association.rb", 103]
Enter fullscreen mode Exit fullscreen mode

Super cool right?

Next time you see a method and you don't understand how/where it was defined, try using source_location.

Top comments (0)