1

I have a rake task that is used to set up a bunch of symlinks, but only if they don't already exist. Currently when you run the task, there is no output. So you don't know if anything happened. How can I provide output like Rails generators do by saying 'created' or 'skipped' for each of the symlinks? What gems or modules do i need to include to get this type of functionality?

# example
task :setup do
  if !File.symlink?('/example/link')
    %x{cd /example && ln -s /something link}
  end
end
Andrew
  • 227,796
  • 193
  • 515
  • 708
  • 1
    have a look at this question & answers: http://stackoverflow.com/questions/2246141/puts-vs-logger-in-rails-rake-tasks – bento Jul 19 '12 at 18:19
  • @Béla that one is talking about using the Rails logger. Not exactly what I am trying to do. – Andrew Jul 19 '12 at 19:52

1 Answers1

0

I would probably use Ruby's FileUtils ln_s functionality for this.

ln_s(old, new, options = {})

Creates a symbolic link new which points to old. If new already exists and it is a directory, creates a symbolic link new/old. If new already exists and it is not a directory, raises Errno::EEXIST. But if :force option is set, overwrite new.

FileUtils.ln_s '/usr/bin/ruby', '/usr/local/bin/ruby'
FileUtils.ln_s 'verylongsourcefilename.c', 'c', :force => true

...

ln_s(list, destdir, options = {})

Creates several symbolic links in a directory, with each one pointing to the item in list. If destdir is not a directory, raises Errno::ENOTDIR.

If destdir is not a directory, raises Errno::ENOTDIR.

Andrew
  • 227,796
  • 193
  • 515
  • 708
Peter Brown
  • 50,956
  • 18
  • 113
  • 146
  • So what does `FileUtils.ln_s` provide that `%x{ln -s}` does not? – Andrew Jul 19 '12 at 19:57
  • @Andrew You don't have to worry about reading input and parsing it from the system call. You can rescue from the Errno::EEXIST exception and handle those cases when the file already exists. Also, %x{} is like doing eval() on the system, it's a bad habit to get into, especially when you can do it in Ruby. – Peter Brown Jul 19 '12 at 20:35
  • Okay, sounds like a good idea to switch to that. Now back to my original question, do you know how to create some formatted output similar to that of a Rails generator? – Andrew Jul 19 '12 at 20:47
  • Is there a reason you're not using a rails generator? You could also use one of the thor generators. http://blog.plataformatec.com.br/2009/07/creating-your-own-generators-with-thor/ – Peter Brown Jul 19 '12 at 20:54