ruby - How to detect an array- or set-like value while avoiding type checks -


i have method accepts argument can array/set-like object, or hash. gist of method like:

def find(query = {})   if array === query or set === query     query = {:_id => {'$in' => query.to_a}}   end   mongo_collection.find(query) end 

the method accept set of id objects , turn hash condition mongodb.

two problems above code:

  1. it fail if 'set' not required standard library. don't want require dependency perform check.
  2. i don't want strict type comparisons. want accept array- or set-like value , cast array of values to_a.

how perform check? considerations have in mind:

  1. i check to_ary method, set doesn't respond to_ary. objects implement method should fundamentally arrays, , agree set isn't fundamentally array. see consequences of implementing to_int , to_str in ruby
  2. i can't check to_a since hash responds it
  3. methods common array , set, not hash are:

    [:&, :+, :-, :<<, :collect!, :flatten!, :map!, :|] 

i decided go this:

query = {:_id => {'$in' => query.to_a}} if query.respond_to? :& 

since intersection operator set-like object have. i'm not sure this.

how trying find out if query hash like?

def find(query = {})   query = {:_id => {'$in' => query.to_a}} unless query.respond_to?(:has_key?)   mongo_collection.find(query) end 

it reasonable expect object hash or hash if responds has_key?.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -