Juan Castelli
Juan Castelli

Reputation: 185

Execute ruby method from command-line

I have the following class in Ruby in the file test_class.rb:

class TestClass

   def test_verify_one
         # DO SOME
   end

   def test_verify_two
         # DO SOME
   end

end

To execute this class I send two parameters to the terminal, ENVIRONMENT and LANGUAGE.

So... to call from terminal I use:

ruby test_class.rb ENVIRONMENT LANGUAGE

This executes both methods.

I want to execute only one.

I tried the following:

ruby -r "test_class.rb" -e "TestClass.test_verify_one" ENVIRONMENT LANGUAGE

but it is not working.

Can you help me?

Upvotes: 0

Views: 3821

Answers (2)

Peter Carter
Peter Carter

Reputation: 2728

If you want your first method to take the variables you're passing to it you need to define your first method to take two variables, like so:

class TestClass

    def test_verify_one (var1, var2)
             # DO SOME
       end

       def test_verify_two
             # DO SOME
       end

end

You will then need to put a condition into your second which causes it to only execute under the conditions you want it to... or just comment it out if you don't need it at the moment. So, for example, if you only wanted test 2 to fire when variables were not passed in, your code would look something like this:

class TestClass

    def test_verify_one (var1, var2)
        # DO SOME
    end

    def test_verify_two (var1, var2)
        if (var1 and var2) defined? nil
        # DO SOME
    end

end

Upvotes: 0

Anthony E
Anthony E

Reputation: 11235

Within the same folder as test_class.rb, run the ruby command with the following command syntax:

ruby -I . -r "test_class" -e "TestClass.test_verify_one" arg1 arg2

Breaking this command down we get:

-I . Include current directory in $LOAD_PATH so we can use require

-r Require a file named test_class within the $LOAD_PATH. This is possible because we included the current directory in our load path above (.rb extension is optional here).

-e Same as you've provided, evaluates the following code.

Now, if we call ARGV within that method we should get arg1 and arg2 on separate lines:

#...
def self.test_verify_one
  puts ARGV
end
#...

Upvotes: 4

Related Questions