Posted almost 6 years ago. Visible to the public.
ArrayInquirer provides friendlier way to check contents in an array
Rails 5 introduces ArrayInquirer
that wraps an array object and provides friendlier methods to check for the presence of elements that can be either a string or a symbol.
Copypets = ActiveSupport::ArrayInquirer.new([:cat, :dog, 'rabbit']) > pets.cat? #=> true > pets.rabbit? #=> true > pets.elephant? #=> false
Array Inquirer also has any?
method to check for the presence of any of the passed arguments as elements in the array.
Copypets = ActiveSupport::ArrayInquirer.new([:cat, :dog, 'rabbit']) > pets.any?(:cat, :dog) #=> true > pets.any?('cat', 'dog') #=> true > pets.any?(:rabbit, 'elephant') #=> true > pets.any?('elephant', :tiger) #=> false
Since ArrayInquirer
class inherits from Array
class, it's any?
method performs same as any?
method of Array
class when no arguments are passed.
Copypets = ActiveSupport::ArrayInquirer.new([:cat, :dog, 'rabbit']) > pets.any? #=> true > pets.any? { |pet| pet.to_s == 'dog' } #=> true
Use inquiry method on array to fetch Array Inquirer version
For any given array we can have its Array Inquirer version by calling inquiry
method on it.
Copypets = [:cat, :dog, 'rabbit'].inquiry > pets.cat? #=> true > pets.rabbit? #=> true > pets.elephant? #=> false
Usage of Array Inquirer in Rails code
Rails 5 makes use of Array Inquirer and provides a better way of checking for the presence of given variant. Before Rails 5 code looked like this.
Copyrequest.variant = :phone > request.variant #=> [:phone] > request.variant.include?(:phone) #=> true > request.variant.include?('phone') #=> false
Corresponding Rails 5 version is below.
Copyrequest.variant = :phone > request.variant.phone? #=> true > request.variant.tablet? #=> false