views:

590

answers:

5

I want to read only the first line of a file using Ruby in the fastest, simplest, most idiomatic way possible. What's the best approach?

(Specifically: I want to read the git commit UUID out of the REVISION file in my latest Capistrano-deployed Rails directory, and then output that to my tag. This will let me see at an http-glance what version is deployed to my server. If there's an entirely different & better way to do this, please let me know.)

+1  A: 
first_line = open("filename").gets
yjerem
+1  A: 

You can try this:

File.foreach('path_to_file').first
Vincent
LocalJumpError: no block given
klochner
@klochner: Your Ruby is old. This works fine in 1.8.7 and above.
Chuck
Sorry Vincent, I can't remove downvote unless you make some minor edit.
klochner
Sorry guys. Chuck answer is the right one.
Vincent
I upvoted this one because I like the "first"ness of it. Unfortunately, my Rails host (DreamHost) is only on 1.8.5, so it isn't the "correct" one for me. :-\
Craig Walker
I like the expressiveness of "first" but I don't like the "foreach", which is misleading. I suppose the "perfect" (?) answer is to monkey-patch a File#first_line(path) method.
Mike Woodhouse
+11  A: 

This will read exactly one line and ensure that the file is properly closed immediately after.

File.open('somefile.txt') {|f| f.readline}
Chuck
+3  A: 

How to read the first line in a ruby file:

commit_hash = File.open("filename.txt").first

Alternatively you could just do a git-log from inside your application:

commit_hash = `git log -1 --pretty=format:"%H"`

The %H tells the format to print the full commit hash. There are also modules which allow you to access your local git repo from inside a Rails app in a more ruby-ish manner although I have never used them.

jkupferman
+1  A: 

I think the jkupferman suggestion of investigating the git --pretty options makes the most sense, however yet another approach would be the head command e.g.

ruby -e 'puts head -n 1 filename' #(backtick before head and after filename)

Andy Atkinson