ejoubaud
ejoubaud

Reputation: 5241

Document partial parameters in Rails

Is there any standard or emerging standard to document the parameters that can be passed into a Rails partial ?

When _my_partial.html.erb expects a title and an elements local var passed with render 'my_partial', title: t, elements: e, there must be a common way to document their names, expected types and roles, without reading the whole partial code. Something like RDoc or Tomdoc for methods and classes. Isn't there ?

Edit: I've found a post whose author advocates initializing parameters with <% var ||= 'default_val' %> in the first lines of the partial, which is indeed a safe practice and a kind of in-code doc. Is there really no comment/parameter-declaration solution for this ?

Upvotes: 4

Views: 379

Answers (1)

Luke Griffiths
Luke Griffiths

Reputation: 899

At the beginning of your partial, simply call all the variables that are referenced.

# _my_partial.html.erb
<% title %>            <---  first line of file
<% elements[0] %>

<h3><%= title %></h3>
<% elements.each do |element| %>
   <p> etc ... </p>

Reasons why this is good for your project:

  • it does not rely on comments or non-code files
  • any developer on the project can quickly find out which variables are needed by looking at the top of the file in question
  • by calling the variables, you ensure that a missing variable will result in an exception.
  • elements is called with square brackets because we also want it to blow up if it's not an enumerable, right?

The practice of using <% var ||= 'default_val' %> is actually unsafe because it allows bugs to hide. You want your code to immediately blow up the moment something isn't done right. And if these variables should be passed, then you want the code to blow up when they're not there.

Upvotes: 3

Related Questions