23e6178f295b9cb7473d44d9e501a2b3

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?

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 !

9dc2fe52cbc7a4f42b54d056e470efea

Krzysztof Wilczynski

August 15, 2010, August 15, 2010 22:13, permalink

No rating. Login to rate!

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)  }

Your refactoring





Format Copy from initial code

or Cancel