Peter Penzov
Peter Penzov

Reputation: 1728

Pass arguments in ruby method

I want to send 2 params from CLI when I start rake task. I tried this code:

namespace :tnx do

  require_relative "transactions.rb"
  include Cnp_transactions_modes

  task :generate, [:clean_all] => [:environment]  do |t, args|

    if args[: clean_all] == 'true'
      // something
    end

    if args[:times].empty?
      Cnp_transactions_modes.create_transactions(args[:times])
    end    
  end
end

But I get error:

rake aborted!
NoMethodError: undefined method `empty?' for nil:NilClass

How I can solve this Issue?

Upvotes: 0

Views: 52

Answers (1)

Eric Duminil
Eric Duminil

Reputation: 54303

The error comes from the fact that if args[:times] is nil, empty? cannot be called on args[:times] because empty? isn't defined for nil object. In Rails, you could use blank? to check if it's nil or empty.

This should be enough :

if args[:times]

You don't need to check if args[:times] is empty, you need to check it's defined.

Note that it's the opposite of your condition, but it's probably more logical that way.

Upvotes: 3

Related Questions