Search code examples
rubypuppetsystem-callsreturn-code

Using Ruby to execute arbitrary system calls


This problem is to get into an internship within a devops department:

"Write a ruby library that executes arbitrary system calls (eg: “dmesg", "ping -c 1 www.google.com”) and provides separated output streams of stderr and stdout as well are providing the final return code of the process. Show your work with unit tests.”

Am I supposed to use already established system calls and replicate them in Ruby code? That seems silly to me. Am I supposed to come up with my own arbitrary calls and write a library complete with errors and status calls?

I am not looking for someone to write this for me. I feel that the first step to solving this problem is understanding it.


Solution

  • Get Clarification from the Source

    The assignment is poorly worded, and misuses a number of terms. In addition, we can only guess what they really expect; the appropriate thing to do would be to ask the company directly for clarification.

    Re-Implement Open3

    With that said, what they probably want is a way to process any given command and its arguments as a decorated method, akin to the way Open3#capture3 from the standard library works. That means the code you write should take the command and any arguments as parameters.

    For example, using Open3#capture3 from the standard library:

    require 'open3'
    
    def command_wrapper cmd, *args
      stdout_str, stderr_str, status = Open3.capture3 "#{cmd} #{args.join ' '}"
    end
    
    command_wrapper "/bin/echo", "-n", "foo", "bar", "baz"
    #=> ["foo bar baz", "", #<Process::Status: pid 31661 exit 0>]
    

    I sincerely doubt that it's useful to re-implement this library, but that certainly seems like what they're asking you to do. Shrug.

    You're also supposed to write unit tests for the re-implementation, so you will have to swot something up with a built-in framework like Test::Unit or MiniTest, or an external testing framework like RSpec, or Wrong. See the Ruby Toolbox for a more comprehensive list of available unit testing frameworks.