ruby on rails - Could I improve this method with duck typing? -


hopefully haven't misunderstood meaning of "duck typing", i've read, means should write code based on how object responds methods rather type/class is.

here's code:

def convert_hash(hash)   if hash.keys.all? { |k| k.is_a?(integer) }     return hash   elsif hash.keys.all? { |k| k.is_a?(property) }     new_hash = {}     hash.each_pair {|k,v| new_hash[k.id] = v}     return new_hash   else     raise "custom attribute keys should id's or property objects"   end end 

what want make sure end hash keys integer representing id of activerecord object. don't particularly enjoy having iterate through hash keys twice all? determine if need grab id's out.

of course, i'll accept other suggestions improve code :)

how write method should depend on whether expect exception thrown during course of normal program execution. if want readable exception message because end-user might see it, throwing 1 manually makes sense. otherwise, i'd this:

def convert(hash)     new_hash = {}     hash.each_pair { |k,v| new_hash[ k.is_a?(integer) ? k : k.id ] = v }     return new_hash end 

this accomplish same thing, , you'll still exception if array key doesn't have id field. better, uses little more duck typing because has id field acceptable, better explicitly checking being property. makes code more flexible, when unit testing.

we still have explicit check integer objects, kind of occasional special case acceptable, when checking built-in data types.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -