Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

couchrest-rails plugin installed

  • Loading branch information...
commit 71a85efd36b57cabe8b93d473d0052d2464ab636 1 parent 0a53d0e
@Stanley authored
Showing with 1,528 additions and 0 deletions.
  1. +36 −0 config/initializers/couchdb.rb
  2. +20 −0 vendor/plugins/couchrest-rails/MIT-LICENSE
  3. +193 −0 vendor/plugins/couchrest-rails/README.md
  4. +11 −0 vendor/plugins/couchrest-rails/Rakefile
  5. +8 −0 vendor/plugins/couchrest-rails/generators/couch_rest_rails/USAGE
  6. +12 −0 vendor/plugins/couchrest-rails/generators/couch_rest_rails/couch_rest_rails_generator.rb
  7. +13 −0 vendor/plugins/couchrest-rails/generators/couch_rest_rails/templates/couchdb.yml
  8. +36 −0 vendor/plugins/couchrest-rails/generators/couch_rest_rails/templates/couchdb_initializer.rb
  9. +10 −0 vendor/plugins/couchrest-rails/init.rb
  10. +3 −0  vendor/plugins/couchrest-rails/install.rb
  11. +5 −0 vendor/plugins/couchrest-rails/lib/autotest/discover.rb
  12. +35 −0 vendor/plugins/couchrest-rails/lib/couch_rest_rails.rb
  13. +86 −0 vendor/plugins/couchrest-rails/lib/couch_rest_rails/database.rb
  14. +16 −0 vendor/plugins/couchrest-rails/lib/couch_rest_rails/document.rb
  15. +88 −0 vendor/plugins/couchrest-rails/lib/couch_rest_rails/fixtures.rb
  16. +88 −0 vendor/plugins/couchrest-rails/lib/couch_rest_rails/lucene.rb
  17. +56 −0 vendor/plugins/couchrest-rails/lib/couch_rest_rails/tests.rb
  18. +90 −0 vendor/plugins/couchrest-rails/lib/couch_rest_rails/views.rb
  19. +44 −0 vendor/plugins/couchrest-rails/lib/spec/rails/matchers/couch_document_validations.rb
  20. +123 −0 vendor/plugins/couchrest-rails/spec/lib/couch_rest_rails/database_spec.rb
  21. +29 −0 vendor/plugins/couchrest-rails/spec/lib/couch_rest_rails/document_spec.rb
  22. +101 −0 vendor/plugins/couchrest-rails/spec/lib/couch_rest_rails/fixtures_spec.rb
  23. +50 −0 vendor/plugins/couchrest-rails/spec/lib/couch_rest_rails/lucene_spec.rb
  24. +78 −0 vendor/plugins/couchrest-rails/spec/lib/couch_rest_rails/tests_spec.rb
  25. +47 −0 vendor/plugins/couchrest-rails/spec/lib/couch_rest_rails/views_spec.rb
  26. +59 −0 vendor/plugins/couchrest-rails/spec/lib/couch_rest_rails_spec.rb
  27. +46 −0 vendor/plugins/couchrest-rails/spec/matchers/couch_document_validations_spec.rb
  28. +11 −0 vendor/plugins/couchrest-rails/spec/mock/fixtures/bar.yml
  29. +11 −0 vendor/plugins/couchrest-rails/spec/mock/fixtures/foo.yml
  30. +1 −0  vendor/plugins/couchrest-rails/spec/mock/lucene/bar/lucene/default/search.js
  31. +1 −0  vendor/plugins/couchrest-rails/spec/mock/lucene/foo/lucene/default/search.js
  32. +7 −0 vendor/plugins/couchrest-rails/spec/mock/views/bar/views/default/all/map.js
  33. +7 −0 vendor/plugins/couchrest-rails/spec/mock/views/foo/views/default/all/map.js
  34. +7 −0 vendor/plugins/couchrest-rails/spec/mock/views/foo/views/default/tags/map.js
  35. +3 −0  vendor/plugins/couchrest-rails/spec/mock/views/foo/views/default/tags/reduce.js
  36. +53 −0 vendor/plugins/couchrest-rails/spec/spec_helper.rb
  37. +43 −0 vendor/plugins/couchrest-rails/tasks/couch_rest_rails_tasks.rake
  38. +1 −0  vendor/plugins/couchrest-rails/uninstall.rb
View
36 config/initializers/couchdb.rb
@@ -0,0 +1,36 @@
+begin
+
+ env = ENV['RAILS_ENV'] || 'development'
+
+ couchdb_config = YAML::load(ERB.new(IO.read(RAILS_ROOT + "/config/couchdb.yml")).result)[env]
+
+ host = couchdb_config["host"] || 'localhost'
+ port = couchdb_config["port"] || '5984'
+ database = couchdb_config["database"]
+ username = couchdb_config["username"]
+ password = couchdb_config["password"]
+ ssl = couchdb_config["ssl"] || false
+ db_prefix = couchdb_config["database_prefix"] || ""
+ db_suffix = couchdb_config["database_suffix"] || ""
+ host = "localhost" if host == nil
+ port = "5984" if port == nil
+ ssl = false if ssl == nil
+
+ protocol = ssl ? 'https' : 'http'
+ authorized_host = (username.blank? && password.blank?) ? host :
+ "#{CGI.escape(username)}:#{CGI.escape(password)}@#{host}"
+
+rescue
+
+ raise "There was a problem with your config/couchdb.yml file. Check and make sure it's present and the syntax is correct."
+
+else
+
+ COUCHDB_CONFIG = {
+ :host_path => "#{protocol}://#{authorized_host}:#{port}",
+ :db_prefix => "#{db_prefix}",
+ :db_suffix => "#{db_suffix}"
+ }
+
+ COUCHDB_SERVER = CouchRest.new COUCHDB_CONFIG[:host_path]
+end
View
20 vendor/plugins/couchrest-rails/MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) Henry Poydar
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
View
193 vendor/plugins/couchrest-rails/README.md
@@ -0,0 +1,193 @@
+# CouchRest-Rails
+
+A Rails plugin for connecting to and working with a [CouchDB](http://couchdb.apache.org) document-oriented database via the [CouchRest](http://github.com/jchris/couchrest) RESTful CouchDB client.
+
+Specifically, this plugin provides the following utilities:
+
+* Initializer for use with a couchdb.yml configuration file
+* CouchDB-specific rake tasks (database creation, deletion, fixture loading, views synchronization)
+* CouchDB-specific fixtures
+* Setup and teardown helpers for spec'ing and testing
+* A paper-thin wrapper around CouchRest::ExtendedDocument
+* Support for multiple CouchDB databases per application
+* Optional support for Lucene full-text indexing and searching of your CouchDB databases and documents
+
+This plugin does not interfere with the traditional relational database backend, so you can use that as a datastore alongside CouchDB if you want. (In fact, you'll have to unwire the requirement for a relational database if you don't want to use one.)
+
+This plugin assumes some knowledge of CouchDB and its important differences from conventional Rails data storage (RDBMS) options. See [the CouchDB site](http://couchdb.apache.org) for more information.
+
+## Requirements
+
+* [CouchRest gem](http://github.com/jchris/couchrest)
+* [Validatable gem](http://validatable.rubyforge.org/)
+* [JSON gem](http://json.rubyforge.com)
+* [RSpec](http://github.com/dchelimsky/rspec) BDD framework (optional - for running plugin specs)
+* [RSpec-Rails](http://github.com/dchelimsky/rspec-rails) library (optional - for running plugin specs)
+* Lucene (optional) for full text searching of CouchDB documents
+
+## Installation
+
+Install with the native Rails plugin installation script:
+
+ script/plugin install git://github.com/hpoydar/couchrest-rails.git
+
+Or simply add to vendor/plugins and generate the files you need:
+
+ script/generate couch_rest_rails
+
+The plugin creates two folders:
+
+* `db/couch/` - For storing CouchDB database information map and reduce functions (views)
+* `test/fixtures/couch` - for storing and loading CouchDB fixtures (yaml)
+
+These paths can be customized in an initializer or environment configuration file:
+
+ CouchRestRails.fixtures_path = 'custom/path/to/your/fixtures/from/app/root'
+ CouchRestRails.views_path = 'custom/path/to/your/views/from/app/root'
+
+The installation process will also create a `config/couchdb.yml` file for customizing your configuration.
+
+## Usage
+
+### Configuration
+
+The `couchdb.yml` file can be customized to support the specifics of your particular CouchDB installation. Since multiple databases per application are supported, it is recommended that you specify a `database_prefix` for use in naming the database on the CouchDB server. This will make it much easier to peer into your server with Sofa and figure out which databases belong to which application.
+
+Database names are defined in the `CouchRestRails::Document` models that use them. (See below, 'CouchRestRails document model')
+
+### Rake tasks
+
+Use the rake tasks to create databases, delete databases, reset databases, push views and load fixtures:
+
+ rake couchdb:create[database] # Create a CouchDB database defined in config/couchdb.yml for the current environment (use no database argument to use all databases defined in CouchRestRails::Document models)
+ rake couchdb:delete[database] # Deletes a CouchDB database for the current RAILS_ENV (use no database argument to use all databases defined in CouchRestRails::Document models)
+ rake couchdb:fixtures:load[database] # Load fixtures into a current environment's CouchDB database (use no database argument to use all databases defined in CouchRestRails::Document models)
+ rake couchdb:lucene:push[database] # Push Lucene views into a current environment's CouchDB database (use no database argument to use all databases defined in CouchRestRails::Document models)
+ rake couchdb:views:push[database] # Push views into a current environment's CouchDB database (use no database argument to use all databases defined in CouchRestRails::Document models)
+ rake doc:plugins:couchrest-rails # Generate documentation for the couchrest-rails plugin
+
+### CouchRestRails document model
+
+For models, inherit from CouchRestRails::Document, which hooks up CouchRest::ExtendedDocument to your CouchDB backend and includes the [Validatable](http://validatable.rubyforge.org/) module:
+
+ class YourCouchDocument < CouchRestRails::Document
+ use_database :database_name
+
+ property :email
+ property :question
+ property :answer
+ property :rating
+
+ timestamps!
+
+ view_by :email
+
+ validates_presence_of :question
+ validates_numericality_of :rating
+
+ ...
+
+ end
+
+Make sure you define your database in the model with the `use_database :<database_name>` directive.
+
+See the CouchRest documentation and specs for more information about CouchRest::ExtendedDocument. (The views defined here are in addition to the ones you can manually set up and push via rake in db/couch/views.)
+
+### CouchDB views
+
+Custom views--outside of the ones defined in your CouchRestRails::Document models--that you want to push up to the CouchDB database/server instance should be in the following format:
+
+ db/couch/<database_name>/views
+ |-- <design_document_name>
+ |-- <view_name>
+ |-- map.js
+ `-- reduce.js
+
+Push up your views via rake (`rake couchdb:views:push`) or within your code or console (`CouchRestRails::Views.push`).
+
+
+### Tests, specs and fixtures
+
+For testing or spec'ing, use these helpers to setup and teardown a test database with fixtures:
+
+ CouchRestRails::Tests.setup
+ CouchRestRails::Tests.teardown
+
+There are also some simple matchers you can can use to spec validations. See `spec/lib/matchers`.
+
+You can store fixtures as Yaml files in the following path pattern:
+
+ test/fixtures/couch/<database_name>.yml
+
+You can customize this path in an initializer or environment file:
+
+ CouchRestRails.fixtures_path = 'custom/path/to/your/fixtures'
+
+#### Rails integration unit testing
+
+Create fixture file by via rake (`rake couchdb:fixtures:dump[<database_name>]`) or within your code or console (`CouchRestRails::Fixtures.dump[<database_name>]`).
+
+Add fixtures to rails test:
+
+ class RailsTest < Test::Unit::TestCase
+ couchdb_fixtures :<database_name>
+
+ ...
+ end
+
+### Lucene
+
+If you want to support Lucene full-text searching of CouchDB documents, enable support for it in an initializer or environment configuration file:
+
+ CouchRestRails.use_lucene = true
+
+The Lucene design documents per database are stored alongside the views:
+
+ db/couch/<database_name>/lucene
+ |-- <design_document_name>
+ |-- <lucene_search>.js
+ |-- <lucene_search>.js
+ |-- ...
+
+You can also customize this path:
+
+ CouchRestRails.lucene_path = 'custom/path/to/your/lucene/docs/from/app/root'
+
+Push up your lucene doc via rake (`rake couchdb:lucence:push`) or within your code or console (`CouchRestRails::Lucene.push`).
+
+## Further development and testing
+
+To run the test suite, you'll need rspec installed with rspec-rails library enabled for the host application. You can run the tests in the following way:
+
+ <rails_root>$ rake spec:plugins
+ <plugin_root>$ rake spec
+ <plugin_root>$ autospec
+
+(The latter requires the ZenTest gem)
+
+_Please don't submit any pull requests with failing specs_
+
+### TODO
+
+* Roll up CouchRest::ExtendedDocument, since it might be deprecated from CouchRest (see CouchRest raw branch)
+* A persistent connection object? Keep-alive?
+* Hook into Rails logger to display times for CouchDB operations
+* Mechanism for better view testing?
+* Restful model/controller/test/spec generator
+* Error class for CouchRestRails::Document with I18n support
+* Support a default database for all CouchRestRails::Document models
+* Gemify
+* Add more parseable options to couchdb.yml
+
+## Contributors / Thanks
+
+* Arnaud Berthomier
+* Dave Farkas
+* Adam Keyes
+* Glenn Rempe
+* John Wood
+
+
+## License
+
+Copyright (c) Henry Poydar, released under the MIT license
View
11 vendor/plugins/couchrest-rails/Rakefile
@@ -0,0 +1,11 @@
+require 'rake'
+require 'spec/rake/spectask'
+
+desc 'Default: run specs.'
+task :default => :spec
+
+desc 'Run the specs'
+Spec::Rake::SpecTask.new(:spec) do |t|
+ t.spec_opts = ['--colour --format progress --loadby mtime --reverse']
+ t.spec_files = FileList['spec/**/*_spec.rb']
+end
View
8 vendor/plugins/couchrest-rails/generators/couch_rest_rails/USAGE
@@ -0,0 +1,8 @@
+Description:
+ Generates the files needed for your Rails application to connect to and work with a CouchDB database over CouchRest.
+
+Example:
+ ./script/generate couchrest_rails
+
+ This will create:
+ config/initializers/couchdb.rb
View
12 vendor/plugins/couchrest-rails/generators/couch_rest_rails/couch_rest_rails_generator.rb
@@ -0,0 +1,12 @@
+class CouchRestRailsGenerator < Rails::Generator::Base
+
+ def manifest
+ record do |m|
+ m.directory "db/couch"
+ m.directory "test/fixtures/couch"
+ m.template "couchdb.yml", "config/couchdb.yml"
+ m.template "couchdb_initializer.rb", "config/initializers/couchdb.rb"
+ end
+ end
+
+end
View
13 vendor/plugins/couchrest-rails/generators/couch_rest_rails/templates/couchdb.yml
@@ -0,0 +1,13 @@
+base: &base
+ database_prefix:
+ database_suffix: _<%%= RAILS_ENV %>
+
+development:
+ host: localhost
+ port: 5984
+ <<: *base
+
+test:
+ host: localhost
+ port: 5984
+ <<: *base
View
36 vendor/plugins/couchrest-rails/generators/couch_rest_rails/templates/couchdb_initializer.rb
@@ -0,0 +1,36 @@
+begin
+
+ env = ENV['RAILS_ENV'] || 'development'
+
+ couchdb_config = YAML::load(ERB.new(IO.read(RAILS_ROOT + "/config/couchdb.yml")).result)[env]
+
+ host = couchdb_config["host"] || 'localhost'
+ port = couchdb_config["port"] || '5984'
+ database = couchdb_config["database"]
+ username = couchdb_config["username"]
+ password = couchdb_config["password"]
+ ssl = couchdb_config["ssl"] || false
+ db_prefix = couchdb_config["database_prefix"] || ""
+ db_suffix = couchdb_config["database_suffix"] || ""
+ host = "localhost" if host == nil
+ port = "5984" if port == nil
+ ssl = false if ssl == nil
+
+ protocol = ssl ? 'https' : 'http'
+ authorized_host = (username.blank? && password.blank?) ? host :
+ "#{CGI.escape(username)}:#{CGI.escape(password)}@#{host}"
+
+rescue
+
+ raise "There was a problem with your config/couchdb.yml file. Check and make sure it's present and the syntax is correct."
+
+else
+
+ COUCHDB_CONFIG = {
+ :host_path => "#{protocol}://#{authorized_host}:#{port}",
+ :db_prefix => "#{db_prefix}",
+ :db_suffix => "#{db_suffix}"
+ }
+
+ COUCHDB_SERVER = CouchRest.new COUCHDB_CONFIG[:host_path]
+end
View
10 vendor/plugins/couchrest-rails/init.rb
@@ -0,0 +1,10 @@
+require 'couch_rest_rails'
+
+%w(couchrest json validatable).each do |g|
+ begin
+ require g
+ rescue LoadError
+ puts "Could not load required gem '#{g}'"
+ exit
+ end
+end
View
3  vendor/plugins/couchrest-rails/install.rb
@@ -0,0 +1,3 @@
+require 'rails_generator'
+require 'rails_generator/scripts/generate'
+Rails::Generator::Scripts::Generate.new.run(['couchrest_rails', 'relax'], :destination => RAILS_ROOT)
View
5 vendor/plugins/couchrest-rails/lib/autotest/discover.rb
@@ -0,0 +1,5 @@
+$:.push(File.join(File.dirname(__FILE__), %w[.. .. rspec]))
+
+Autotest.add_discovery do
+ "rspec"
+end
View
35 vendor/plugins/couchrest-rails/lib/couch_rest_rails.rb
@@ -0,0 +1,35 @@
+module CouchRestRails
+
+ mattr_accessor :lucene_path
+ self.lucene_path = 'db/couch'
+
+ mattr_accessor :fixtures_path
+ self.fixtures_path = 'test/fixtures/couch'
+
+ mattr_accessor :test_environment
+ self.test_environment = 'test'
+
+ mattr_accessor :use_lucene
+ self.use_lucene = false
+
+ mattr_accessor :views_path
+ self.views_path = 'db/couch'
+
+ def process_database_method(database_name, &block)
+ # If wildcard passed, use model definitions for database names
+ if database_name == '*'
+ databases = CouchRestRails::Database.list
+ else
+ databases = [database_name]
+ end
+ response = ['']
+ databases.each do |database|
+ yield database, response
+ end
+ response << ''
+ response.join("\n")
+ end
+
+ module_function :process_database_method
+
+end
View
86 vendor/plugins/couchrest-rails/lib/couch_rest_rails/database.rb
@@ -0,0 +1,86 @@
+module CouchRestRails
+ module Database
+
+ extend self
+
+ def create(database_name = '*', opts = {})
+
+ CouchRestRails.process_database_method(database_name) do |db, response|
+
+ # Setup up views directory
+ database_views_path = File.join(RAILS_ROOT, CouchRestRails.views_path, db, 'views')
+ unless File.exist?(database_views_path)
+ FileUtils.mkdir_p(database_views_path)
+ response << "Created #{File.join(CouchRestRails.views_path, db, 'views')} views directory"
+ end
+
+ # Setup the Lucene directory if enabled
+ if CouchRestRails.use_lucene
+ database_lucene_path = File.join(RAILS_ROOT, CouchRestRails.lucene_path, db, 'lucene')
+ unless File.exist?(database_lucene_path)
+ FileUtils.mkdir_p(database_lucene_path)
+ response << "Created #{File.join(CouchRestRails.lucene_path, db, 'lucene')} Lucene directory"
+ end
+ end
+
+ full_db_name = [COUCHDB_CONFIG[:db_prefix], File.basename(db), COUCHDB_CONFIG[:db_suffix]].join
+
+ # Warn if no model uses the database
+ unless CouchRestRails::Database.list.include?(db)
+ response << "WARNING: there are no CouchRestRails::Document models using #{db}"
+ end
+
+ # Create the database
+ if COUCHDB_SERVER.databases.include?(full_db_name)
+ response << "Database #{db} (#{full_db_name}) already exists"
+ next
+ else
+ COUCHDB_SERVER.create_db(full_db_name)
+ response << "Created database #{db} (#{full_db_name})"
+ end
+
+ end
+
+ end
+
+ def delete(database_name = '*', opts = {})
+
+ CouchRestRails.process_database_method(database_name) do |db, response|
+
+ full_db_name = [COUCHDB_CONFIG[:db_prefix], File.basename(db), COUCHDB_CONFIG[:db_suffix]].join
+ if !COUCHDB_SERVER.databases.include?(full_db_name)
+ response << "Database #{db} (#{full_db_name}) does not exist"
+ else
+ CouchRest.delete "#{COUCHDB_CONFIG[:host_path]}/#{full_db_name}"
+ response << "Deleted database #{db} (#{full_db_name})"
+ end
+
+ # Warn if views path still present for database
+ if File.exist?(File.join(RAILS_ROOT, CouchRestRails.views_path, db, 'views'))
+ response << "WARNING: #{File.join(CouchRestRails.views_path, db, 'views')} views path still present"
+ end
+
+ # Warn if Lucene path still present for database
+ if CouchRestRails.use_lucene
+ if File.exist?(File.join(RAILS_ROOT, CouchRestRails.lucene_path, db, 'views'))
+ response << "WARNING: #{File.join(CouchRestRails.lucene_path, db, 'views')} Lucene path still present"
+ end
+ end
+
+ end
+
+ end
+
+ def list
+ databases = []
+ # Ensure models are loaded
+ Dir.glob(File.join(RAILS_ROOT, 'app', 'models', '*.rb')).map { |m| require_dependency m }
+ Object.subclasses_of(CouchRestRails::Document).collect do |doc|
+ raise "#{doc.name} does not have a database defined" unless doc.database
+ databases << doc.unadorned_database_name
+ end
+ databases.sort.uniq
+ end
+
+ end
+end
View
16 vendor/plugins/couchrest-rails/lib/couch_rest_rails/document.rb
@@ -0,0 +1,16 @@
+module CouchRestRails
+ class Document < CouchRest::ExtendedDocument
+
+ include Validatable
+
+ def self.use_database(db)
+ db = [COUCHDB_CONFIG[:db_prefix], db.to_s, COUCHDB_CONFIG[:db_suffix]].join
+ self.database = COUCHDB_SERVER.database(db)
+ end
+
+ def self.unadorned_database_name
+ database.name.sub(/^#{COUCHDB_CONFIG[:db_prefix]}/, '').sub(/#{COUCHDB_CONFIG[:db_suffix]}$/, '')
+ end
+
+ end
+end
View
88 vendor/plugins/couchrest-rails/lib/couch_rest_rails/fixtures.rb
@@ -0,0 +1,88 @@
+module CouchRestRails
+ module Fixtures
+
+ extend self
+
+ def blurbs
+ res = []
+ res << "Cras dictum. Maecenas ut turpis. In vitae erat ac orci dignissim eleifend. Nunc quis justo. Sed vel ipsum in purus tincidunt pharetra. Sed pulvinar, felis id consectetuer malesuada, enim nisl mattis elit, a facilisis tortor nibh quis leo. Sed augue lacus, pretium vitae, molestie eget, rhoncus quis, elit. Donec in augue. Fusce orci wisi, ornare id, mollis vel, lacinia vel, massa. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas."
+ res << "Aliquam lectus orci, adipiscing et, sodales ac, feugiat non, lacus. Ut dictum velit nec est. Quisque posuere, purus sit amet malesuada blandit, sapien sapien auctor arcu, sed pulvinar felis mi sollicitudin tortor. Maecenas volutpat, nisl et dignissim pharetra, urna lectus ultrices est, vel pretium pede turpis id velit. Aliquam sagittis magna in felis egestas rutrum. Proin wisi libero, vestibulum eget, pulvinar nec, suscipit ut, mi. Integer in arcu ultricies leo dapibus ultricies. Sed rhoncus lobortis dolor. Suspendisse dolor. Mauris sapien velit, pulvinar non, rutrum non, consectetuer eget, metus. Morbi tincidunt lorem at urna. Etiam porta. Ut mauris. Phasellus tristique rhoncus magna. Nam tincidunt consequat urna. Sed tempor."
+ res << "Nunc auctor bibendum eros. Maecenas porta accumsan mauris. Etiam enim enim, elementum sed, bibendum quis, rhoncus non, metus. Fusce neque dolor, adipiscing sed, consectetuer et, lacinia sit amet, quam. Suspendisse wisi quam, consectetuer in, blandit sed, suscipit eu, eros. Etiam ligula enim, tempor ut, blandit nec, mollis eu, lectus. Nam cursus. Vivamus iaculis. Aenean risus purus, pharetra in, blandit quis, gravida a, turpis. Donec nisl. Aenean eget mi. Fusce mattis est id diam. Phasellus faucibus interdum sapien. Duis quis nunc. Sed enim."
+ res << "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi commodo, ipsum sed pharetra gravida, orci magna rhoncus neque, id pulvinar odio lorem non turpis. Nullam sit amet enim. Suspendisse id velit vitae ligula volutpat condimentum. Aliquam erat volutpat. Sed quis velit. Nulla facilisi. Nulla libero. Vivamus pharetra posuere sapien. Nam consectetuer. Sed aliquam, nunc eget euismod ullamcorper, lectus nunc ullamcorper orci, fermentum bibendum enim nibh eget ipsum. Donec porttitor ligula eu dolor. Maecenas vitae nulla consequat libero cursus venenatis. Nam magna enim, accumsan eu, blandit sed, blandit a, eros."
+ res << "Morbi non erat non ipsum pharetra tempus. Donec orci. Proin in ante. Pellentesque sit amet purus. Cras egestas diam sed ante. Etiam imperdiet urna sit amet risus. Donec ornare arcu id erat. Aliquam ultrices scelerisque sem. In elit nulla, molestie vel, ornare sit amet, interdum vel, mauris. Etiam dignissim imperdiet metus."
+ res << "Donec placerat. Nullam nibh dolor, blandit sed, fermentum id, imperdiet sit amet, neque. Nam mollis ultrices justo. Sed tempor. Sed vitae tellus. Etiam sem arcu, eleifend sit amet, gravida eget, porta at, wisi. Nam non lacus vitae ipsum viverra pretium. Phasellus massa. Fusce magna sem, gravida in, feugiat ac, molestie eget, wisi. Fusce consectetuer luctus ipsum. Vestibulum nunc. Suspendisse dignissim adipiscing libero. Integer leo. Sed pharetra ligula a dui. Quisque ipsum nibh, ullamcorper eget, pulvinar sed, posuere vitae, nulla. Sed varius nibh ut lacus. Curabitur fringilla. Nunc est ipsum, pretium quis, dapibus sed, varius non, lectus. Proin a quam. Praesent lacinia, eros quis aliquam porttitor, urna lacus volutpat urna, ut fermentum neque mi egestas dolor."
+ end
+
+ def load(database_name = '*', opts = {})
+
+ CouchRestRails.process_database_method(database_name) do |db, response|
+
+ unless File.exist?(File.join(RAILS_ROOT, CouchRestRails.fixtures_path, "#{db}.yml"))
+ response << "Fixtures file (#{File.join(CouchRestRails.fixtures_path, "#{db}.yml")}) does not exist"
+ next
+ end
+
+ full_db_name = [COUCHDB_CONFIG[:db_prefix], db, COUCHDB_CONFIG[:db_suffix]].join
+ full_db_path = [COUCHDB_CONFIG[:host_path], '/', full_db_name].join
+ unless COUCHDB_SERVER.databases.include?(full_db_name)
+ response << "The CouchDB database #{db} (#{full_db_name}) does not exist - create it first"
+ next
+ end
+
+ db_conn = CouchRest.database(full_db_path)
+ fixture_files = []
+ Dir.glob(File.join(RAILS_ROOT, CouchRestRails.fixtures_path, "#{db}.yml")).each do |file|
+ db_conn.bulk_save(YAML::load(ERB.new(IO.read(file)).result).map {|f| f[1]})
+ fixture_files << File.basename(file)
+ end
+ if fixture_files.empty?
+ response << "No fixtures found in #{CouchRestRails.fixtures_path}"
+ else
+ response << "Loaded the following fixture files into #{db} (#{full_db_name}): #{fixture_files.join(', ')}"
+ end
+
+ end
+
+ end
+
+ def dump(database_name = '*', opts = {})
+
+ CouchRestRails.process_database_method(database_name) do |db, response|
+
+ full_db_name = [COUCHDB_CONFIG[:db_prefix], db, COUCHDB_CONFIG[:db_suffix]].join
+ full_db_path = [COUCHDB_CONFIG[:host_path], '/', full_db_name].join
+ unless COUCHDB_SERVER.databases.include?(full_db_name)
+ response << "The CouchDB database #{db} (#{full_db_name}) does not exist"
+ next
+ end
+
+ fixtures_file = File.join(RAILS_ROOT, CouchRestRails.fixtures_path, "#{db}.yml")
+ if File.exist?(fixtures_file)
+ response << "Overwriting fixtures in #{File.join(CouchRestRails.fixtures_path, "#{db}.yml")}"
+ end
+
+ File.open(fixtures_file, 'w' ) do |file|
+ yaml_hash = {}
+ db_conn = CouchRest.database(full_db_path)
+ docs = db_conn.documents(:include_docs => true)
+ docs["rows"].each do |data|
+ doc = data["doc"]
+ unless (doc['_id'] =~ /^_design*/) == 0
+ doc.delete('_rev')
+ yaml_hash[doc['_id']] = doc
+ end
+ end
+ file.write yaml_hash.to_yaml
+ end
+
+ response << "Dumped fixtures into #{File.join(CouchRestRails.fixtures_path, "#{db}.yml")}"
+
+ end
+ end
+
+ def random_blurb
+ blurbs.sort_by {rand}.first
+ end
+
+ end
+end
View
88 vendor/plugins/couchrest-rails/lib/couch_rest_rails/lucene.rb
@@ -0,0 +1,88 @@
+require 'json'
+
+module CouchRestRails
+ module Lucene
+ extend self
+
+
+ # Push Lucene searches to couchdb
+ def push(database_name = '*', opts = {})
+
+ CouchRestRails.process_database_method(database_name) do |db, response|
+
+ full_db_name = [COUCHDB_CONFIG[:db_prefix], File.basename(db), COUCHDB_CONFIG[:db_suffix]].join
+ full_db_path = [COUCHDB_CONFIG[:host_path], '/', full_db_name].join
+
+ # Default to push all Lucene searches for the given database
+ search_name = opts[:search_name] || '*'
+
+ # Default to load searches from all design documents
+ design_doc_name = opts[:design_doc_name] || '*'
+
+ # Check for CouchDB database
+ if !COUCHDB_SERVER.databases.include?(full_db_name)
+ response << "Database #{db} (#{full_db_name}) does not exist"
+ next
+ end
+
+ # Check for views directory
+ unless File.exist?(File.join(RAILS_ROOT, CouchRestRails.lucene_path, db))
+ response << "Lucene directory (#{CouchRestRails.lucene_path}/#{db}) does not exist"
+ next
+ end
+
+ # Assemble searches for each design document
+ db_conn = CouchRest.database(full_db_path)
+
+ Dir.glob(File.join(RAILS_ROOT, CouchRestRails.lucene_path, db, "lucene", design_doc_name)).each do |doc|
+
+ searches = {}
+ couchdb_design_doc = db_conn.get("_design/#{File.basename(doc)}") rescue nil
+
+ searches = assemble_lucene_searches(doc)
+
+ # Warn if overwriting existing search
+ if couchdb_design_doc && couchdb_design_doc['fulltext']
+ searches.keys.each do |search|
+ if couchdb_design_doc['fulltext'][search]
+ response << "Overwriting existing Lucene search '#{search}' in _design/#{File.basename(doc)}"
+ end
+ end
+ end
+
+ # Save or update
+ if couchdb_design_doc.nil?
+ couchdb_design_doc = {
+ "_id" => "_design/#{File.basename(doc)}",
+ 'language' => 'javascript',
+ 'fulltext' => searches
+ }
+ else
+ if couchdb_design_doc['fulltext']
+ # Merge with existing searches
+ searches = couchdb_design_doc['fulltext'].merge!(searches)
+ end
+ couchdb_design_doc['fulltext'] = searches
+ end
+ db_conn.save_doc(couchdb_design_doc)
+
+ response << "Pushed Lucene searches to #{full_db_name}/_design/#{File.basename(doc)}: #{searches.keys.join(', ')}"
+
+ end
+
+ end
+
+ end
+
+ # Assemble Lucene searches
+ def assemble_lucene_searches(lucene_doc_path)
+ searches = {}
+ Dir.glob(File.join(lucene_doc_path, '*')).each do |search_file|
+ search_name = File.basename(search_file).sub(/\.js$/, '')
+ searches[search_name] = JSON.parse(IO.read(search_file).gsub(/\n/, ''))
+ end
+ searches
+ end
+
+ end
+end
View
56 vendor/plugins/couchrest-rails/lib/couch_rest_rails/tests.rb
@@ -0,0 +1,56 @@
+module CouchRestRails
+ module Tests
+
+ extend self
+ mattr_accessor :fixtures_loaded
+ self.fixtures_loaded = Set.new
+
+ def setup(database_name = '*', opts = {})
+ res = ''
+ ENV['RAILS_ENV'] = CouchRestRails.test_environment
+ unless opts[:skip_if_fixtures_loaded] && fixtures_loaded.include?(database_name)
+ res += CouchRestRails::Database.delete(database_name, opts)
+ res += CouchRestRails::Database.create(database_name, opts)
+ res += CouchRestRails::Fixtures.load(database_name, opts)
+ res += CouchRestRails::Views.push(database_name, opts)
+ fixtures_loaded << database_name
+ end
+ res
+ end
+
+ def reset_fixtures
+ CouchRestRails::Database.delete("*") unless fixtures_loaded.empty?
+ fixtures_loaded.clear
+ end
+
+ def teardown(database_name = "*")
+ ENV['RAILS_ENV'] = CouchRestRails.test_environment
+ CouchRestRails::Database.delete(database_name)
+ fixtures_loaded.delete(database_name)
+ end
+ end
+end
+module Test
+ module Unit #:nodoc:
+ class TestCase #:nodoc:
+
+ setup :setup_couchdb_fixtures if defined?(setup)
+ teardown :teardown_couchdb_fixtures if defined?(teardown)
+
+ superclass_delegating_accessor :database
+ self.database = nil
+
+ class << self
+ def couchdb_fixtures(*databases)
+ self.database = databases.map { |d| d.to_s }
+ end
+ end
+ def setup_couchdb_fixtures
+ CouchRestRails::Tests.setup(self.database) unless self.database.nil?
+ end
+ def teardown_couchdb_fixtures
+ CouchRestRails::Tests.teardown(self.database) unless self.database.nil?
+ end
+ end
+ end
+end
View
90 vendor/plugins/couchrest-rails/lib/couch_rest_rails/views.rb
@@ -0,0 +1,90 @@
+module CouchRestRails
+ module Views
+ extend self
+
+ # Push views to couchdb
+ def push(database_name = '*', opts = {})
+
+ CouchRestRails.process_database_method(database_name) do |db, response|
+
+ full_db_name = [COUCHDB_CONFIG[:db_prefix], File.basename(db), COUCHDB_CONFIG[:db_suffix]].join
+ full_db_path = [COUCHDB_CONFIG[:host_path], '/', full_db_name].join
+
+ # Default to push all views for the given database
+ view_name = opts[:view_name] || '*'
+
+ # Default to load views from all design documents
+ design_doc_name = opts[:design_doc_name] || '*'
+
+ # Check for CouchDB database
+ if !COUCHDB_SERVER.databases.include?(full_db_name)
+ response << "Database #{db} (#{full_db_name}) does not exist"
+ next
+ end
+
+ # Check for views directory
+ unless File.exist?(File.join(RAILS_ROOT, CouchRestRails.views_path, db))
+ response << "Views directory (#{CouchRestRails.views_path}/#{db}) does not exist"
+ next
+ end
+
+ # Assemble views for each design document
+ db_conn = CouchRest.database(full_db_path)
+
+ Dir.glob(File.join(RAILS_ROOT, CouchRestRails.views_path, db, "views", design_doc_name)).each do |doc|
+
+ views = {}
+ couchdb_design_doc = db_conn.get("_design/#{File.basename(doc)}") rescue nil
+ Dir.glob(File.join(doc, view_name)).each do |view|
+
+ # Load view from filesystem
+ map_reduce = assemble_view(view)
+ if map_reduce.empty?
+ response << "No view files were found in #{CouchRestRails.views_path}/#{db}/views/#{File.basename(doc)}/#{File.basename(view)}"
+ next
+ else
+ views[File.basename(view)] = map_reduce
+ end
+
+ # Warn if overwriting views on Couch
+ if couchdb_design_doc && couchdb_design_doc['views'] && couchdb_design_doc['views'][File.basename(view)]
+ response << "Overwriting existing view '#{File.basename(view)}' in _design/#{File.basename(doc)}"
+ end
+
+ end
+
+ # Merge with existing views
+ views = couchdb_design_doc['views'].merge!(views) unless couchdb_design_doc.nil?
+
+ # Save or update
+ if couchdb_design_doc.nil?
+ couchdb_design_doc = {
+ "_id" => "_design/#{File.basename(doc)}",
+ 'language' => 'javascript',
+ 'views' => views
+ }
+ else
+ couchdb_design_doc['views'] = views
+ end
+ db_conn.save_doc(couchdb_design_doc)
+
+ response << "Pushed views to #{full_db_name}/_design/#{File.basename(doc)}: #{views.keys.join(', ')}"
+
+ end
+
+ end
+
+ end
+
+ # Assemble views
+ def assemble_view(design_doc_path)
+ view = {}
+ map_file = File.join(design_doc_path, 'map.js')
+ reduce_file = File.join(design_doc_path, 'reduce.js')
+ view[:map] = IO.read(map_file) if File.exist?(map_file)
+ view[:reduce] = IO.read(reduce_file) if File.exist?(reduce_file) && File.size(reduce_file) > 0
+ view
+ end
+
+ end
+end
View
44 vendor/plugins/couchrest-rails/lib/spec/rails/matchers/couch_document_validations.rb
@@ -0,0 +1,44 @@
+module Spec
+ module Rails
+ module Matchers
+
+ def validate_couchdb_document_format_of(attribute, options)
+ return simple_matcher("document model to validate format of :#{attribute} with #{options[:with]}") do |model|
+ model.send("#{attribute}=", nil)
+ !model.valid? && model.errors.on(attribute)
+ end
+ end
+
+ def validate_couchdb_document_length_of(attribute, options)
+ return simple_matcher("document model to validate length of :#{attribute} within
+ #{options[:maximum] || 0} to #{options[:minimum] || 'infinity'}") do |model|
+ if options[:within]
+ model.send("#{attribute}=", 'x' * (options[:within].last + 1))
+ else
+ if options[:maximum]
+ model.send("#{attribute}=", 'x' * (options[:maximum] + 1))
+ else
+ model.send("#{attribute}=", 'x' * (options[:minimum] - 1))
+ end
+ end
+ !model.valid? && model.errors.on(attribute)
+ end
+ end
+
+ def validate_couchdb_document_presence_of(attribute)
+ return simple_matcher("document model to validate presence of :#{attribute}") do |model|
+ model.send("#{attribute}=", nil)
+ !model.valid? && model.errors.on(attribute)
+ end
+ end
+
+ def validate_couchdb_document_numericality_of(attribute)
+ return simple_matcher("document model to validate numericality of :#{attribute}") do |model|
+ model.send("#{attribute}=", 'x')
+ !model.valid? && model.errors.on(attribute)
+ end
+ end
+
+ end
+ end
+end
View
123 vendor/plugins/couchrest-rails/spec/lib/couch_rest_rails/database_spec.rb
@@ -0,0 +1,123 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+describe CouchRestRails::Database do
+
+ before :each do
+ setup_foo_bars
+ end
+
+ after :all do
+ cleanup_foo_bars
+ end
+
+ describe '#create' do
+
+ it 'should create the specified CouchDB database for the current environment' do
+ CouchRestRails::Database.create('foo')
+ res = CouchRest.get(@foo_db_url)
+ res['db_name'].should == @foo_db_name
+ end
+
+ it 'should do nothing and display a message if the database already exists' do
+ CouchRest.database!(@foo_db_url)
+ res = CouchRestRails::Database.create('foo')
+ res.should =~ /already exists/i
+ end
+
+ it 'should create a folder to store database views' do
+ res = CouchRestRails::Database.create('foo')
+ File.exist?(File.join(RAILS_ROOT, CouchRestRails.views_path, 'foo', 'views')).should be_true
+ end
+
+ it 'should create a folder to store lucene design docs if Lucene is enabled' do
+ res = CouchRestRails::Database.create('foo')
+ File.exist?(File.join(RAILS_ROOT, CouchRestRails.lucene_path, 'foo', 'lucene')).should be_true
+ end
+
+ it 'should create all databases as defined in CouchRestRails::Document models when no argument is specified' do
+ class CouchRestRailsTestDocumentFoo < CouchRestRails::Document
+ use_database :foo
+ end
+ class CouchRestRailsTestDocumentBar < CouchRestRails::Document
+ use_database :bar
+ end
+ CouchRestRails::Database.create
+ dbf = CouchRest.get(@foo_db_url)
+ dbf['db_name'].should == @foo_db_name
+ dbb = CouchRest.get(@bar_db_url)
+ dbb['db_name'].should == @bar_db_name
+ end
+
+ it 'should issue a warning if no CouchRestRails::Document models are using the database' do
+ res = CouchRestRails::Database.create('foobar')
+ res.should =~ /no CouchRestRails::Document models using/
+ CouchRestRails::Database.delete('foobar')
+ FileUtils.rm_rf(File.join(RAILS_ROOT, CouchRestRails.views_path, 'foobar'))
+ end
+
+ end
+
+ describe "#delete" do
+
+ it 'should delete the specified CouchDB database for the current environment' do
+ CouchRest.database!(@foo_db_url)
+ CouchRestRails::Database.delete('foo')
+ lambda {CouchRest.get(@foo_db_url)}.should raise_error('Resource not found')
+ end
+
+ it 'should do nothing and display a message if the database does not exist' do
+ res = CouchRestRails::Database.delete('foo')
+ res.should =~ /does not exist/i
+ end
+
+ it 'should delete all databases as defined in CouchRestRails::Document models when no argument is specified' do
+ CouchRest.database!(@foo_db_url)
+ CouchRest.database!(@bar_db_url)
+ class CouchRestRailsTestDocumentFoo < CouchRestRails::Document
+ use_database :foo
+ end
+ class CouchRestRailsTestDocumentBar < CouchRestRails::Document
+ use_database :bar
+ end
+ CouchRestRails::Database.delete
+ lambda {CouchRest.get(@foo_db_url)}.should raise_error('Resource not found')
+ lambda {CouchRest.get(@bar_db_url)}.should raise_error('Resource not found')
+ end
+
+ it 'should warn if the views path for the database still exists' do
+ CouchRestRails::Database.create('foo')
+ res = CouchRestRails::Database.delete('foo')
+ res.should =~ /views path still present/
+ end
+
+ it 'should warn if the Lucene path for the database still exists if Lucene is enabled' do
+ CouchRestRails::Database.create('foo')
+ res = CouchRestRails::Database.delete('foo')
+ res.should =~ /Lucene path still present/
+ end
+
+ end
+
+ describe '#list' do
+
+ it 'should return a sorted array of all CouchDB databases for the application' do
+ class CouchRestRailsTestDocumentFoo < CouchRestRails::Document
+ use_database :foo
+ end
+ class CouchRestRailsTestDocumentBar < CouchRestRails::Document
+ use_database :bar
+ end
+ CouchRestRails::Database.list.include?('bar').should be_true
+ CouchRestRails::Database.list.include?('foo').should be_true
+ CouchRestRails::Database.list.index('foo').should > CouchRestRails::Database.list.index('bar')
+ end
+
+ it 'should raise an error if a model does not have a database defined' do
+ class CouchRestRailsTestDocumentNoDatabase < CouchRestRails::Document
+ end
+ lambda {CouchRestRails::Database.list}.should raise_error('CouchRestRailsTestDocumentNoDatabase does not have a database defined')
+ end
+
+ end
+
+end
View
29 vendor/plugins/couchrest-rails/spec/lib/couch_rest_rails/document_spec.rb
@@ -0,0 +1,29 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+describe CouchRestRails::Document do
+
+ class CouchRestRailsTestDocument < CouchRestRails::Document
+ use_database :foo
+ end
+
+ before :each do
+ @doc = CouchRestRailsTestDocument.new
+ end
+
+ it "should inherit from CouchRest::ExtendedDocument" do
+ CouchRestRails::Document.ancestors.include?(CouchRest::ExtendedDocument).should be_true
+ end
+
+ it "should define its CouchDB connection and CouchDB database name" do
+ @doc.database.name.should == "#{COUCHDB_CONFIG[:db_prefix]}foo#{COUCHDB_CONFIG[:db_suffix]}"
+ end
+
+ describe '.unadorned_database_name' do
+
+ it "should return the database name without the prefix and suffix" do
+ CouchRestRailsTestDocument.unadorned_database_name.should == 'foo'
+ end
+
+ end
+
+end
View
101 vendor/plugins/couchrest-rails/spec/lib/couch_rest_rails/fixtures_spec.rb
@@ -0,0 +1,101 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+describe CouchRestRails::Fixtures do
+
+ before :each do
+ setup_foo_bars
+ end
+
+ after :all do
+ cleanup_foo_bars
+ end
+
+ describe '#blurbs' do
+
+ it 'should produce an array of text blurbs for testing purposes' do
+ CouchRestRails::Fixtures.blurbs.is_a?(Array).should be_true
+ end
+
+ it 'should produce a random text blurb' do
+ CouchRestRails::Fixtures.random_blurb.is_a?(String).should be_true
+ end
+
+ end
+
+ describe '#load' do
+
+ after :each do
+ CouchRestRails::Database.delete('foo')
+ CouchRestRails::Database.delete('bar')
+ cleanup_foo_bars
+ end
+
+ it "should notify if the specified database doesn't exist" do
+ res = CouchRestRails::Fixtures.load('foo')
+ res.should =~ /does not exist/i
+ end
+
+ it "should load up the Yaml files in CouchRestRails.fixtures_path as documents for the specified database" do
+ CouchRestRails::Database.create('foo')
+ res = CouchRestRails::Fixtures.load('foo')
+ db = CouchRest.database(@foo_db_url)
+ db.documents['rows'].size.should == 10
+ end
+
+ it "should load up the Yaml files in CouchRestRails.fixtures_path as documents for all databases if no argument is passed" do
+ class CouchRestRailsTestDocumentFoo < CouchRestRails::Document
+ use_database :foo
+ end
+ class CouchRestRailsTestDocumentBar < CouchRestRails::Document
+ use_database :bar
+ end
+ CouchRestRails::Database.create('foo')
+ CouchRestRails::Database.create('bar')
+ CouchRestRails::Fixtures.load
+ dbf = CouchRest.database(@foo_db_url)
+ dbb = CouchRest.database(@bar_db_url)
+ (dbf.documents['rows'].size + dbb.documents['rows'].size).should == 15
+ end
+
+ end
+
+ describe "#dump" do
+
+ before :each do
+ ['foo', 'bar'].each do |db|
+ FileUtils.cp(File.join(RAILS_ROOT, CouchRestRails.fixtures_path, "#{db}.yml"),
+ File.join(RAILS_ROOT, CouchRestRails.fixtures_path, "#{db}x.yml"))
+ CouchRestRails::Database.create("#{db}x")
+ CouchRestRails::Fixtures.load("#{db}x")
+ FileUtils.rm_rf(File.join(RAILS_ROOT, CouchRestRails.fixtures_path, "#{db}x.yml"))
+ end
+ end
+
+ after :each do
+ ['foo', 'bar'].each do |db|
+ CouchRestRails::Database.delete("#{db}x")
+ FileUtils.rm_rf(File.join(RAILS_ROOT, CouchRestRails.fixtures_path, "#{db}x.yml"))
+ end
+ cleanup_foo_bars
+ end
+
+ it "should dump fixtures for the specified database" do
+ res = CouchRestRails::Fixtures.dump('foox')
+ File.exist?(File.join(RAILS_ROOT, CouchRestRails.fixtures_path, 'foox.yml')).should be_true
+ end
+
+ it "should dump fixtures for all databases as defined in CouchRestRails::Document models if no argument is specified" do
+ class CouchRestRailsTestDocumentFoo < CouchRestRails::Document
+ use_database :foox
+ end
+ class CouchRestRailsTestDocumentBar < CouchRestRails::Document
+ use_database :barx
+ end
+ CouchRestRails::Fixtures.dump
+ File.exist?(File.join(RAILS_ROOT, CouchRestRails.fixtures_path, 'foox.yml')).should be_true
+ File.exist?(File.join(RAILS_ROOT, CouchRestRails.fixtures_path, 'barx.yml')).should be_true
+ end
+
+ end
+
+end
View
50 vendor/plugins/couchrest-rails/spec/lib/couch_rest_rails/lucene_spec.rb
@@ -0,0 +1,50 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+describe CouchRestRails::Views do
+
+ before :each do
+ setup_foo_bars
+ CouchRestRails.lucene_path = 'vendor/plugins/couchrest-rails/spec/mock/lucene'
+ end
+
+ after :all do
+ cleanup_foo_bars
+ end
+
+ describe '#push' do
+
+ it "should push the Lucene search in CouchRestRails.lucene_path to a design document for the specified database" do
+ CouchRestRails::Database.delete('foo')
+ CouchRestRails::Database.create('foo')
+ CouchRestRails::Fixtures.load('foo')
+ CouchRestRails::Lucene.push('foo')
+ db = CouchRest.database(@foo_db_url)
+ db.get("_design/default")['fulltext'].should_not be_blank
+ end
+
+ it "should replace existing searches but issue a warning" do
+ CouchRestRails::Database.delete('foo')
+ CouchRestRails::Database.create('foo')
+ CouchRestRails::Lucene.push('foo')
+ res = CouchRestRails::Lucene.push('foo')
+ res.should =~ /Overwriting/
+ end
+
+ it "should push the Lucene searches in CouchRestRails.lucene_path to a design document for all databases if * or no argument is passed" do
+ class CouchRestRailsTestDocumentFoo < CouchRestRails::Document
+ use_database :foo
+ end
+ class CouchRestRailsTestDocumentBar < CouchRestRails::Document
+ use_database :bar
+ end
+ CouchRestRails::Tests.setup
+ CouchRestRails::Lucene.push
+ dbf = CouchRest.database(@foo_db_url)
+ dbb = CouchRest.database(@bar_db_url)
+ dbf.get("_design/default")['fulltext'].should_not be_blank
+ dbb.get("_design/default")['fulltext'].should_not be_blank
+ end
+
+ end
+
+end
View
78 vendor/plugins/couchrest-rails/spec/lib/couch_rest_rails/tests_spec.rb
@@ -0,0 +1,78 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+describe CouchRestRails::Tests do
+
+ before :each do
+ setup_foo_bars
+ CouchRestRails.views_path = 'vendor/plugins/couchrest-rails/spec/mock/views'
+ end
+
+ after :all do
+ cleanup_foo_bars
+ end
+
+ describe '#setup' do
+
+ it 'should always use the test environment' do
+ RAILS_ENV.should == CouchRestRails.test_environment
+ end
+
+ it 'should delete, add, push views and load fixtures for the specified database' do
+ # Dirty up a db first
+ CouchRestRails::Database.create('foo')
+ db = CouchRest.database(@foo_db_url)
+ CouchRestRails::Fixtures.load('foo')
+ db.documents['rows'].size.should == 10
+
+ CouchRestRails::Tests.setup('foo')
+ db.documents['rows'].size.should == 11 # Includes design docs
+ db.view("default/all")['rows'].size.should == 10
+ end
+
+ it 'should delete, add, push views and load fixtures for all databases if none are specified' do
+ class CouchRestRailsTestDocumentFoo < CouchRestRails::Document
+ use_database :foo
+ end
+ class CouchRestRailsTestDocumentBar < CouchRestRails::Document
+ use_database :bar
+ end
+
+ # Dirty up dbs first
+ CouchRestRails::Database.create('foo')
+ CouchRestRails::Database.create('bar')
+ dbf = CouchRest.database(@foo_db_url)
+ dbb = CouchRest.database(@bar_db_url)
+ CouchRestRails::Fixtures.load('foo')
+ CouchRestRails::Fixtures.load('bar')
+ (dbf.documents['rows'].size + dbb.documents['rows'].size).should == 15
+
+ CouchRestRails::Tests.setup
+
+ (dbf.documents['rows'].size + dbb.documents['rows'].size).should == 17 # Includes design docs
+ (dbf.view("default/all")['rows'].size + dbb.view("default/all")['rows'].size).should == 15
+ end
+
+ end
+
+ describe '#teardown' do
+
+ it 'should always use the test environment' do
+ RAILS_ENV.should == CouchRestRails.test_environment
+ end
+
+ it 'should delete the specified test database' do
+ CouchRestRails::Tests.setup('foo')
+ CouchRestRails::Tests.teardown('foo')
+ lambda {CouchRest.get(@foo_db_url)}.should raise_error('Resource not found')
+ end
+
+ it 'should delete all of the test databases if none are specified' do
+ CouchRestRails::Tests.setup
+ CouchRestRails::Tests.teardown
+ lambda {CouchRest.get(@foo_db_url)}.should raise_error('Resource not found')
+ lambda {CouchRest.get(@bar_db_url)}.should raise_error('Resource not found')
+ end
+
+ end
+
+end
View
47 vendor/plugins/couchrest-rails/spec/lib/couch_rest_rails/views_spec.rb
@@ -0,0 +1,47 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+describe CouchRestRails::Views do
+
+ before :each do
+ setup_foo_bars
+ CouchRestRails.views_path = 'vendor/plugins/couchrest-rails/spec/mock/views'
+ end
+
+ after :all do
+ cleanup_foo_bars
+ end
+
+ describe '#push' do
+
+ it "should push the views in CouchRestRails.views_path to a design document for the specified database" do
+ res = CouchRestRails::Database.delete('foo')
+ res = CouchRestRails::Database.create('foo')
+ res = CouchRestRails::Fixtures.load('foo')
+ res = CouchRestRails::Views.push('foo')
+ db = CouchRest.database(@foo_db_url)
+ db.view("default/all")['rows'].size.should == 10
+ end
+
+ it "should replace existing views but issue a warning" do
+ CouchRestRails::Tests.setup('foo')
+ CouchRestRails::Views.push('foo')
+ res = CouchRestRails::Views.push('foo')
+ res.should =~ /Overwriting/
+ end
+
+ it "should push the views in CouchRestRails.views_path to a design document for all databases if * or no arg is passed" do
+ class CouchRestRailsTestDocumentFoo < CouchRestRails::Document
+ use_database :foo
+ end
+ class CouchRestRailsTestDocumentBar < CouchRestRails::Document
+ use_database :bar
+ end
+ CouchRestRails::Tests.setup
+ dbf = CouchRest.database(@foo_db_url)
+ dbb = CouchRest.database(@bar_db_url)
+ (dbf.view("default/all")['rows'].size + dbb.view("default/all")['rows'].size).should == 15
+ end
+
+ end
+
+end
View
59 vendor/plugins/couchrest-rails/spec/lib/couch_rest_rails_spec.rb
@@ -0,0 +1,59 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+require 'rails_generator'
+require 'rails_generator/scripts/generate'
+
+describe 'CouchRestRails' do
+
+ after :all do
+ CouchRest.delete(COUCHDB_CONFIG[:full_path]) rescue nil
+ end
+
+ describe 'plugin installation' do
+
+ before :all do
+ @fake_rails_root = File.join(File.dirname(__FILE__), 'rails_root')
+ FileUtils.mkdir_p(@fake_rails_root)
+ FileUtils.mkdir_p("#{@fake_rails_root}/config/initializers")
+ end
+
+ after :all do
+ FileUtils.rm_rf(@fake_rails_root)
+ end
+
+ it "should generate the necessary files in the host application" do
+ Rails::Generator::Scripts::Generate.new.run(
+ ['couchrest_rails'], :destination => @fake_rails_root)
+ Dir.glob(File.join(@fake_rails_root, "**", "*.*")).map {|f| File.basename(f)}.should ==
+ ['couchdb.yml', 'couchdb.rb']
+ end
+
+ end
+
+ describe ".process_database_method" do
+
+ before :each do
+ class CouchRestRailsTestDocumentFoo < CouchRestRails::Document
+ use_database :foo
+ end
+ class CouchRestRailsTestDocumentBar < CouchRestRails::Document
+ use_database :bar
+ end
+ end
+
+ it "should act on all databases if * passed as an argument" do
+ res = CouchRestRails.process_database_method('*') do |db, r|
+ r << db
+ end
+ res.should == "\nbar\nfoo\n"
+ end
+
+ it "should act on a single database if passed" do
+ res = CouchRestRails.process_database_method('foo') do |db, r|
+ r << db
+ end
+ res.should == "\nfoo\n"
+ end
+
+ end
+
+end
View
46 vendor/plugins/couchrest-rails/spec/matchers/couch_document_validations_spec.rb
@@ -0,0 +1,46 @@
+require File.dirname(__FILE__) + '/../spec_helper'
+
+describe Spec::Rails::Matchers do
+
+ describe 'validations' do
+
+ before :all do
+ class CouchRestRailsTestDocumentFoo < CouchRestRails::Document
+ use_database :foo
+
+ property :something_present
+ property :something_long
+ property :something_formatted
+ property :something_numeric
+
+ validates_presence_of :something_present
+ validates_length_of :something_long, :minimum => 10, :maximum => 50
+ validates_format_of :something_formatted, :with => /[A-Z]{3}-[0-9]{3}/
+ validates_numericality_of :something_numeric
+
+ end
+ @couch_foo = CouchRestRailsTestDocumentFoo.new
+ end
+
+ # Use lengthy matcher names so as not to interfere with
+ # rspec-on-rails-matchers plugin if present
+
+ it "should have a matcher for validates_presence_of" do
+ @couch_foo.should validate_couchdb_document_presence_of(:something_present)
+ end
+
+ it "should have a matcher for validates_numericality_of" do
+ @couch_foo.should validate_couchdb_document_numericality_of(:something_numeric)
+ end
+
+ it "should have a matcher for validates_format_of" do
+ @couch_foo.should validate_couchdb_document_format_of(:something_formatted, :with => /[A-Z]{3}-[0-9]{3}/)
+ end
+
+ it "should have a matcher for validates_length_of" do
+ @couch_foo.should validate_couchdb_document_length_of(:something_long, :minimum => 10, :maximum => 50)
+ end
+
+ end
+
+end
View
11 vendor/plugins/couchrest-rails/spec/mock/fixtures/bar.yml
@@ -0,0 +1,11 @@
+<% def blurb; CouchRestRails::Fixtures.random_blurb; end %>
+
+<% 5.times do |i| %>
+record_<%= i %>:
+ type: Bar
+ question: <%= blurb.split('.').first %>
+ answer: <%= blurb %>
+ rating: <%= rand(10) %>
+ created_at: <%= (Time.now - 3600*rand(10)).utc.strftime('%Y/%m/%d %H:%M:%S +0000') %>
+ updated_at: <%= Time.now.utc.strftime('%Y/%m/%d %H:%M:%S +0000') %>
+<% end %>
View
11 vendor/plugins/couchrest-rails/spec/mock/fixtures/foo.yml
@@ -0,0 +1,11 @@
+<% def blurb; CouchRestRails::Fixtures.random_blurb; end %>
+
+<% 10.times do |i| %>
+record_<%= i %>:
+ type: Foo
+ title: <%= blurb.split('.').first %>
+ body: <%= blurb %>
+ tags: <%= blurb.split(' ').sort_by {rand}[0..3].map {|e| e.downcase.gsub(/[^a-z]/, '').strip}.inspect %>
+ created_at: <%= (Time.now - 3600*rand(10)).utc.strftime('%Y/%m/%d %H:%M:%S +0000') %>
+ updated_at: <%= Time.now.utc.strftime('%Y/%m/%d %H:%M:%S +0000') %>
+<% end %>
View
1  vendor/plugins/couchrest-rails/spec/mock/lucene/bar/lucene/default/search.js
@@ -0,0 +1 @@
+{ "bar": "rab"}
View
1  vendor/plugins/couchrest-rails/spec/mock/lucene/foo/lucene/default/search.js
@@ -0,0 +1 @@
+{ "foo": "oof"}
View
7 vendor/plugins/couchrest-rails/spec/mock/views/bar/views/default/all/map.js
@@ -0,0 +1,7 @@
+function(doc) {
+ emit(doc.created_at, {
+ title : doc.title,
+ body : doc.body,
+ created_at : doc.created_at
+ });
+};
View
7 vendor/plugins/couchrest-rails/spec/mock/views/foo/views/default/all/map.js
@@ -0,0 +1,7 @@
+function(doc) {
+ emit(doc.created_at, {
+ title : doc.title,
+ body : doc.body,
+ created_at : doc.created_at
+ });
+};
View
7 vendor/plugins/couchrest-rails/spec/mock/views/foo/views/default/tags/map.js
@@ -0,0 +1,7 @@
+function(doc) {
+ if(doc.tags && doc.tags.length) {
+ for(var idx in doc.tags) {
+ emit(doc.tags[idx], 1);
+ }
+ }
+}
View
3  vendor/plugins/couchrest-rails/spec/mock/views/foo/views/default/tags/reduce.js
@@ -0,0 +1,3 @@
+function(key, values) {
+ return sum(values);
+}
View
53 vendor/plugins/couchrest-rails/spec/spec_helper.rb
@@ -0,0 +1,53 @@
+begin
+ require File.dirname(__FILE__) + '/../../../../spec/spec_helper'
+rescue LoadError
+ puts "You need to install rspec in your base application"
+ exit
+end
+
+require File.dirname(__FILE__) + '/../lib/spec/rails/matchers/couch_document_validations'
+
+def setup_foo_bars
+
+ # Unset classes
+ Object.class_eval do
+ Object.subclasses_of(CouchRestRails::Document).collect do |klass|
+ remove_const klass.name if const_defined? klass.name
+ end
+ end
+
+ # Config
+ CouchRestRails.use_lucene = true
+ CouchRestRails.views_path = 'vendor/plugins/couchrest-rails/spec/mock/couch'
+ CouchRestRails.fixtures_path = 'vendor/plugins/couchrest-rails/spec/mock/fixtures'
+ CouchRestRails.lucene_path = 'vendor/plugins/couchrest-rails/spec/mock/couch'
+
+ # Paths
+ @foo_db_name = [
+ COUCHDB_CONFIG[:db_prefix], 'foo',
+ COUCHDB_CONFIG[:db_suffix]
+ ].join
+ @foo_db_url = [
+ COUCHDB_CONFIG[:host_path], "/",
+ @foo_db_name
+ ].join
+ @bar_db_name = @foo_db_name.gsub(/foo/, 'bar')
+ @bar_db_url = @foo_db_url.gsub(/foo/, 'bar')
+
+ # Delete existing
+ CouchRest.delete(@foo_db_url) rescue nil
+ CouchRest.delete(@bar_db_url) rescue nil
+
+end
+
+def cleanup_foo_bars
+
+ CouchRest.delete(@foo_db_url) rescue nil
+ CouchRest.delete(@bar_db_url) rescue nil
+
+ ['foo', 'bar', 'foox', 'barx'].each do |db|
+ FileUtils.rm_rf(File.join(RAILS_ROOT, 'vendor/plugins/couchrest-rails/spec/mock/couch', db))
+ FileUtils.rm_rf(File.join(RAILS_ROOT, 'vendor/plugins/couchrest-rails/spec/mock/couch', db))
+ end
+
+end
View
43 vendor/plugins/couchrest-rails/tasks/couch_rest_rails_tasks.rake
@@ -0,0 +1,43 @@
+namespace :couchdb do
+
+ desc "Create a CouchDB database defined in config/couchdb.yml for the current environment (use no database argument to use all databases defined in CouchRestRails::Document models)"
+ task :create, :database, :needs => :environment do |t, args|
+ args.with_defaults(:database => "*", :opts => {})
+ puts CouchRestRails::Database.create(args.database, args.opts)
+ end
+
+ desc "Deletes a CouchDB database for the current RAILS_ENV (use no database argument to use all databases defined in CouchRestRails::Document models)"
+ task :delete, :database, :needs => :environment do |t, args|
+ args.with_defaults(:database => "*", :opts => {})
+ puts CouchRestRails::Database.delete(args.database, args.opts)
+ end
+
+ namespace :fixtures do
+ desc "Load fixtures into a current environment's CouchDB database (use no database argument to use all databases defined in CouchRestRails::Document models)"
+ task :load, :database, :needs => :environment do |t, args|
+ args.with_defaults(:database => "*")
+ puts CouchRestRails::Fixtures.load(args.database)
+ end
+ task :dump, :database, :needs => :environment do |t, args|
+ args.with_defaults(:database => "*")
+ puts CouchRestRails::Fixtures.dump(args.database)
+ end
+ end
+
+ namespace :views do
+ desc "Push views into a current environment's CouchDB database (use no database argument to use all databases defined in CouchRestRails::Document models)"
+ task :push, :database, :needs => :environment do |t, args|
+ args.with_defaults(:database => "*", :opts => {})
+ puts CouchRestRails::Views.push(args.database, args.opts)
+ end
+ end
+
+ namespace :lucene do
+ desc "Push Lucene views into a current environment's CouchDB database (use no database argument to use all databases defined in CouchRestRails::Document models)"
+ task :push, :database, :needs => :environment do |t, args|
+ args.with_defaults(:database => "*", :opts => {})
+ puts CouchRestRails::Lucene.push(args.database, args.opts)
+ end
+ end
+
+end
View
1  vendor/plugins/couchrest-rails/uninstall.rb
@@ -0,0 +1 @@
+# Uninstall hook code here
Please sign in to comment.
Something went wrong with that request. Please try again.