Created
January 22, 2011 00:13
-
-
Save jistr/790686 to your computer and use it in GitHub Desktop.
Simple YAML -> CouchDB fixture loader for Rails
This file contains hidden or 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
# YAML -> CouchDB fixture loader for Rails | |
# ======================================== | |
# by Jiri Stransky (http://twitter.com/jistr) | |
# for use with testing database instances only ;) | |
# | |
# What it does: | |
# * Loads fixtures from "test/fixtures" directory. | |
# * Permits use of ERB in the fixtures. | |
# * Uses CouchRest. | |
# | |
# Usage: | |
# 1) Put this file into "test" subdirectory of your Rails app (where test_helper.rb usually is). | |
# 2) Wherever you want to load fixtures into your CouchDB: | |
# 2a) Require this file. | |
# 2b) fixture_loader = CouchFixture::Loader.new("my database url") | |
# fixture_loader.load_all | |
require 'yaml' | |
require 'erb' | |
require 'couchrest' | |
module CouchFixture | |
class Loader | |
RELATIVE_FIXTURES_PATH = '../fixtures' | |
def initialize(db) | |
case db | |
when CouchRest::Database | |
@db = db | |
when String | |
@db = CouchRest.database! db | |
else | |
raise 'CouchFixture::Loader can be initialized only with a database URL string or CouchRest::Database object' | |
end | |
end | |
def load_all | |
get_all_fixture_filenames.each do |filename| | |
load_file filename | |
end | |
end | |
def load(fixture) | |
load_file(File.expand_path(RELATIVE_FIXTURES_PATH, __FILE__) + '/' + fixture + '.yml') | |
end | |
private | |
def get_all_fixture_filenames | |
fixture_dir = File.expand_path(RELATIVE_FIXTURES_PATH, __FILE__) | |
Dir.glob("#{fixture_dir}/*.yml") | |
end | |
def load_file(filename) | |
# the first level keys aren't important, we are only interested in values | |
contents = YAML::load(erb_process_file(filename)).values | |
contents.each do |document| | |
last = document == contents.last | |
# bulk save if not last, batch save always | |
@db.save_doc(document, !last, true) | |
end | |
end | |
def erb_process_file(filename) | |
erb = ERB.new IO.read(filename) | |
# make empty object for ERB binding | |
bindable = Object.new | |
class << bindable | |
def get_binding | |
binding | |
end | |
end | |
erb.result(bindable.get_binding) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment