DEV Community

Ian
Ian

Posted on

2

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
post.method(:comments).source_location
=> ["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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay