More Rails Magic
Rails Magic is the term used to describe Ruby on Rails’ built-in syntactic sugar that provides concise, readable code that is enjoyable for developers to work with.
New Ruby on Rails developers may initially become frustrated at the way Rails utilizes conventions to abstract common programming tasks with minimal code, but it does get easier over time.
I received a taste of Rails Magic after joining an organization that was maintaining a monolithic Rails app with over 100,000 files in it. As I read through the codebase, I noted nearly every controller used delegate at the top.
It looked a lot like this:
class SomeController
delegate :foo, :bar, to: :baz
Searching Documentation
Unable to discern what was happening, I sought out Rails documentation on API Dock…
The documentation defined delegate as …a delegate class method to easily expose contained objects’ public methods as your own.
So delegate was allowing us to call an object’s method without referencing the object by name. We simply delegate the method to the object at the beginning of the controller and can reference the method from there on out.
Nice.
Examples
Now, two examples to illustrate this in practice:
With Delegate
class SomeController
delegate :foo, :bar, to: :baz
def some_method
return foo + bar
end
Withoout Delegate
class SomeController
# no delegate
def some_method
return baz.foo + baz.bar
end
end
Notice how much more concise the code becomes when we leverage delegate. We no longer need to reference the object and its method, we simply reference the method.
Bigger Picture
Imagine a codebase of 100,000+ files, many of which use the same objects and methods over and over.
At scale, you really start to realize the gains of this little piece of Rails Magic, and your colossal, monolithic Rails app becomes a bit more readable and maintainable.
Use of delegate is not just limited to controllers. In fact, its more widely used in ActiveRecord.
Note in the example below how we can use it with ActiveRecord associations:
class Greeter < ActiveRecord::Base
def hello
'hello'
end
def goodbye
'goodbye'
end
end
class Foo < ActiveRecord::Base
belongs_to :greeter
delegate :hello, to: :greeter
end
# "hello"
Foo.new.hello
# NoMethodError: undefined method `goodbye'
Foo.new.goodbye
When harnessed correctly, Rails offers an intuitive and enjoyable coding experience with its convention-over-configuration philosophy.
Using delegate is just one of many examples of Rails Magic in practice. I will share many more in subsequent posts!