Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ruby method .present?

I have a method like this in rails app:

def current_user
        return @current_user if @current_user.present?
        @current_user = current_user_session && current_user_session.record
end

I haven't used the .present? method before so I went into my interactive ruby shell to play around with it.

Whenever I use xxx.present? it returns a NoMethodError. It doesn't matter if xxx is a string, number, array anything.

How can I use this method?

like image 879
Kane Avatar asked Sep 15 '13 08:09

Kane


People also ask

Is present in Ruby?

Chromium (Cr) metal is present in Ruby as an impurity. Ruby has pink to blood-red colour. It is a gemstone. It is a variety of the mineral corundum (aluminium oxide).

How do you return a value from a method in Ruby?

Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it. If you wanted to explicitly return a value you can use the return keyword.

How do you use nil in Ruby?

In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby's way of referring to nothing or void. Ruby also provide a nil?


3 Answers

present is a rails method, not ruby.
try using rails c instead of irb to use it in your console.

like image 67
jomo Avatar answered Sep 23 '22 05:09

jomo


present is a method provided by ActiveSupport. It is not a part of core ruby. That is why you are not able to use it in the ruby shell. To play around with it, you will need to require the relevant libraries in your console (e.g. irb / pry):

require 'active_support'
require 'active_support/core_ext'

This way, you will have access to all the utility methods provided by activesupport.

like image 33
Nerve Avatar answered Sep 23 '22 05:09

Nerve


As mentioned above, .present is not in the ruby standard library. Instead, it's in active_support (docs.)

To use active_support, first install the gem, then require it in irb or your ruby script. More information on how to selectively load activesupport extensions can be found in the Rails guides.

like image 23
James Lim Avatar answered Sep 26 '22 05:09

James Lim