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:
- it fail if 'set' not required standard library. don't want require dependency perform check.
- 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:
- i check
to_ary
method, set doesn't respondto_ary
. objects implement method should fundamentally arrays, , agree set isn't fundamentally array. see consequences of implementing to_int , to_str in ruby - i can't check
to_a
since hash responds it 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
Post a Comment