Ruby's `.present?` without Rails?

1.9k Views Asked by At

I'm developing a "Rails-less" Ruby daemon for automation (although in theory it runs within a Rails directory). For general purposes and the principle of the matter, I would like to find the (most) "native"/common way to utilize a Ruby version of .present?/.blank?/.empty?/.nil? to identify if an array or a (hash) value exists and is not empty (i.e., [] or {}).

From what I've read (e.g., Stack Overflow) and tested, all of these functions appear to be Rails-specific methods, part of ActiveSupport(?).

Coming from other web/interpreter languages (PHP, Python, JS, etc.), this is a general logic function most languages (with arrays, which are most) have this functionality built in one way or another (e.g., PHP's isset( ... ) or JavaScript's .length).

I understand there are RegEx workarounds for .blank?, but .present? seems it would require exception handling to identify if it's "present"). I'm having a hard time believing it doesn't exist, but there's little talk about Ruby without Rails' involvement.

2

There are 2 best solutions below

0
On BEST ANSWER

Active Support is broken in small pieces so that you can load just what you need. For .blank? and .present? methods it would be enough to require:

require 'active_support/core_ext/object/blank.rb'

As docs say.

Object#nil? , Array#empty? and Hash#empty? already defined so you dont need anything to require to use those.

Make sure active_support gem installed in your system

0
On

You can use ActiveSupport without including all rails in your app, that's actually quite common.

nil? and empty? are defined in the standard library.

E.g., String#empty? is simply testing if the length is 0.

To use active support, just install the gem or add it to your gemfile then:

require 'active_support'

The documentation also states you can cherry pick the core extensions you want:

require 'active_support/core_ext/object/blank'