Developer at large, expert typist, fungineer

A tale of two Rails views

At sign

Why do I prefer to avoid referencing instance variables in view?

I needed to clarify this personal principle to a teammate recently. It was one of those things I’ve internalized so strongly that it was initially difficult for me to do so; one of those things that have become so true to me that teaching someone else about it requires getting past the “well, obviously it’s the best, that’s why” phase of mental tantrum.


An entirely made-up, possibly oversimplified Rails view fragment:

<p>Hi, my name is <%= @user.name %></p>

This is a by-the-book Rails view. Set an ivar in an action, use it in views (and helpers), you’re done, get back to thinking about building product.

It’s easy to iterate with this. It’s easy to see data “passed”1 into the view by scanning for the @ sigil; your editor probably does this already. It’s easy to move markup around in templates with a simple cut-paste.

If you stick with ivars long enough, you’re going to end up with two kinds of misadventures.

Most commonly, you’ll wonder why @user is nil for some view or edge case. Maybe you forgot a filter or didn’t set it in an action? Backend developers are sometimes equipped with the curiosity and knowledge to fix this themselves. For front-end developers or those new to the system, this kind of error is basically “womp-womp sad music go interrupt someone who can help you”.

This leads to the second misadventure: where did this @user thing come from2? Maybe it was set in a helper, or a filter, or an action? Well now you’ve painted yourself into a weak spot of a language like Ruby. Your tools probably can’t point you directly at the line of code where a variable came into being. You can do some clever grep’ing around3, probably. At best, you know the system well enough to get to the right file and find it, or there’s some convention you can use to intuit where it might be set.


Of course this way is better, right?

<p>Hi, my name is <%= current_user.name %></p>

Well, not initially. Already you have to pick a good name for a method because you’re probably going to use it all over the place. Then you have to find a good place to put that method: on a helper method? on a helper object? on a model?, i.e. now you’re making decisions, which is a thing Rails tries to shield you from wherever possible. Personally, I find naming things quite entertaining and hardly one of the hardest problems in computer science4.

A marginal benefit comes from reducing the entry points that the name current_user came to be a thing in this view: it’s a method name, a local variable, or a view-local variable passed into the template5. Thus the search space for “where did this thing come from” is way smaller for typical Rails templates and manageably smaller for unreasonable Rails templates.

This way pays off once the application gets past the point where new code tidily fits into models, views, controllers, or helpers. At that point, you need objects, messages, and experience at building with objects and messages (successes, stalemates, and abject failures)6. If you’re competent at messages (i.e. method calls) in Ruby, you can at this point experience a “this is Unix, I know this!”7 moment and work with this method call like you would any other method/function invocation in a computer program.

Making this investment into a method call yields another long-term benefit: simplicity in experimentation and testing8. I can poke at helper methods and helper objects in a Rails console without breaking a sweat. If that feedback loop doesn’t get the job done, I can write tests against helpers and (some) controller methods to iterate on figuring out why something doesn’t work the way I think it should.


It’s amazing that blogging about programming is so popular. Programming involves a lot of tradeoffs. Tradeoffs make for wordy articles that don’t leave you thinking “yeah, those other guys are SOOOO WRONG” or “YEAHHHH I’m so right”.

If I’ve written this properly, hopefully you felt both of those feelings. Maybe you reminisced about a day when you thought view ivars were great and then regretted it. Perhaps it’s easier to see why you’d start an app or feature off using ivars and then refactor them to method calls later.

With instance variables in views, as with many other grey areas of Rails, the most useful long view is this: you’re always right, and you’re always wrong, it just depends on which “you” (past you, present you, legacy project you, greenfield project you) is being observed.


  1. I’m not using “passed” as scare quotes here. Rails’ choice to take ivars from actions and teleport them into views is oft villified, but I find it more useful to think of them as something that just is. They are incredibly useful at first, but some developers will long for an explicit contract (i.e. a parameter list) between action and view. 
  2. If you’re an object design enthusiast, functional programming aficionado, or Rails contrarian you may be crafting an amazing retort about sharing state in weird ways at this point. Please review the previous footnote. Yes, you’re basically right. No, that’s not going to change how Rails works. 
  3. Regexes, two problems, etc. 
  4. Actual hard problems in computer science: systems connected by unreliable (i.e. any) network, laws and regulations written by humans, working with money. 
  5. When it comes to variables in Rails templates, a short guide by Adam Keys; method names: friend, ivars: foe, local variables: foe, view-local variables (passed via render explicitly or by the framework): both! 
  6. This is the concise version of a seems-really-important-to-me idea I need to express in more words. Remind me to write this, should I forget about it, internet! 
  7. What up, Ariana Richards
  8. You knew the testing thing was coming, didn’t you? I mean it’s like Chekov said about guns in stories: if method calls are mentioned in the first act, you have to mention TDD in the last act. If you headdesk’d, consider that you might be annoyed by TDD because you keep giving yourself a head injury when it’s mentioned. 

2 Responses to “A tale of two Rails views”

  1. Mrchris

    These days, I usually aim for only having access to a @presenter and a current_user in my views.

    Regarding the Naming things thing, I find it a massive Pita.

Comments are closed.

Follow

Get every new post delivered to your Inbox.

Join 2,590 other followers

%d bloggers like this: