Tuesday 11 December 2018

What is the difference between using .exists?, and .present? in Ruby?



I want to make sure I'm using them for the correct occasion and want to know of any subtleties. They seem to function the same way, which is to check to see if a object field has been defined, when I use them via the console and there isn't a whole lot information online when I did a google search. Thanks!


Answer




To clarify: neither present? nor exists? are "pure" ruby—they're both from Rails-land.



present?



present? is an ActiveSupport extension to Object. It's usually used as a test for an object's general "falsiness". From the documentation:




An object is present if it’s not blank?. An object is blank if it’s false, empty, or a whitespace string.





So, for example:



[ "", " ", false, nil, [], {} ].any?(&:present?)
# => false


exists?



exists? is from ActiveResource. From its documentation:





Asserts the existence of a resource, returning true if the resource is found.




Note.create(:title => 'Hello, world.', :body => 'Nothing more for now...')
Note.exists?(1) # => true

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...