4

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.

Jon Lawton
  • 890
  • 3
  • 14
  • 33
  • `present?`, `blank?`, `empty?`, and `nil?` are quite different. What do you really need / want? What's the actual problem you're trying to solve? – Stefan Apr 17 '18 at 12:27
  • Do ruby's built-in methods like `.empty?`, `.nil?`, `.zero?`, etc really not solve your problem? Do you really need to pull `ActiveSupport` into your project as a dependency? What are you trying to achieve? – Tom Lord Apr 17 '18 at 12:31

2 Answers2

6

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

Martin
  • 4,042
  • 2
  • 19
  • 29
0

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'
Jaffa
  • 12,442
  • 4
  • 49
  • 101