I always get great big lines of code at the top of my Rails models
. I am looking for suggestions for the best way to break them up with standard Ruby style. For example, one line I am looking at now is this:
delegate :occupation, :location, :picture_url, :homepage_url, :headline, :full_name, :to => :profile, :prefix => true, :allow_nil => true
What is the conventional style for breaking up these long method call lines?
Best Answer
The short answer is it depends.
Basics
For a start you can save few chars using the "new" Ruby hash syntax:
vs.
Hash/Arrays
Sometimes you need to initialize an array or hash, especially for hashes it's nice to write them this way:
The same hash on the same line would be (not as nice):
Various method calls
Some methods require many params or these params have long names:
In this case I would probably write it this way:
It's still not very beautiful but I guess is less ugly.
Again, not the most beautiful code on earth but It has some kind of structure.
Also, sometimes you could use variables to split lines. This is just an example, but basicly you name blocks of things (and sometimes after this you realise you can actually move that block in a method)
Blocks
Speaking of blocks (closures):
can be written like this:
If you have proper blocks try to use do-end instead of curly braces:
Conditional
Don't use the ternary if operator for complex things:
If you have complex if statements like this:
It's probably just better to move things in methods and make things not only shorter but also readable:
Long strings
Heredoc is your friend...I always need to google in order to get the syntax right but once you get it right is makes certain things nicer to read:
Queries
I tend to do this way for simple cases:
Sometimes queries are even worst. If I use squeel and the query is very big I tend to use parenthesis like this:
I'd say, if possible try to avoid complex queries and split them in smaller scopes or whatever:
This would be probably the best way.
The reality
Unfortunately people tend to write long lines and it's bad:
git diff
from the console having long lines is painfulI have a ruler in my editor so that I know when I'm about to cross the 80th char on the line. But rarely cross the line by few chars it's actually nicer than split it.
Conclusion
There are several ways of keep lines under the 80s and often depends on the situation. The problem with long lines is not just bad style, long lines are often a symptom of too much complexity.