About the present method in rails, how to use?

Hi, guys

I read this book ‘Agile web development with rails’ and know this
method
present, so i have some question.
How to use this present method?
What is the usage of this method ?
Can you give me a example for explaining it?

Thanks a lot.

Hey

First, be careful, the name of the method is actually “present?”, with
the ‘?’. There is another method called “blank?”, what this last
method does is asking if an object (or variable) is, let’s say, in a
‘black state’, that is whether it is nil, empty or an empty string and
returns true. So you would do things like:

book = “”

if book.blank?
book = writer.write_book
else
speaker.read_book(book)
end

We are asking if the book has something written on it, and if it
doesn’t, we write something on it, otherwise, just read it. As you can
see, book is “” which is an empty string, so something will be written
there.

If you go and check the source code
(present? (Object) - APIdock) of “present?”, you will
find this :

def present?
!blank?
end

From this we can say that an object will return true if it is NOT
blank. To summarize, “present?” checks if an object is nil, or empty,
or “” and returns false if the object is in fact in one of the
previous states, otherwise it returns true.

So we could rewrite the previous example as

if book.present?
speaker.read_book(book)
else
book = writer.write_book
end

Hope this helps!

Many thanks to Alejandro, that is very helpful.

2011/8/7 Alejandro C. [email protected]