I've developed a set of Ruby scripts. Each of them should be 'self-contained', so a user can run it on its own. But also I would like to use them to build other scripts, I mean for example to use its methods but also to run it as a whole, without doing `
When I write a one off script, I often wrap it in a class. You've pointed out some advantages of doing this including reuse and cleaner documentation.
I find that there are several levels of polish for scripts depending on how they are going to be used. If the script is run once and never used again, I may not wrap it in a class. If it's important (taking backups of production systems), it's probably worth putting it in full gem form and writing tests. Somewhere in the middle is the single purpose class. Generally this means you're taking the code that's not in a method and putting it in the class constructor.
#!ruby def amethod(i) i+1 end ARGF.each do |l| if l.chomp.to_i > 0 puts amethod(l.chomp.to_i) end end
#!ruby class OneAdder def amethod(i) i+1 end def initialize ARGF.each do |l| if l.chomp.to_i > 0 puts amethod(l.chomp.to_i) end end end end OneAdder.new