# Logic basically stolen from http://iain.nl/2009/05/writing-yaml-files/
class Hash
  def deep_stringify_keys
    new_hash = {}
    self.each do |key, value|
      new_hash.merge!(key.to_s => (value.is_a?(Hash) ? value.deep_stringify_keys : value))
    end
  end
end

module EOL
  class TestInfo

    def self.save(name, data)
      if data.is_a? Hash # ...and it should be...
        data.keys.each do |k|
          begin
            data[k].to_yaml
          # Okay, I don't know what happened, but at some point, objects stopped allowing #to_yaml if they were
          # either generated by factory_girl or if they were "used" after creation.  The solution, oddly but
          # effectively enough, was to simply reload them from the DB.  This handles that automatically:
          rescue TypeError => e
            data[k] = data[k].class.send(:find, data[k])
          end
        end
      end

      File.open(file_for(name), "w") do |f|
        test_info_yaml = data.deep_stringify_keys.to_yaml
        
        # this will remove any Proc statements from the YAML file. Procs were being used in validations
        # for models using the Paperclip plugin to attach icons
        test_info_yaml.gsub!(/^\s*- \!ruby\/object:Proc \{\}\n/, '')
        f.write(test_info_yaml)
      end

    end

    def self.load(name)
      require_all_models
      hash = YAML::load_file(file_for(name))
    end

    def self.file_for(name)
      Rails.root.join('tmp', "#{name}_test_info.yml")
    end

    def self.require_all_models
      Dir.glob("#{Rails.root}/app/models/**/*.rb") do |model_name|
        require_dependency model_name
      end 
    end

  end
end
