Simplify "any" validation with an or-operator in Ruby

How to simplify the following check? ...

if node[:base][:database][:adapter].empty? || node[:base][:database][:host].empty? || node[:base][:database][:database].empty? || node[:base][:database][:port].empty? 

to something like

 required_keys = { :adapter, :host, :database...etc...} required keys - node[:base][:database] == [] 

This syntax does not work a bit, but basically subtracts the keys from the set of necessary keys. If you have all the necessary keys in your set, the result should be empty.

I'm not sure about the correct syntax ?, Any help would be appreciated

+4
source share
2 answers
 required_keys = [:adapter, :host, :database ] if required_keys.any?{|x| node[:base][:database][x].empty?} #code here end 

Or you could also:

 node[:base][:database].values_at(*required_keys).any?(&:empty?) 
+11
source

If you think you are going to use this function in several places, you can extend the Hash class and require an extension in the initializer.

 class Hash def contains_values_for?(*keys) keys.all? do |key| self[key].present? end end end 

Now you can do:

 node[:base][:database].contains_values_for?(:adapter, :host, :database, :port) 
0
source

Source: https://habr.com/ru/post/1481031/


All Articles