def include_class?(obj_class)
stack = []
hash.each do |k, v|
if v.is_a?(Hash)
stack << [k,v]
else
return true if v.class == obj_class
end
end
stack.each do |parent, current_hash|
current_hash.each do |k, v|
if v.is_a?(Hash)
stack << {k, v}
else
return true if v.class == obj_class
end
end
end
false
end
Refactorings
No refactoring yet !
Krzysztof Wilczynski
August 15, 2010, August 15, 2010 22:13, permalink
I am not 100% sure whether this is what you are after ... Look at the simple use-case tests below.
class Hash
def include_object?(object_class)
self.collect { |k, v| v.values.grep(object_class).any? if v.is_a?(Hash) }.any?
end
end
test = [
{ :comment => { :body => '', :asset => '' } },
{ :comment => { :body => '', :asset => 'Hash' } }, # Sanity check ... String it is ...
{ :comment => { :body => '', :asset => Array.new } },
{ :comment => { :body => '', :asset => File.open('/dev/null') }},
{ :comment => { :body => '', :asset => Time.new } },
{ :comment => { :body => '', :asset => Time.new } }
]
test.each { |i| p i.include_object?(File) }
test.each { |i| p i.include_object?(Array) }
test.each { |i| p i.include_object?(Hash) }
test.each { |i| p i.include_object?(Time) }
I have a hash like this one:
file = File.open('/path/to/file')
hash = {:comment => {:body => "comment...", :asset => file}}
I need to know if my hash contain a file before posting to a web-service, I'm doing hash.include_class(File) with something similar with following code, any suggestion to make it short?