logoalt Hacker News

chris1232105/05/20251 replyview on HN

It's been widely understood in the Ruby community for some time now that metaprogramming—like in the example above—should generally be limited to framework or library code, and avoided in regular application code.

Dynamically generated methods can provide amazing DX when used appropriately. A classic example from Rails is belongs_to, which dynamically defines methods based on the arguments provided:

class Post < ApplicationRecord belongs_to :user end

This generates methods like:

post.user - retrieves the associated user

post.user=(user) - sets the associated user

post.user_changed? - returns true if the user foreign key has changed.


Replies

t-writescode05/05/2025

Aren’t all these enhancement methods that are added dynamically to every ActiveRecord a major reason why regular AR calls are painfully slow and it’s better to use .pluck() instead? One builds a whole object from pieces, the other vomits put an array?

show 1 reply