Created
January 21, 2009 16:31
-
-
Save metaskills/50027 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'yaml' | |
# When this file is loaded, for each data fixture file, a module is created within the DataFixtures module | |
# with the same name as the fixture file. For each fixture in that fixture file, a singleton method is | |
# added to the module with the name of the given fixture, returning the value of the fixture. | |
# | |
# For example: | |
# | |
# A fixture in <tt>int_live_data.yml</tt> named <tt>fix1_response_for_get_vin_parts</tt> with value | |
# <tt><foo>hi!</foo></tt> would be made available like so: | |
# | |
# DataFixtures::IntLiveData.fix1_response_for_get_vin_parts | |
# => "<foo>hi!</foo>" | |
# | |
# Alternatively you can treat the fixture module like a hash | |
# | |
# DataFixtures::IntLiveData[:fix1_response_for_get_vin_parts] | |
# => "<foo>hi!</foo>" | |
# | |
# You can find out all available fixtures by calling | |
# | |
# DataFixtures.fixtures | |
# => ["IntLiveData"] | |
# | |
# And all the fixtures contained in a given fixture by calling | |
# | |
# DataFixtures::IntLiveData.fixtures | |
# => ["fix1_response_for_get_vin_parts", "...", "..."] | |
module DataFixtures | |
class << self | |
def create_fixtures | |
files.each do |file| | |
create_fixture_for(file) | |
end | |
end | |
def create_fixture_for(file) | |
fixtures = YAML.load(erb_render(file)) | |
fixture_module = Module.new | |
fixtures.each do |name, value| | |
fixture_method = Proc.new { value.is_a?(String) ? value : YAML.load(value.to_yaml) } | |
fixture_module.send :define_method, name, &fixture_method | |
fixture_module.send :module_function, name | |
end | |
fixture_module.module_eval(<<-EVAL, __FILE__, __LINE__) | |
module_function | |
def fixtures | |
#{fixtures.keys.sort.inspect} | |
end | |
def [](name) | |
send(name) if fixtures.include?(name.to_s) | |
end | |
EVAL | |
const_set(module_name(file), fixture_module) | |
end | |
def fixtures | |
constants.sort | |
end | |
private | |
def files | |
Dir.glob(File.dirname(__FILE__) + '/data_fixtures/*.yml').map {|fixture| File.basename(fixture)} | |
end | |
def module_name(file_name) | |
File.basename(file_name, '.*').camelcase | |
end | |
def path(file_name) | |
File.join(File.dirname(__FILE__), 'data_fixtures', file_name) | |
end | |
def erb_render(file) | |
fixture_content = IO.read(path(file)) | |
ERB.new(fixture_content).result | |
end | |
end | |
create_fixtures | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment