11

Running rails generate controller Foo home results in:

class FooController < Application Controller
  def home
  end
end
(There's nothing on this line in the actual file, just a blank line)

Is there a purpose to this blank line?

Neil Kelty
  • 619
  • 1
  • 6
  • 9

2 Answers2

13

It's common to use a newline to indicate end of line, even for the last line. Many editors (like vi, which I use) add in this newline silently. The consensus is that text files (especially in the Unix world) should end in a newline, and there have been problems historically if it wasn't present. Why should text files end with a newline?

The tool I used to count the lines in a file "wc" just counts the newlines in a file, so without that trailing newline it would show 3 instead of 4.

It also improves the readability of the templates used in the generator. Consider: https://github.com/rails/rails/blob/master/railties/lib/rails/generators/rails/controller/templates/controller.rb

To remove the trailing newline, that template would have the last line of:

end<% end -%>

instead of:

end
<% end -%>

That seems less readable to me.


The discussion below refers to a blank line earlier in the file, instead of the trailing newline character.

It was an oversight and fixed in a later version of rails.

You can see in the commit history here where the blank lines get removed:

https://github.com/rails/rails/commits/master/railties/lib/rails/generators/rails/controller/templates/controller.rb

This is the commit where it was removed:
Remove redundant blank line at the bottom

It also shows you why it was there, previously they were just adding a blank line after each action.

Community
  • 1
  • 1
Shawn Balestracci
  • 7,380
  • 1
  • 34
  • 52
6

It is a common practice to end a file with a newline when keeping your source code in SCM such as git. Suppose, you add something at the end and commit the changes. Now compare the diffs in two cases.

1) Ending with newline:

--- foo_controller.rb   2013-04-18 09:14:48.000000000 +0800
+++ foo_controller2.rb  2013-04-18 09:15:10.000000000 +0800
@@ -1,4 +1,7 @@
 class FooController < ApplicationController
   def home
   end
-end
\ No newline at end of file
+end
+
+p FooController.methods
\ No newline at end of file

2) No newline:

--- foo_controller.rb   2013-04-18 09:16:28.000000000 +0800
+++ foo_controller2.rb  2013-04-18 09:16:35.000000000 +0800
@@ -2,3 +2,5 @@
   def home
   end
 end
+
+p FooController.methods

You see that diff treats "end" and "end\n" as two different lines which causes less clean view in the first case.

Simon Perepelitsa
  • 20,350
  • 8
  • 55
  • 74