I hope I did not understand the meaning of duck printing, but from what I read, it means that I have to write code based on how the object responds to methods and not to type / class.
Here is the 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 be ID or Property objects"
end
end
I want to end up with a hash where the keys are an integer representing the identifier of an ActiveRecord object. I donβt particularly like going through hash keys twice with all?to determine if I need to capture the identifier.
Of course, I will accept any other suggestions for improving this code :)
source
share