aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/array_inquirer.rb
diff options
context:
space:
mode:
authorGeorge Claghorn <george.claghorn@gmail.com>2015-03-10 01:00:37 -0400
committerGeorge Claghorn <george@basecamp.com>2015-03-24 13:33:01 -0500
commitc64b99ecc98341d504aced72448bee758f3cfdaf (patch)
treed704a17a440c57e6e45a4005e7e331a7dc00672f /activesupport/lib/active_support/array_inquirer.rb
parent9d9cc4777be3787ed3645d704f02e5ba1228be13 (diff)
downloadrails-c64b99ecc98341d504aced72448bee758f3cfdaf.tar.gz
rails-c64b99ecc98341d504aced72448bee758f3cfdaf.tar.bz2
rails-c64b99ecc98341d504aced72448bee758f3cfdaf.zip
Add ActiveSupport::ArrayInquirer and Array#inquiry
Wrapping an array in an `ArrayInquirer` gives a friendlier way to check its string-like contents. For example, `request.variant` returns an `ArrayInquirer` object. To check a request's variants, you can call: request.variant.phone? request.variant.any?(:phone, :tablet) ...instead of: request.variant.include?(:phone) request.variant.any? { |v| v.in?([:phone, :tablet]) } `Array#inquiry` is a shortcut for wrapping the receiving array in an `ArrayInquirer`: pets = [:cat, :dog] pets.cat? # => true pets.ferret? # => false pets.any?(:cat, :ferret} # => true
Diffstat (limited to 'activesupport/lib/active_support/array_inquirer.rb')
-rw-r--r--activesupport/lib/active_support/array_inquirer.rb38
1 files changed, 38 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/array_inquirer.rb b/activesupport/lib/active_support/array_inquirer.rb
new file mode 100644
index 0000000000..0ae534da00
--- /dev/null
+++ b/activesupport/lib/active_support/array_inquirer.rb
@@ -0,0 +1,38 @@
+module ActiveSupport
+ # Wrapping an array in an +ArrayInquirer+ gives a friendlier way to check
+ # its string-like contents:
+ #
+ # variants = ActiveSupport::ArrayInquirer.new([:phone, :tablet])
+ #
+ # variants.phone? # => true
+ # variants.tablet? # => true
+ # variants.desktop? # => false
+ #
+ # variants.any?(:phone, :tablet) # => true
+ # variants.any?(:phone, :desktop) # => true
+ # variants.any?(:desktop, :watch) # => false
+ class ArrayInquirer < Array
+ def any?(*candidates, &block)
+ if candidates.none?
+ super
+ else
+ candidates.any? do |candidate|
+ include?(candidate) || include?(candidate.to_sym)
+ end
+ end
+ end
+
+ private
+ def respond_to_missing?(name, include_private = false)
+ name[-1] == '?'
+ end
+
+ def method_missing(name, *args)
+ if name[-1] == '?'
+ any?(name[0..-2])
+ else
+ super
+ end
+ end
+ end
+end