damian damian - 1 month ago 7
Ruby Question

Scripting in Ruby

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 `

script.rb
`.

So far what I have is just a couple of scripts (separate files) where I have no classes, just a couple of methods. The processing of taking user input and running those methods is outside of any functions. I see that this model may be not right.

My question is, what should I do now to keep every script self contained but also to allow other scripts to use it? Should every script just contain a class with a main method that I would run
object.main
?

Or maybe my approach of writing a simple scripts, no classes is also good?

If I start a new script, should I always go the objective way?

Answer

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.

This:

#!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

Becomes:

#!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