Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing boolean parameters in Ruby on Rails

My Ruby on Rails function should receive a boolean parameter, check it and, if it is true, do something.

  def isReady
     if (params[:ready] == true)
            doSomething()
     end
  end

However, with the example below we never get inside this if (but it enters the function), probably because the parameter is passed as a string instead of as a boolean. How can I pass boolean parameters properly, or convert them?

curl --data "ready=true" http://example.com/users/isReady

1 Answers

probably because the parameter is passed as a string instead of as a boolean.

Correct. The way I handle this in generic Ruby way is as follows:

class String
  def to_b()
    self.downcase == "true"
  end
end

Now any string will have the to_b method. You can you write

def ready?
  if params[:ready].to_b
    do_something
  end
end
like image 67
14 revs, 12 users 16% Avatar answered May 17 '26 23:05

14 revs, 12 users 16%



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!