Earlier quoted context omitted.
Other people have mentioned "dynamic typing" as being the reason for this, but that's not actually true. The real reason is two Ruby features: `define_method` and `method_missing`. If you have a class `Customer` with a field `roles` that is an array of strings, you can write code like this class Customer ROLES = ["superadmin", "admin", "user"] ROLES.each do |role| define_method("is_#{role}?") do roles.include?(role)…
To add, the above code is a pretty near approximation of the literal code inside the devise codebase, which is a very standard Ruby auth system. See here: https://github.com/heartcombo/devise/blob/main/lib/devise/co... def self.define_helpers(mapping) #:nodoc: mapping = mapping.name class_eval That code is *literally* calling class_eval with a multi-line string parameter, where it inlines the helper name (like admin,…
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 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.