<% end %>
diff --git a/app/views/wiki/tex.rhtml b/app/views/wiki/tex.rhtml
index 6ac2fa5d..47113df4 100644
--- a/app/views/wiki/tex.rhtml
+++ b/app/views/wiki/tex.rhtml
@@ -2,7 +2,6 @@
\usepackage{amsmath}
\usepackage{amsfonts}
-\usepackage[OT1]{fontenc} %rigtige danske bogstaver...
\usepackage{graphicx}
\usepackage{ucs}
\usepackage[utf8x]{inputenc}
@@ -12,12 +11,10 @@
\begin{document}
-\sloppy
-
%-------------------------------------------------------------------
\section*{<%= @page.name %>}
<%= @tex_content %>
-\end{document}
\ No newline at end of file
+\end{document}
diff --git a/app/views/wiki/tex_web.rhtml b/app/views/wiki/tex_web.rhtml
index 45953c52..63cf8a95 100644
--- a/app/views/wiki/tex_web.rhtml
+++ b/app/views/wiki/tex_web.rhtml
@@ -1,19 +1,11 @@
\documentclass[12pt,titlepage]{article}
-\usepackage{fancyhdr}
-\pagestyle{fancy}
-
-\fancyhead[LE,RO]{}
-\fancyhead[LO,RE]{\nouppercase{\bfseries \leftmark}}
-\fancyfoot[C]{\thepage}
-
-\usepackage[danish]{babel} %danske tekster
-\usepackage{a4}
+\usepackage{amsmath}
+\usepackage{amsfonts}
\usepackage{graphicx}
\usepackage{ucs}
-\usepackage[utf8]{inputenc}
-\input epsf
-
+\usepackage[utf8x]{inputenc}
+\usepackage{hyperref}
%-------------------------------------------------------------------
@@ -26,10 +18,8 @@
\tableofcontents
\pagebreak
-\sloppy
-
%-------------------------------------------------------------------
<%= @tex_content %>
-\end{document}
\ No newline at end of file
+\end{document}
diff --git a/config/environment.rb b/config/environment.rb
index 24e89a88..ecee8155 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -7,7 +7,7 @@ Rails::Initializer.run do |config|
# Use the database for sessions instead of the file system
# (create the session table with 'rake create_sessions_table')
- config.action_controller.session_store = :active_record_store
+ #config.action_controller.session_store = :active_record_store
# Enable page/fragment caching by setting a file-based store
# (remember to create the caching directory and make it readable to the application)
diff --git a/public/stylesheets/instiki.css b/public/stylesheets/instiki.css
index 0d92b291..e2f46c1d 100644
--- a/public/stylesheets/instiki.css
+++ b/public/stylesheets/instiki.css
@@ -24,7 +24,7 @@ a:visited {
color:#666;
}
-h1,h2,h3 {
+h1,h2,h3,h4,h5,h6 {
color:#333;
font-family:georgia, verdana, sans-serif;
}
@@ -34,13 +34,21 @@ font-size:200%;
}
h2 {
-font-size:130%;
+font-size:173%;
}
h3 {
+font-size:144%;
+}
+
+h4 {
font-size:120%;
}
+h5,h6 {
+font-size:100%
+}
+
h1#pageName {
line-height:1em;
margin:0.2em 0 0;
diff --git a/vendor/plugins/sqlite3-ruby/sqlite3/pragmas.rb b/vendor/plugins/sqlite3-ruby/sqlite3/pragmas.rb
index 72473871..20b31800 100644
--- a/vendor/plugins/sqlite3-ruby/sqlite3/pragmas.rb
+++ b/vendor/plugins/sqlite3-ruby/sqlite3/pragmas.rb
@@ -246,9 +246,56 @@ module SQLite3
end
def table_info( table, &block ) # :yields: row
- get_query_pragma "table_info", table, &block
+ columns, *rows = execute2("PRAGMA table_info(#{table})")
+
+ needs_tweak_default = version_compare(driver.libversion, "3.3.7") > 0
+
+ result = [] unless block_given?
+ rows.each do |row|
+ new_row = {}
+ columns.each_with_index do |name, index|
+ new_row[name] = row[index]
+ end
+
+ tweak_default(new_row) if needs_tweak_default
+
+ if block_given?
+ yield new_row
+ else
+ result << new_row
+ end
+ end
+
+ result
end
-
+
+ private
+
+ # Compares two version strings
+ def version_compare(v1, v2)
+ v1 = v1.split(".").map { |i| i.to_i }
+ v2 = v2.split(".").map { |i| i.to_i }
+ parts = [v1.length, v2.length].max
+ v1.push 0 while v1.length < parts
+ v2.push 0 while v2.length < parts
+ v1.zip(v2).each do |a,b|
+ return -1 if a < b
+ return 1 if a > b
+ end
+ return 0
+ end
+
+ # Since SQLite 3.3.8, the table_info pragma has returned the default
+ # value of the row as a quoted SQL value. This method essentially
+ # unquotes those values.
+ def tweak_default(hash)
+ case hash["dflt_value"]
+ when /^null$/i then
+ hash["dflt_value"] = nil
+ when /^'(.*)'$/
+ hash["dflt_value"] = $1.gsub(/''/, "'")
+ end
+ end
end
end
diff --git a/vendor/plugins/sqlite3-ruby/sqlite3/version.rb b/vendor/plugins/sqlite3-ruby/sqlite3/version.rb
index 12e678b0..2398c0ac 100644
--- a/vendor/plugins/sqlite3-ruby/sqlite3/version.rb
+++ b/vendor/plugins/sqlite3-ruby/sqlite3/version.rb
@@ -36,9 +36,10 @@ module SQLite3
MAJOR = 1
MINOR = 2
- TINY = 0
+ TINY = 1
STRING = [ MAJOR, MINOR, TINY ].join( "." )
+ #:beta-tag:
end
diff --git a/vendor/rails/actionmailer/CHANGELOG b/vendor/rails/actionmailer/CHANGELOG
index 34d1ac4b..0719e727 100644
--- a/vendor/rails/actionmailer/CHANGELOG
+++ b/vendor/rails/actionmailer/CHANGELOG
@@ -1,3 +1,38 @@
+*1.13.2* (February 5th, 2007)
+
+* Deprecate server_settings renaming it to smtp_settings, add sendmail_settings to allow you to override the arguments to and location of the sendmail executable. [Koz]
+
+
+*1.3.1* (January 16th, 2007)
+
+* Depend on Action Pack 1.13.1
+
+
+*1.3.0* (January 16th, 2007)
+
+* Make mime version default to 1.0. closes #2323 [ror@andreas-s.net]
+
+* Make sure quoted-printable text is decoded correctly when only portions of the text are encoded. closes #3154. [jon@siliconcircus.com]
+
+* Make sure DOS newlines in quoted-printable text are normalized to unix newlines before unquoting. closes #4166 and #4452. [Jamis Buck]
+
+* Fixed that iconv decoding should catch InvalidEncoding #3153 [jon@siliconcircus.com]
+
+* Tighten rescue clauses. #5985 [james@grayproductions.net]
+
+* Automatically included ActionController::UrlWriter, such that URL generation can happen within ActionMailer controllers. [DHH]
+
+* Replace Reloadable with Reloadable::Deprecated. [Nicholas Seckar]
+
+* Resolve action naming collision. #5520 [ssinghi@kreeti.com]
+
+* ActionMailer::Base documentation rewrite. Closes #4991 [Kevin Clark, Marcel Molina Jr.]
+
+* Replace alias method chaining with Module#alias_method_chain. [Marcel Molina Jr.]
+
+* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.]
+
+
*1.2.5* (August 10th, 2006)
* Depend on Action Pack 1.12.5
@@ -22,12 +57,12 @@
* Depend on Action Pack 1.12.2
-*1.2.1* (April 6th, 2005)
+*1.2.1* (April 6th, 2006)
* Be part of Rails 1.1.1
-*1.2.0* (March 27th, 2005)
+*1.2.0* (March 27th, 2006)
* Nil charset caused subject line to be improperly quoted in implicitly multipart messages #2662 [ehalvorsen+rails@runbox.com]
diff --git a/vendor/rails/actionmailer/MIT-LICENSE b/vendor/rails/actionmailer/MIT-LICENSE
index 26f55e77..5856add6 100644
--- a/vendor/rails/actionmailer/MIT-LICENSE
+++ b/vendor/rails/actionmailer/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2004 David Heinemeier Hansson
+Copyright (c) 2004-2006 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/vendor/rails/actionmailer/README b/vendor/rails/actionmailer/README
index 8c85e1ae..354c1ab8 100755
--- a/vendor/rails/actionmailer/README
+++ b/vendor/rails/actionmailer/README
@@ -1,7 +1,7 @@
= Action Mailer -- Easy email delivery and testing
Action Mailer is a framework for designing email-service layers. These layers
-are used to consolidate code for sending out forgotten passwords, welcoming
+are used to consolidate code for sending out forgotten passwords, welcome
wishes on signup, invoices for billing, and any other use case that requires
a written notification to either a person or another system.
@@ -136,13 +136,10 @@ Action Mailer is released under the MIT license.
== Support
-The Action Mailer homepage is http://actionmailer.rubyonrails.org. You can find
+The Action Mailer homepage is http://www.rubyonrails.org. You can find
the Action Mailer RubyForge page at http://rubyforge.org/projects/actionmailer.
And as Jim from Rake says:
Feel free to submit commits or feature requests. If you send a patch,
remember to update the corresponding unit tests. If fact, I prefer
- new feature to be submitted in the form of new unit tests.
-
-For other information, feel free to ask on the ruby-talk mailing list (which
-is mirrored to comp.lang.ruby) or contact mailto:david@loudthinking.com.
+ new feature to be submitted in the form of new unit tests.
\ No newline at end of file
diff --git a/vendor/rails/actionmailer/Rakefile b/vendor/rails/actionmailer/Rakefile
index 6095c6dc..8773ce30 100755
--- a/vendor/rails/actionmailer/Rakefile
+++ b/vendor/rails/actionmailer/Rakefile
@@ -54,7 +54,7 @@ spec = Gem::Specification.new do |s|
s.rubyforge_project = "actionmailer"
s.homepage = "http://www.rubyonrails.org"
- s.add_dependency('actionpack', '= 1.12.5' + PKG_BUILD)
+ s.add_dependency('actionpack', '= 1.13.2' + PKG_BUILD)
s.has_rdoc = true
s.requirements << 'none'
diff --git a/vendor/rails/actionmailer/lib/action_mailer.rb b/vendor/rails/actionmailer/lib/action_mailer.rb
index a489e32b..eeb1a428 100755
--- a/vendor/rails/actionmailer/lib/action_mailer.rb
+++ b/vendor/rails/actionmailer/lib/action_mailer.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004 David Heinemeier Hansson
+# Copyright (c) 2004-2006 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -21,14 +21,13 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
-begin
- require 'action_controller'
-rescue LoadError
+unless defined?(ActionController)
begin
- require File.dirname(__FILE__) + '/../../actionpack/lib/action_controller'
+ $:.unshift "#{File.dirname(__FILE__)}/../../actionpack/lib"
+ require 'action_controller'
rescue LoadError
require 'rubygems'
- require_gem 'actionpack', '>= 1.9.1'
+ gem 'actionpack', '>= 1.12.5'
end
end
@@ -48,4 +47,4 @@ ActionMailer::Base.class_eval do
helper MailHelper
end
-silence_warnings { TMail::Encoder.const_set("MAX_LINE_LEN", 200) }
\ No newline at end of file
+silence_warnings { TMail::Encoder.const_set("MAX_LINE_LEN", 200) }
diff --git a/vendor/rails/actionmailer/lib/action_mailer/adv_attr_accessor.rb b/vendor/rails/actionmailer/lib/action_mailer/adv_attr_accessor.rb
index 50afe4d7..cfd72301 100644
--- a/vendor/rails/actionmailer/lib/action_mailer/adv_attr_accessor.rb
+++ b/vendor/rails/actionmailer/lib/action_mailer/adv_attr_accessor.rb
@@ -1,7 +1,6 @@
module ActionMailer
module AdvAttrAccessor #:nodoc:
- def self.append_features(base)
- super
+ def self.included(base)
base.extend(ClassMethods)
end
diff --git a/vendor/rails/actionmailer/lib/action_mailer/base.rb b/vendor/rails/actionmailer/lib/action_mailer/base.rb
index a67072a9..4f1b6787 100644
--- a/vendor/rails/actionmailer/lib/action_mailer/base.rb
+++ b/vendor/rails/actionmailer/lib/action_mailer/base.rb
@@ -7,7 +7,9 @@ require 'tmail/net'
module ActionMailer #:nodoc:
# ActionMailer allows you to send email from your application using a mailer model and views.
#
+ #
# = Mailer Models
+ #
# To use ActionMailer, you need to create a mailer model.
#
# $ script/generate mailer Notifier
@@ -23,7 +25,7 @@ module ActionMailer #:nodoc:
# recipients recipient.email_address_with_name
# from "system@example.com"
# subject "New account information"
- # body "account" => recipient
+ # body :account => recipient
# end
# end
#
@@ -45,7 +47,9 @@ module ActionMailer #:nodoc:
# in an instance variable @account with the value of recipient being accessible in the
# view.
#
- # = Mailer Views
+ #
+ # = Mailer views
+ #
# Like ActionController, each mailer class has a corresponding view directory
# in which each method of the class looks for a template with its name.
# To define a template to be used with a mailing, create an .rhtml file with the same name as the method
@@ -59,7 +63,30 @@ module ActionMailer #:nodoc:
# Hi <%= @account.name %>,
# Thanks for joining our service! Please check back often.
#
- # = Sending Mail
+ # You can even use Action Pack helpers in these views. For example:
+ #
+ # You got a new note!
+ # <%= truncate(note.body, 25) %>
+ #
+ #
+ # = Generating URLs for mailer views
+ #
+ # If your view includes URLs from the application, you need to use url_for in the mailing method instead of the view.
+ # Unlike controllers from Action Pack, the mailer instance doesn't have any context about the incoming request. That's
+ # why you need to jump this little hoop and supply all the details needed for the URL. Example:
+ #
+ # def signup_notification(recipient)
+ # recipients recipient.email_address_with_name
+ # from "system@example.com"
+ # subject "New account information"
+ # body :account => recipient,
+ # :home_page => url_for(:host => "example.com", :controller => "welcome", :action => "greeting")
+ # end
+ #
+ # You can now access @home_page in the template and get http://example.com/welcome/greeting.
+ #
+ # = Sending mail
+ #
# Once a mailer action and template are defined, you can deliver your message or create it and save it
# for delivery later:
#
@@ -73,7 +100,9 @@ module ActionMailer #:nodoc:
# like to deliver. The signup_notification method defined above is
# delivered by invoking Notifier.deliver_signup_notification.
#
- # = HTML Email
+ #
+ # = HTML email
+ #
# To send mail as HTML, make sure your view (the .rhtml file) generates HTML and
# set the content type to html.
#
@@ -87,7 +116,9 @@ module ActionMailer #:nodoc:
# end
# end
#
- # = Multipart Email
+ #
+ # = Multipart email
+ #
# You can explicitly specify multipart messages:
#
# class ApplicationMailer < ActionMailer::Base
@@ -120,7 +151,9 @@ module ActionMailer #:nodoc:
# with the corresponding content type. The same body hash is passed to
# each template.
#
+ #
# = Attachments
+ #
# Attachments can be added by using the +attachment+ method.
#
# Example:
@@ -141,6 +174,7 @@ module ActionMailer #:nodoc:
# end
# end
#
+ #
# = Configuration options
#
# These options are specified on the class level, like ActionMailer::Base.template_root = "/my/templates"
@@ -150,7 +184,7 @@ module ActionMailer #:nodoc:
# * logger - the logger is used for generating information on the mailing run if available.
# Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
#
- # * server_settings - Allows detailed configuration of the server:
+ # * smtp_settings - Allows detailed configuration for :smtp delivery method:
# * :address Allows you to use a remote mail server. Just change it from its default "localhost" setting.
# * :port On the off chance that your mail server doesn't run on port 25, you can change it.
# * :domain If you need to specify a HELO domain, you can do it here.
@@ -159,10 +193,12 @@ module ActionMailer #:nodoc:
# * :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
+ # * :location The location of the sendmail executable, defaults to "/usr/sbin/sendmail"
+ # * :arguments The command line arguments
# * raise_delivery_errors - whether or not errors should be raised if the email fails to be delivered.
#
# * delivery_method - Defines a delivery method. Possible values are :smtp (default), :sendmail, and :test.
- # Sendmail is assumed to be present at "/usr/sbin/sendmail".
#
# * perform_deliveries - Determines whether deliver_* methods are actually carried out. By default they are,
# but this can be turned off to help functional testing.
@@ -174,9 +210,8 @@ module ActionMailer #:nodoc:
# 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.
- # * default_mime_version - The default mime version used for the message. Defaults to nil. You
- # can also pick a different value from inside a method with @mime_version. When multipart messages are in
- # use, @mime_version will be set to "1.0" if it is not set inside a method.
+ # * 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
# which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to
# ["text/html", "text/enriched", "text/plain"]. Items that appear first in the array have higher priority in the mail client
@@ -184,17 +219,18 @@ module ActionMailer #:nodoc:
# @implicit_parts_order.
class Base
include AdvAttrAccessor, PartContainer
+ include ActionController::UrlWriter
# Action Mailer subclasses should be reloaded by the dispatcher in Rails
# when Dependencies.mechanism = :load.
- include Reloadable::Subclasses
+ include Reloadable::Deprecated
private_class_method :new #:nodoc:
class_inheritable_accessor :template_root
cattr_accessor :logger
- @@server_settings = {
+ @@smtp_settings = {
:address => "localhost",
:port => 25,
:domain => 'localhost.localdomain',
@@ -202,7 +238,13 @@ module ActionMailer #:nodoc:
:password => nil,
:authentication => nil
}
- cattr_accessor :server_settings
+ cattr_accessor :smtp_settings
+
+ @@sendmail_settings = {
+ :location => '/usr/sbin/sendmail',
+ :arguments => '-i -t'
+ }
+ cattr_accessor :sendmail_settings
@@raise_delivery_errors = true
cattr_accessor :raise_delivery_errors
@@ -222,7 +264,7 @@ module ActionMailer #:nodoc:
@@default_content_type = "text/plain"
cattr_accessor :default_content_type
- @@default_mime_version = nil
+ @@default_mime_version = "1.0"
cattr_accessor :default_mime_version
@@default_implicit_parts_order = [ "text/html", "text/enriched", "text/plain" ]
@@ -321,6 +363,18 @@ module ActionMailer #:nodoc:
def deliver(mail)
new.deliver!(mail)
end
+
+ # Server Settings is the old name for smtp_settings
+ def server_settings
+ smtp_settings
+ end
+ deprecate :server_settings=>"It's now named smtp_settings"
+
+ def server_settings=(settings)
+ ActiveSupport::Deprecation.warn("server_settings has been renamed smtp_settings, this warning will be removed with rails 2.0", caller)
+ self.smtp_settings=settings
+ end
+
end
# Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
@@ -348,7 +402,7 @@ module ActionMailer #:nodoc:
templates.each do |path|
# TODO: don't hardcode rhtml|rxml
basename = File.basename(path)
- next unless md = /^([^\.]+)\.([^\.]+\.[^\+]+)\.(rhtml|rxml)$/.match(basename)
+ next unless md = /^([^\.]+)\.([^\.]+\.[^\.]+)\.(rhtml|rxml)$/.match(basename)
template_name = basename
content_type = md.captures[1].gsub('.', '/')
@parts << Part.new(:content_type => content_type,
@@ -395,7 +449,7 @@ module ActionMailer #:nodoc:
begin
send("perform_delivery_#{delivery_method}", mail) if perform_deliveries
- rescue Object => e
+ rescue Exception => e # Net::SMTP errors or sendmail pipe errors
raise e if raise_delivery_errors
end
@@ -508,14 +562,14 @@ module ActionMailer #:nodoc:
destinations = mail.destinations
mail.ready_to_send
- Net::SMTP.start(server_settings[:address], server_settings[:port], server_settings[:domain],
- server_settings[:user_name], server_settings[:password], server_settings[:authentication]) do |smtp|
+ 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.sendmail(mail.encoded, mail.from, destinations)
end
end
def perform_delivery_sendmail(mail)
- IO.popen("/usr/sbin/sendmail -i -t","w+") do |sm|
+ IO.popen("#{sendmail_settings[:location]} #{sendmail_settings[:arguments]}","w+") do |sm|
sm.print(mail.encoded.gsub(/\r/, ''))
sm.flush
end
diff --git a/vendor/rails/actionmailer/lib/action_mailer/helpers.rb b/vendor/rails/actionmailer/lib/action_mailer/helpers.rb
index b53326ca..8176ba8a 100644
--- a/vendor/rails/actionmailer/lib/action_mailer/helpers.rb
+++ b/vendor/rails/actionmailer/lib/action_mailer/helpers.rb
@@ -1,8 +1,6 @@
module ActionMailer
module Helpers #:nodoc:
- def self.append_features(base) #:nodoc:
- super
-
+ def self.included(base) #:nodoc:
# Initialize the base module to aggregate its helpers.
base.class_inheritable_accessor :master_helper_module
base.master_helper_module = Module.new
@@ -13,14 +11,12 @@ module ActionMailer
base.class_eval do
# Wrap inherited to create a new master helper module for subclasses.
class << self
- alias_method :inherited_without_helper, :inherited
- alias_method :inherited, :inherited_with_helper
+ alias_method_chain :inherited, :helper
end
# Wrap initialize_template_class to extend new template class
# instances with the master helper module.
- alias_method :initialize_template_class_without_helper, :initialize_template_class
- alias_method :initialize_template_class, :initialize_template_class_with_helper
+ alias_method_chain :initialize_template_class, :helper
end
end
diff --git a/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail/quoting.rb b/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail/quoting.rb
index a56e2267..69424234 100644
--- a/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail/quoting.rb
+++ b/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail/quoting.rb
@@ -49,25 +49,31 @@ module TMail
class << self
def unquote_and_convert_to(text, to_charset, from_charset = "iso-8859-1", preserve_underscores=false)
return "" if text.nil?
- if text =~ /^=\?(.*?)\?(.)\?(.*)\?=$/
- from_charset = $1
- quoting_method = $2
- text = $3
- case quoting_method.upcase
- when "Q" then
- unquote_quoted_printable_and_convert_to(text, to_charset, from_charset, preserve_underscores)
- when "B" then
- unquote_base64_and_convert_to(text, to_charset, from_charset)
- else
- raise "unknown quoting method #{quoting_method.inspect}"
- end
- else
- convert_to(text, to_charset, from_charset)
+ text.gsub(/(.*?)(?:(?:=\?(.*?)\?(.)\?(.*?)\?=)|$)/) do
+ before = $1
+ from_charset = $2
+ quoting_method = $3
+ text = $4
+
+ before = convert_to(before, to_charset, from_charset) if before.length > 0
+ before + case quoting_method
+ when "q", "Q" then
+ unquote_quoted_printable_and_convert_to(text, to_charset, from_charset, preserve_underscores)
+ when "b", "B" then
+ unquote_base64_and_convert_to(text, to_charset, from_charset)
+ when nil then
+ # will be nil at the end of the string, due to the nature of
+ # the regex used.
+ ""
+ else
+ raise "unknown quoting method #{quoting_method.inspect}"
+ end
end
end
def unquote_quoted_printable_and_convert_to(text, to, from, preserve_underscores=false)
text = text.gsub(/_/, " ") unless preserve_underscores
+ text = text.gsub(/\r\n|\r/, "\n") # normalize newlines
convert_to(text.unpack("M*").first, to, from)
end
@@ -80,7 +86,7 @@ module TMail
def convert_to(text, to, from)
return text unless to && from
text ? Iconv.iconv(to, from, text).first : ""
- rescue Iconv::IllegalSequence, Errno::EINVAL
+ rescue Iconv::IllegalSequence, Iconv::InvalidEncoding, Errno::EINVAL
# the 'from' parameter specifies a charset other than what the text
# actually is...not much we can do in this case but just return the
# unconverted text.
diff --git a/vendor/rails/actionmailer/lib/action_mailer/version.rb b/vendor/rails/actionmailer/lib/action_mailer/version.rb
index 21bc3f6a..44d87158 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 = 1
- MINOR = 2
- TINY = 5
+ MINOR = 3
+ TINY = 2
STRING = [MAJOR, MINOR, TINY].join('.')
end
diff --git a/vendor/rails/actionmailer/test/fixtures/path.with.dots/multipart_with_template_path_with_dots.rhtml b/vendor/rails/actionmailer/test/fixtures/path.with.dots/multipart_with_template_path_with_dots.rhtml
index 897a5065..e69de29b 100644
--- a/vendor/rails/actionmailer/test/fixtures/path.with.dots/multipart_with_template_path_with_dots.rhtml
+++ b/vendor/rails/actionmailer/test/fixtures/path.with.dots/multipart_with_template_path_with_dots.rhtml
@@ -1 +0,0 @@
-Have a lovely picture, from me. Enjoy!
\ No newline at end of file
diff --git a/vendor/rails/actionmailer/test/mail_helper_test.rb b/vendor/rails/actionmailer/test/mail_helper_test.rb
index bf5bf7f3..19f3707d 100644
--- a/vendor/rails/actionmailer/test/mail_helper_test.rb
+++ b/vendor/rails/actionmailer/test/mail_helper_test.rb
@@ -1,8 +1,4 @@
-$:.unshift(File.dirname(__FILE__) + "/../lib/")
-$:.unshift File.dirname(__FILE__) + "/fixtures/helpers"
-
-require 'test/unit'
-require 'action_mailer'
+require "#{File.dirname(__FILE__)}/abstract_unit"
module MailerHelper
def person_name
@@ -56,8 +52,6 @@ class HelperMailer < ActionMailer::Base
helper_method :name_of_the_mailer_class
end
-HelperMailer.template_root = File.dirname(__FILE__) + "/fixtures"
-
class MailerHelperTest < Test::Unit::TestCase
def new_mail( charset="utf-8" )
mail = TMail::Mail.new
diff --git a/vendor/rails/actionmailer/test/mail_render_test.rb b/vendor/rails/actionmailer/test/mail_render_test.rb
index d5819652..42454fef 100644
--- a/vendor/rails/actionmailer/test/mail_render_test.rb
+++ b/vendor/rails/actionmailer/test/mail_render_test.rb
@@ -1,7 +1,4 @@
-$:.unshift(File.dirname(__FILE__) + "/../lib/")
-
-require 'test/unit'
-require 'action_mailer'
+require "#{File.dirname(__FILE__)}/abstract_unit"
class RenderMailer < ActionMailer::Base
def inline_template(recipient)
@@ -24,7 +21,21 @@ class RenderMailer < ActionMailer::Base
end
end
-RenderMailer.template_root = File.dirname(__FILE__) + "/fixtures"
+class FirstMailer < ActionMailer::Base
+ def share(recipient)
+ recipients recipient
+ subject "using helpers"
+ from "tester@example.com"
+ end
+end
+
+class SecondMailer < ActionMailer::Base
+ def share(recipient)
+ recipients recipient
+ subject "using helpers"
+ from "tester@example.com"
+ end
+end
class RenderHelperTest < Test::Unit::TestCase
def setup
@@ -46,3 +57,23 @@ class RenderHelperTest < Test::Unit::TestCase
end
end
+class FirstSecondHelperTest < Test::Unit::TestCase
+ def setup
+ ActionMailer::Base.delivery_method = :test
+ ActionMailer::Base.perform_deliveries = true
+ ActionMailer::Base.deliveries = []
+
+ @recipient = 'test@localhost'
+ end
+
+ def test_ordering
+ mail = FirstMailer.create_share(@recipient)
+ assert_equal "first mail", mail.body.strip
+ mail = SecondMailer.create_share(@recipient)
+ assert_equal "second mail", mail.body.strip
+ mail = FirstMailer.create_share(@recipient)
+ assert_equal "first mail", mail.body.strip
+ mail = SecondMailer.create_share(@recipient)
+ assert_equal "second mail", mail.body.strip
+ end
+end
diff --git a/vendor/rails/actionmailer/test/mail_service_test.rb b/vendor/rails/actionmailer/test/mail_service_test.rb
index 5fdf4074..31a871a0 100755
--- a/vendor/rails/actionmailer/test/mail_service_test.rb
+++ b/vendor/rails/actionmailer/test/mail_service_test.rb
@@ -1,31 +1,8 @@
-$:.unshift(File.dirname(__FILE__) + "/../lib/")
-
-require 'test/unit'
-require 'action_mailer'
-
-class MockSMTP
- def self.deliveries
- @@deliveries
- end
-
- def initialize
- @@deliveries = []
- end
-
- def sendmail(mail, from, to)
- @@deliveries << [mail, from, to]
- end
-end
-
-class Net::SMTP
- def self.start(*args)
- yield MockSMTP.new
- end
-end
+require "#{File.dirname(__FILE__)}/abstract_unit"
class FunkyPathMailer < ActionMailer::Base
- self.template_root = "#{File.dirname(__FILE__)}/fixtures/path.with.dots"
-
+ self.template_root = "#{File.dirname(__FILE__)}/fixtures/path.with.dots"
+
def multipart_with_template_path_with_dots(recipient)
recipients recipient
subject "Have a lovely picture"
@@ -33,14 +10,9 @@ class FunkyPathMailer < ActionMailer::Base
attachment :content_type => "image/jpeg",
:body => "not really a jpeg, we're only testing, after all"
end
-
- def template_path
- "#{File.dirname(__FILE__)}/fixtures/path.with.dots"
- end
end
class TestMailer < ActionMailer::Base
-
def signed_up(recipient)
@recipients = recipient
@subject = "[Signed up] Welcome #{recipient}"
@@ -222,7 +194,7 @@ class TestMailer < ActionMailer::Base
subject "nested multipart"
from "test@example.com"
content_type "multipart/mixed"
- part :content_type => "multipart/alternative", :content_disposition => "inline" do |p|
+ part :content_type => "multipart/alternative", :content_disposition => "inline", :headers => { "foo" => "bar" } do |p|
p.part :content_type => "text/plain", :body => "test text\nline #2"
p.part :content_type => "text/html", :body => "test HTML \nline #2"
end
@@ -273,8 +245,6 @@ class TestMailer < ActionMailer::Base
end
end
-TestMailer.template_root = File.dirname(__FILE__) + "/fixtures"
-
class ActionMailerTest < Test::Unit::TestCase
include ActionMailer::Quoting
@@ -284,6 +254,7 @@ class ActionMailerTest < Test::Unit::TestCase
def new_mail( charset="utf-8" )
mail = TMail::Mail.new
+ mail.mime_version = "1.0"
if charset
mail.set_content_type "text", "plain", { "charset" => charset }
end
@@ -306,6 +277,7 @@ class ActionMailerTest < Test::Unit::TestCase
assert_equal "multipart/mixed", created.content_type
assert_equal "multipart/alternative", created.parts.first.content_type
+ assert_equal "bar", created.parts.first.header['foo'].to_s
assert_equal "text/plain", created.parts.first.parts.first.content_type
assert_equal "text/html", created.parts.first.parts[1].content_type
assert_equal "application/octet-stream", created.parts[1].content_type
@@ -324,7 +296,6 @@ class ActionMailerTest < Test::Unit::TestCase
expected.body = "Hello there, \n\nMr. #{@recipient}"
expected.from = "system@loudthinking.com"
expected.date = Time.local(2004, 12, 12)
- expected.mime_version = nil
created = nil
assert_nothing_raised { created = TestMailer.create_signed_up(@recipient) }
@@ -816,17 +787,30 @@ EOF
assert_match %r{format=flowed}, mail['content-type'].to_s
assert_match %r{charset=utf-8}, mail['content-type'].to_s
end
+
+ def test_deprecated_server_settings
+ old_smtp_settings = ActionMailer::Base.smtp_settings
+ assert_deprecated do
+ ActionMailer::Base.server_settings
+ end
+ assert_deprecated do
+ ActionMailer::Base.server_settings={}
+ assert_equal Hash.new, ActionMailer::Base.smtp_settings
+ end
+ ensure
+ ActionMailer::Base.smtp_settings=old_smtp_settings
+ end
end
-class InheritableTemplateRootTest < Test::Unit::TestCase
- def test_attr
- expected = "#{File.dirname(__FILE__)}/fixtures/path.with.dots"
- assert_equal expected, FunkyPathMailer.template_root
-
- sub = Class.new(FunkyPathMailer)
- sub.template_root = 'test/path'
-
- assert_equal 'test/path', sub.template_root
- assert_equal expected, FunkyPathMailer.template_root
- end
-end
+class InheritableTemplateRootTest < Test::Unit::TestCase
+ def test_attr
+ expected = "#{File.dirname(__FILE__)}/fixtures/path.with.dots"
+ assert_equal expected, FunkyPathMailer.template_root
+
+ sub = Class.new(FunkyPathMailer)
+ sub.template_root = 'test/path'
+
+ assert_equal 'test/path', sub.template_root
+ assert_equal expected, FunkyPathMailer.template_root
+ end
+end
diff --git a/vendor/rails/actionmailer/test/quoting_test.rb b/vendor/rails/actionmailer/test/quoting_test.rb
index 6291cd3d..77bd769b 100644
--- a/vendor/rails/actionmailer/test/quoting_test.rb
+++ b/vendor/rails/actionmailer/test/quoting_test.rb
@@ -1,7 +1,4 @@
-$:.unshift(File.dirname(__FILE__) + "/../lib/")
-$:.unshift(File.dirname(__FILE__) + "/../lib/action_mailer/vendor")
-
-require 'test/unit'
+require "#{File.dirname(__FILE__)}/abstract_unit"
require 'tmail'
require 'tempfile'
@@ -22,6 +19,18 @@ class QuotingTest < Test::Unit::TestCase
assert_equal unquoted, original
end
+ # test an email that has been created using \r\n newlines, instead of
+ # \n newlines.
+ def test_email_quoted_with_0d0a
+ mail = TMail::Mail.parse(IO.read("#{File.dirname(__FILE__)}/fixtures/raw_email_quoted_with_0d0a"))
+ assert_match %r{Elapsed time}, mail.body
+ end
+
+ def test_email_with_partially_quoted_subject
+ mail = TMail::Mail.parse(IO.read("#{File.dirname(__FILE__)}/fixtures/raw_email_with_partially_quoted_subject"))
+ assert_equal "Re: Test: \"\346\274\242\345\255\227\" mid \"\346\274\242\345\255\227\" tail", mail.subject
+ end
+
private
# This whole thing *could* be much simpler, but I don't think Tempfile,
@@ -40,7 +49,7 @@ class QuotingTest < Test::Unit::TestCase
end
system("ruby #{test_name} > #{res_name}") or raise "could not run test in sandbox"
- File.read(res_name)
+ File.read(res_name).chomp
ensure
File.delete(test_name) rescue nil
File.delete(res_name) rescue nil
diff --git a/vendor/rails/actionmailer/test/tmail_test.rb b/vendor/rails/actionmailer/test/tmail_test.rb
index 3930c7d3..7d83a68a 100644
--- a/vendor/rails/actionmailer/test/tmail_test.rb
+++ b/vendor/rails/actionmailer/test/tmail_test.rb
@@ -1,8 +1,4 @@
-$:.unshift(File.dirname(__FILE__) + "/../lib/")
-$:.unshift File.dirname(__FILE__) + "/fixtures/helpers"
-
-require 'test/unit'
-require 'action_mailer'
+require "#{File.dirname(__FILE__)}/abstract_unit"
class TMailMailTest < Test::Unit::TestCase
def test_body
diff --git a/vendor/rails/actionpack/CHANGELOG b/vendor/rails/actionpack/CHANGELOG
index be0d4064..9480aecd 100644
--- a/vendor/rails/actionpack/CHANGELOG
+++ b/vendor/rails/actionpack/CHANGELOG
@@ -1,3 +1,557 @@
+*1.13.2* (February 5th, 2007)
+
+* Add much-needed html-scanner tests. Fixed CDATA parsing bug. [Rick]
+
+* improve error message for Routing for named routes. [Rob Sanheim]
+
+* Added enhanced docs to routing assertions. [Rob Sanheim]
+
+* fix form_for example in ActionController::Resources documentation. [gnarg]
+
+* Add singleton resources from trunk [Rick Olson]
+
+* TestSession supports indifferent access so session['foo'] == session[:foo] in your tests. #7372 [julik, jean.helou]
+
+* select :multiple => true suffixes the attribute name with [] unless already suffixed. #6977 [nik.kakelin, ben, julik]
+
+* Improve routes documentation. #7095 [zackchandler]
+
+* Resource member routes require :id, eliminating the ambiguous overlap with collection routes. #7229 [dkubb]
+
+* Fixed NumberHelper#number_with_delimiter to use "." always for splitting the original number, not the delimiter parameter #7389 [ceefour]
+
+* Autolinking recognizes trailing and embedded . , : ; #7354 [Jarkko Laine]
+
+* Make TextHelper::auto_link recognize URLs with colons in path correctly, fixes #7268. [imajes]
+
+* Improved auto_link to match more valid urls correctly [Tobias Luetke]
+
+
+*1.13.1* (January 18th, 2007)
+
+* Fixed content-type bug in Prototype [sam]
+
+
+*1.13.0* (January 16th, 2007)
+
+* Modernize cookie testing code, and increase coverage (Heckle++) #7101 [Kevin Clark]
+
+* Heckling ActionController::Resources::Resource revealed that set_prefixes didn't break when :name_prefix was munged. #7081 [Kevin Clark]
+
+* Update to Prototype 1.5.0. [Sam Stephenson]
+
+* Allow exempt_from_layout :rhtml. #6742, #7026 [dcmanges, Squeegy]
+
+* Fix parsing of array[] CGI parameters so extra empty values aren't included. #6252 [Nicholas Seckar, aiwilliams, brentrowland]
+
+* link_to_unless_current works with full URLs as well as paths. #6891 [Jarkko Laine, manfred, idrifter]
+
+* Fix HTML::Node to output double quotes instead of single quotes. Closes #6845 [mitreandy]
+
+* Fix no method error with error_messages_on. Closes #6935 [nik.wakelin Koz]
+
+* Slight doc tweak to the ActionView::Helpers::PrototypeHelper#replace docs. Closes #6922 [Steven Bristol]
+
+* Slight doc tweak to #prepend_filter. Closes #6493 [Jeremy Voorhis]
+
+* Add more extensive documentation to the AssetTagHelper. Closes #6452 [Bob Silva]
+
+* Clean up multiple calls to #stringify_keys in TagHelper, add better documentation and testing for TagHelper. Closes #6394 [Bob Silva]
+
+* [DOCS] fix reference to ActionController::Macros::AutoComplete for #text_field_with_auto_complete. Closes #2578 [Jan Prill]
+
+* Make sure html_document is reset between integration test requests. [ctm]
+
+* Set session to an empty hash if :new_session => false and no session cookie or param is present. CGI::Session was raising an unrescued ArgumentError. [Josh Susser]
+
+* Fix assert_redirected_to bug where redirecting from a nested to to a top-level controller incorrectly added the current controller's nesting. Closes #6128. [Rick Olson]
+
+* Ensure render :json => ... skips the layout. #6808 [Josh Peek]
+
+* Silence log_error deprecation warnings from inspecting deprecated instance variables. [Nate Wiger]
+
+* Only cache GET requests with a 200 OK response. #6514, #6743 [RSL, anamba]
+
+* Correctly report which filter halted the chain. #6699 [Martin Emde]
+
+* respond_to recognizes JSON. render :json => @person.to_json automatically sets the content type and takes a :callback option to specify a client-side function to call using the rendered JSON as an argument. #4185 [Scott Raymond, eventualbuddha]
+ # application/json response with body 'Element.show({:name: "David"})'
+ respond_to do |format|
+ format.json { render :json => { :name => "David" }.to_json, :callback => 'Element.show' }
+ end
+
+* Makes :discard_year work without breaking multi-attribute parsing in AR. #1260, #3800 [sean@ardismg.com, jmartin@desertflood.com, stephen@touset.org, Bob Silva]
+
+* Adds html id attribute to date helper elements. #1050, #1382 [mortonda@dgrmm.net, David North, Bob Silva]
+
+* Add :index and @auto_index capability to model driven date/time selects. #847, #2655 [moriq, Doug Fales, Bob Silva]
+
+* Add :order to datetime_select, select_datetime, and select_date. #1427 [Timothee Peignier, patrick@lenz.sh, Bob Silva]
+
+* Added time_select to work with time values in models. Update scaffolding. #2489, #2833 [Justin Palmer, Andre Caum, Bob Silva]
+
+* Added :include_seconds to select_datetime, datetime_select and time_select. #2998 [csn, Bob Silva]
+
+* All date/datetime selects can now accept an array of month names with :use_month_names. Allows for localization. #363 [tomasj, Bob Silva]
+
+* Adds :time_separator to select_time and :date_separator to select_datetime. Preserves BC. #3811 [Bob Silva]
+
+* @response.redirect_url works with 201 Created responses: just return headers['Location'] rather than checking the response status. [Jeremy Kemper]
+
+* Fixed that HEAD should return the proper Content-Length header (that is, actually use @body.size, not just 0) [DHH]
+
+* Added GET-masquarading for HEAD, so request.method will return :get even for HEADs. This will help anyone relying on case request.method to automatically work with HEAD and map.resources will also allow HEADs to all GET actions. Rails automatically throws away the response content in a reply to HEAD, so you don't even need to worry about that. If you, for whatever reason, still need to distinguish between GET and HEAD in some edge case, you can use Request#head? and even Request.headers["REQUEST_METHOD"] for get the "real" answer. Closes #6694 [DHH]
+
+
+*1.13.0 RC1* (r5619, November 22nd, 2006)
+
+* Update Routing to complain when :controller is not specified by a route. Closes #6669. [Nicholas Seckar]
+
+* Ensure render_to_string cleans up after itself when an exception is raised. #6658 [rsanheim]
+
+* Update to Prototype and script.aculo.us [5579]. [Sam Stephenson, Thomas Fuchs]
+
+* simple_format helper doesn't choke on nil. #6644 [jerry426]
+
+* Reuse named route helper module between Routing reloads. Use remove_method to delete named route methods after each load. Since the module is never collected, this fixes a significant memory leak. [Nicholas Seckar]
+
+* Deprecate standalone components. [Jeremy Kemper]
+
+* Always clear model associations from session. #4795 [sd@notso.net, andylien@gmail.com]
+
+* Remove JavaScriptLiteral in favor of ActiveSupport::JSON::Variable. [Sam Stephenson]
+
+* Sync ActionController::StatusCodes::STATUS_CODES with http://www.iana.org/assignments/http-status-codes. #6586 [dkubb]
+
+* Multipart form values may have a content type without being treated as uploaded files if they do not provide a filename. #6401 [Andreas Schwarz, Jeremy Kemper]
+
+* assert_response supports symbolic status codes. #6569 [Kevin Clark]
+ assert_response :ok
+ assert_response :not_found
+ assert_response :forbidden
+
+* Cache parsed query parameters. #6559 [Stefan Kaes]
+
+* Deprecate JavaScriptHelper#update_element_function, which is superseeded by RJS [Thomas Fuchs]
+
+* Fix invalid test fixture exposed by stricter Ruby 1.8.5 multipart parsing. #6524 [Bob Silva]
+
+* Set ActionView::Base.default_form_builder once rather than passing the :builder option to every form or overriding the form helper methods. [Jeremy Kemper]
+
+* Deprecate expire_matched_fragments. Use expire_fragment instead. #6535 [Bob Silva]
+
+* Deprecate start_form_tag and end_form_tag. Use form_tag / '' from now on. [Rick]
+
+* Added block-usage to PrototypeHelper#form_remote_tag, document block-usage of FormTagHelper#form_tag [Rick]
+
+* Add a 0 margin/padding div around the hidden _method input tag that form_tag outputs. [Rick]
+
+* Added block-usage to TagHelper#content_tag [DHH]. Example:
+
+ <% content_tag :div, :class => "strong" %>
+ Hello world!
+ <% end %>
+
+ Will output:
+
Hello world!
+
+* Deprecated UrlHelper#link_to_image and UrlHelper#link_to :post => true #6409 [BobSilva]
+
+* Upgraded NumberHelper with number_to_phone support international formats to comply with ITU E.123 by supporting area codes with less than 3 digits, added precision argument to number_to_human_size (defaults to 1) #6421 [BobSilva]
+
+* Fixed that setting RAILS_ASSET_ID to "" should not add a trailing slash after assets #6454 [BobSilva/chrismear]
+
+* Force *_url named routes to show the host in ActionView [Rick]
+
+ <%= url_for ... %> # no host
+ <%= foo_path %> # no host
+ <%= foo_url %> # host!
+
+* Add support for converting blocks into function arguments to JavaScriptGenerator#call and JavaScriptProxy#call. [Sam Stephenson]
+
+* Add JavaScriptGenerator#literal for wrapping a string in an object whose #to_json is the string itself. [Sam Stephenson]
+
+* Add <%= escape_once html %> to escape html while leaving any currently escaped entities alone. Fix button_to double-escaping issue. [Rick]
+
+* Fix double-escaped entities, such as &, {, etc. [Rick]
+
+* Fix routing to correctly determine when generation fails. Closes #6300. [psross].
+
+* Fix broken assert_generates when extra keys are being checked. [Jamis Buck]
+
+* Replace KCODE checks with String#chars for truncate. Closes #6385 [Manfred Stienstra]
+
+* Make page caching respect the format of the resource that is being requested even if the current route is the default route so that, e.g. posts.rss is not transformed by url_for to '/' and subsequently cached as '/index.html' when it should be cached as '/posts.rss'. [Marcel Molina Jr.]
+
+* Use String#chars in TextHelper::excerpt. Closes #6386 [Manfred Stienstra]
+
+* Fix relative URL root matching problems. [Mark Imbriaco]
+
+* Fix filter skipping in controller subclasses. #5949, #6297, #6299 [Martin Emde]
+
+* render_text may optionally append to the response body. render_javascript appends by default. This allows you to chain multiple render :update calls by setting @performed_render = false between them (awaiting a better public API). [Jeremy Kemper]
+
+* Rename test assertion to prevent shadowing. Closes #6306. [psross]
+
+* Fixed that NumberHelper#number_to_delimiter should respect precision of higher than two digits #6231 [phallstrom]
+
+* Fixed that FormHelper#radio_button didn't respect an :id being passed in #6266 [evansj]
+
+* Added an html_options hash parameter to javascript_tag() and update_page_tag() helpers #6311 [tzaharia]. Example:
+
+ update_page_tag :defer => 'true' { |page| ... }
+
+ Gives:
+
+
+
+ Which is needed for dealing with the IE6 DOM when it's not yet fully loaded.
+
+* Fixed that rescue template path shouldn't be hardcoded, then it's easier to hook in your own #6295 [mnaberez]
+
+* Fixed escaping of backslashes in JavaScriptHelper#escape_javascript #6302 [sven@c3d2.de]
+
+* Fixed that some 500 rescues would cause 500's themselves because the response had not yet been generated #6329 [cmselmer]
+
+* respond_to :html doesn't assume .rhtml. #6281 [Hampton Catlin]
+
+* Fixed some deprecation warnings in ActionPack [Rick Olson]
+
+* assert_select_rjs decodes escaped unicode chars since the Javascript generators encode them. #6240 [japgolly]
+
+* Deprecation: @cookies, @headers, @request, @response will be removed after 1.2. Use the corresponding method instead. [Jeremy Kemper]
+
+* Make the :status parameter expand to the default message for that status code if it is an integer. Also support symbol statuses. [Jamis Buck]. Examples:
+
+ head :status => 404 # expands to "404 Not Found"
+ head :status => :not_found # expands to "404 Not Found"
+ head :status => :created # expands to "201 Created"
+
+* Add head(options = {}) for responses that have no body. [Jamis Buck]. Examples:
+
+ head :status => 404 # return an empty response with a 404 status
+ head :location => person_path(@person), :status => 201
+
+* Fix bug that kept any before_filter except the first one from being able to halt the before_filter chain. [Rick Olson]
+
+* strip_links is case-insensitive. #6285 [tagoh, Bob Silva]
+
+* Clear the cache of possible controllers whenever Routes are reloaded. [Nicholas Seckar]
+
+* Filters overhaul including meantime filter support using around filters + blocks. #5949 [Martin Emde, Roman Le Negrate, Stefan Kaes, Jeremy Kemper]
+
+* Update CGI process to allow sessions to contain namespaced models. Closes #4638. [dfelstead@site5.com]
+
+* Fix routing to respect user provided requirements and defaults when assigning default routing options (such as :action => 'index'). Closes #5950. [Nicholas Seckar]
+
+* Rescue Errno::ECONNRESET to handle an unexpectedly closed socket connection. Improves SCGI reliability. #3368, #6226 [sdsykes, fhanshaw@vesaria.com]
+
+* Added that respond_to blocks will automatically set the content type to be the same as is requested [DHH]. Examples:
+
+ respond_to do |format|
+ format.html { render :text => "I'm being sent as text/html" }
+ format.rss { render :text => "I'm being sent as application/rss+xml" }
+ format.atom { render :text => "I'm being sent as application/xml", :content_type => Mime::XML }
+ end
+
+* Added utf-8 as the default charset for all renders. You can change this default using ActionController::Base.default_charset=(encoding) [DHH]
+
+* Added proper getters and setters for content type and charset [DHH]. Example of what we used to do:
+
+ response.headers["Content-Type"] = "application/atom+xml; charset=utf-8"
+
+ ...now:
+
+ response.content_type = Mime::ATOM
+ response.charset = "utf-8"
+
+* Declare file extensions exempt from layouts. #6219 [brandon]
+ Example: ActionController::Base.exempt_from_layout 'rpdf'
+
+* Add chained replace/update support for assert_select_rjs [Rick Olson]
+
+ Given RJS like...
+
+ page['test1'].replace "
foo
"
+ page['test2'].replace_html "
foo
"
+
+ Test it with...
+
+ assert_select_rjs :chained_replace
+ assert_select_rjs :chained_replace, "test1"
+
+ assert_select_rjs :chained_replace_html
+ assert_select_rjs :chained_replace_html, "test2"
+
+* Load helpers in alphabetical order for consistency. Resolve cyclic javascript_helper dependency. #6132, #6178 [choonkeat@gmail.com]
+
+* Skip params with empty names, such as the &=Save query string from . #2569 [manfred, raphinou@yahoo.com]
+
+* Fix assert_tag so that :content => "foo" does not match substrings, but only exact strings. Use :content => /foo/ to match substrings. #2799 [Eric Hodel]
+
+* Update JavaScriptGenerator#show/hide/toggle/remove to new Prototype syntax for multiple ids, #6068 [petermichaux@gmail.com]
+
+* Update UrlWriter to support :only_path. [Nicholas Seckar, Dave Thomas]
+
+* Fixed JavaScriptHelper#link_to_function and JavaScriptHelper#button_to_function to have the script argument be optional [DHH]. So what used to require a nil, like this:
+
+ link_to("Hider", nil, :class => "hider_link") { |p| p[:something].hide }
+
+ ...can be written like this:
+
+ link_to("Hider", :class => "hider_link") { |p| p[:something].hide }
+
+* Added access to nested attributes in RJS #4548 [richcollins@gmail.com]. Examples:
+
+ page['foo']['style'] # => $('foo').style;
+ page['foo']['style']['color'] # => $('blank_slate').style.color;
+ page['foo']['style']['color'] = 'red' # => $('blank_slate').style.color = 'red';
+ page['foo']['style'].color = 'red' # => $('blank_slate').style.color = 'red';
+
+* Fixed that AssetTagHelper#image_tag and others using compute_public_path should not modify the incoming source argument (closes #5102) [eule@space.ch]
+
+* Deprecated the auto-appending of .png to AssetTagHelper#image_tag calls that doesn't have an extension [DHH]
+
+* Fixed FormOptionsHelper#select to respect :selected value #5813
+
+* Fixed TextHelper#simple_format to deal with multiple single returns within a single paragraph #5835 [moriq@moriq.com]
+
+* Fixed TextHelper#pluralize to handle 1 as a string #5909 [rails@bencurtis.com]
+
+* Improved resolution of DateHelper#distance_of_time_in_words for better precision #5994 [Bob Silva]
+
+* Changed that uncaught exceptions raised any where in the application will cause RAILS_ROOT/public/500.html to be read and shown instead of just the static "Application error (Rails)" [DHH]
+
+* Added deprecation language for pagination which will become a plugin by Rails 2.0 [DHH]
+
+* Added deprecation language for in_place_editor and auto_complete_field that both pieces will become plugins by Rails 2.0 [DHH]
+
+* Deprecated all of ActionController::Dependencies. All dependency loading is now handled from Active Support [DHH]
+
+* Added assert_select* for CSS selector-based testing (deprecates assert_tag) #5936 [assaf.arkin@gmail.com]
+
+* radio_button_tag generates unique id attributes. #3353 [Bob Silva, somekool@gmail.com]
+
+* strip_tags passes through blank args such as nil or "". #2229, #6702 [duncan@whomwah.com, dharana]
+
+* Cleanup assert_tag :children counting. #2181 [jamie@bravenet.com]
+
+* button_to accepts :method so you can PUT and DELETE with it. #6005 [Dan Webb]
+
+* Update sanitize text helper to strip plaintext tags, and . [Rick Olson]
+
+* Add routing tests to assert that RoutingError is raised when conditions aren't met. Closes #6016 [Nathan Witmer]
+
+* Make auto_link parse a greater subset of valid url formats. [Jamis Buck]
+
+* Integration tests: headers beginning with X aren't excluded from the HTTP_ prefix, so X-Requested-With becomes HTTP_X_REQUESTED_WITH as expected. [Mike Clark]
+
+* Switch to using FormEncodedPairParser for parsing request parameters. [Nicholas Seckar, DHH]
+
+* respond_to .html now always renders #{action_name}.rhtml so that registered custom template handlers do not override it in priority. Custom mime types require a block and throw proper error now. [Tobias Luetke]
+
+* Deprecation: test deprecated instance vars in partials. [Jeremy Kemper]
+
+* Add UrlWriter to allow writing urls from Mailers and scripts. [Nicholas Seckar]
+
+* Relax Routing's anchor pattern warning; it was preventing use of [^/] inside restrictions. [Nicholas Seckar]
+
+* Add controller_paths variable to Routing. [Nicholas Seckar]
+
+* Fix assert_redirected_to issue with named routes for module controllers. [Rick Olson]
+
+* Tweak RoutingError message to show option diffs, not just missing named route significant keys. [Rick Olson]
+
+* Invoke method_missing directly on hidden actions. Closes #3030. [Nicholas Seckar]
+
+* Add RoutingError exception when RouteSet fails to generate a path from a Named Route. [Rick Olson]
+
+* Replace Reloadable with Reloadable::Deprecated. [Nicholas Seckar]
+
+* Deprecation: check whether instance variables have been monkeyed with before assigning them to deprecation proxies. Raises a RuntimeError if so. [Jeremy Kemper]
+
+* Add support for the param_name parameter to the auto_complete_field helper. #5026 [david.a.williams@gmail.com]
+
+* Deprecation! @params, @session, @flash will be removed after 1.2. Use the corresponding instance methods instead. You'll get printed warnings during tests and logged warnings in dev mode when you access either instance variable directly. [Jeremy Kemper]
+
+* Make Routing noisy when an anchor regexp is assigned to a segment. #5674 [francois.beausoleil@gmail.com]
+
+* Added months and years to the resolution of DateHelper#distance_of_time_in_words, such that "60 days ago" becomes "2 months ago" #5611 [pjhyett@gmail.com]
+
+* Make controller_path available as an instance method. #5724 [jmckible@gmail.com]
+
+* Update query parser to support adjacent hashes. [Nicholas Seckar]
+
+* Make action caching aware of different formats for the same action so that, e.g. foo.xml is cached separately from foo.html. Implicitly set content type when reading in cached content with mime revealing extensions so the entire onous isn't on the webserver. [Marcel Molina Jr.]
+
+* Restrict Request Method hacking with ?_method to POST requests. [Rick Olson]
+
+* Fixed the new_#{resource}_url route and added named route tests for Simply Restful. [Rick Olson]
+
+* Added map.resources from the Simply Restful plugin [DHH]. Examples (the API has changed to use plurals!):
+
+ map.resources :messages
+ map.resources :messages, :comments
+ map.resources :messages, :new => { :preview => :post }
+
+* Fixed that integration simulation of XHRs should set Accept header as well [Edward Frederick]
+
+* TestRequest#reset_session should restore a TestSession, not a hash [Koz]
+
+* Don't search a load-path of '.' for controller files [Jamis Buck]
+
+* Update integration.rb to require test_process explicitly instead of via Dependencies. [Nicholas Seckar]
+
+* Fixed that you can still access the flash after the flash has been reset in reset_session. Closes #5584 [lmarlow@yahoo.com]
+
+* Allow form_for and fields_for to work with indexed form inputs. [Jeremy Kemper, Matt Lyon]
+
+ <% form_for 'post[]', @post do |f| -%>
+ <% end -%>
+
+* Remove leak in development mode by replacing define_method with module_eval. [Nicholas Seckar]
+
+* Provide support for decimal columns to form helpers. Closes #5672. [dave@pragprog.com]
+
+* Pass :id => nil or :class => nil to error_messages_for to supress that html attribute. #3586 [olivier_ansaldi@yahoo.com, sebastien@goetzilla.info]
+
+* Reset @html_document between requests so assert_tag works. #4810 [jarkko@jlaine.net, easleydp@gmail.com]
+
+* Integration tests behave well with render_component. #4632 [edward.frederick@revolution.com, dev.rubyonrails@maxdunn.com]
+
+* Added exception handling of missing layouts #5373 [chris@ozmm.org]
+
+* Fixed that real files and symlinks should be treated the same when compiling templates #5438 [zachary@panandscan.com]
+
+* Fixed that the flash should be reset when reset_session is called #5584 [shugo@ruby-lang.org]
+
+* Added special case for "1 Byte" in NumberHelper#number_to_human_size #5593 [murpyh@rubychan.de]
+
+* Fixed proper form-encoded parameter parsing for requests with "Content-Type: application/x-www-form-urlencoded; charset=utf-8" (note the presence of a charset directive) [DHH]
+
+* Add route_name_path method to generate only the path for a named routes. For example, map.person will add person_path. [Nicholas Seckar]
+
+* Avoid naming collision among compiled view methods. [Jeremy Kemper]
+
+* Fix CGI extensions when they expect string but get nil in Windows. Closes #5276 [mislav@nippur.irb.hr]
+
+* Determine the correct template_root for deeply nested components. #2841 [s.brink@web.de]
+
+* Fix that routes with *path segments in the recall can generate URLs. [Rick]
+
+* Fix strip_links so that it doesn't hang on multiline tags [Jamis Buck]
+
+* Remove problematic control chars in rescue template. #5316 [Stefan Kaes]
+
+* Make sure passed routing options are not mutated by routing code. #5314 [Blair Zajac]
+
+* Make sure changing the controller from foo/bar to bing/bang does not change relative to foo. [Jamis Buck]
+
+* Escape the path before routing recognition. #3671
+
+* Make sure :id and friends are unescaped properly. #5275 [me@julik.nl]
+
+* Rewind readable CGI params so others may reread them (such as CGI::Session when passing the session id in a multipart form). #210 [mklame@atxeu.com, matthew@walker.wattle.id.au]
+
+* Added Mime::TEXT (text/plain) and Mime::ICS (text/calendar) as new default types [DHH]
+
+* Added Mime::Type.register(string, symbol, synonyms = []) for adding new custom mime types [DHH]. Example: Mime::Type.register("image/gif", :gif)
+
+* Added support for Mime objects in render :content_type option [DHH]. Example: render :text => some_atom, :content_type => Mime::ATOM
+
+* Add :status option to send_data and send_file. Defaults to '200 OK'. #5243 [Manfred Stienstra ]
+
+* Routing rewrite. Simpler, faster, easier to understand. The published API for config/routes.rb is unchanged, but nearly everything else is different, so expect breakage in plugins and libs that try to fiddle with routes. [Nicholas Seckar, Jamis Buck]
+
+ map.connect '/foo/:id', :controller => '...', :action => '...'
+ map.connect '/foo/:id.:format', :controller => '...', :action => '...'
+ map.connect '/foo/:id', ..., :conditions => { :method => :get }
+
+* Cope with missing content type and length headers. Parse parameters from multipart and urlencoded request bodies only. [Jeremy Kemper]
+
+* Accept multipart PUT parameters. #5235 [guy.naor@famundo.com]
+
+* Added interrogation of params[:format] to determine Accept type. If :format is specified and matches a declared extension, like "rss" or "xml", that mime type will be put in front of the accept handler. This means you can link to the same action from different extensions and use that fact to determine output [DHH]. Example:
+
+ class WeblogController < ActionController::Base
+ def index
+ @posts = Post.find :all
+
+ respond_to do |format|
+ format.html
+ format.xml { render :xml => @posts.to_xml }
+ format.rss { render :action => "feed.rxml" }
+ end
+ end
+ end
+
+ # returns HTML when requested by a browser, since the browser
+ # has the HTML mimetype at the top of its priority list
+ Accept: text/html
+ GET /weblog
+
+ # returns the XML
+ Accept: application/xml
+ GET /weblog
+
+ # returns the HTML
+ Accept: application/xml
+ GET /weblog.html
+
+ # returns the XML
+ Accept: text/html
+ GET /weblog.xml
+
+ All this relies on the fact that you have a route that includes .:format.
+
+* Expanded :method option in FormTagHelper#form_tag, FormHelper#form_for, PrototypeHelper#remote_form_for, PrototypeHelper#remote_form_tag, and PrototypeHelper#link_to_remote to allow for verbs other than GET and POST by automatically creating a hidden form field named _method, which will simulate the other verbs over post [DHH]
+
+* Added :method option to UrlHelper#link_to, which allows for using other verbs than GET for the link. This replaces the :post option, which is now deprecated. Example: link_to "Destroy", person_url(:id => person), :method => :delete [DHH]
+
+* follow_redirect doesn't complain about being redirected to the same controller. #5153 [dymo@mk.ukrtelecom.ua]
+
+* Add layout attribute to response object with the name of the layout that was rendered, or nil if none rendered. [Kevin Clark kevin.clark@gmail.com]
+
+* Fix NoMethodError when parsing params like &&. [Adam Greenfield]
+
+* form.text_area handles the :size option just like the original text_area (:size => '60x10' becomes cols="60" rows="10"). [Jeremy Kemper]
+
+* Excise ingrown code from FormOptionsHelper#options_for_select. #5008 [anonymous]
+
+* Small fix in routing to allow dynamic routes (broken after [4242]) [Rick]
+
+ map.connect '*path', :controller => 'files', :action => 'show'
+
+* Use #flush between switching from #write to #syswrite. Closes #4907. [Blair Zajac ]
+
+* Allow error_messages_for to report errors for multiple objects, as well as support for customizing the name of the object in the error summary header. Closes #4186. [andrew@redlinesoftware.com, Marcel Molina Jr.]
+
+ error_messages_for :account, :user, :subscription, :object_name => :account
+
+* Fix assert_redirected_to tests according to real-world usage. Also, don't fail if you add an extra :controller option: [Rick]
+
+ redirect_to :action => 'new'
+ assert_redirected_to :controller => 'monkeys', :action => 'new'
+
+* Diff compared routing options. Allow #assert_recognizes to take a second arg as a hash to specify optional request method [Rick]
+
+ assert_recognizes({:controller => 'users', :action => 'index'}, 'users')
+ assert_recognizes({:controller => 'users', :action => 'create'}, {:path => 'users', :method => :post})
+
+* Diff compared options with #assert_redirected_to [Rick]
+
+* Add support in routes for semicolon delimited "subpaths", like /books/:id;:action [Jamis Buck]
+
+* Change link_to_function and button_to_function to (optionally) take an update_page block instead of a JavaScript string. Closes #4804. [zraii@comcast.net, Sam Stephenson]
+
+* Modify routing so that you can say :require => { :method => :post } for a route, and the route will never be selected unless the request method is POST. Only works for route recognition, not for route generation. [Jamis Buck]
+
+* Added :add_headers option to verify which merges a hash of name/value pairs into the response's headers hash if the prerequisites cannot be satisfied. [Sam Stephenson]
+ ex. verify :only => :speak, :method => :post,
+ :render => { :status => 405, :text => "Must be post" },
+ :add_headers => { "Allow" => "POST" }
+
+
*1.12.5* (August 10th, 2006)
* Updated security fix
@@ -5,24 +559,6 @@
*1.12.4* (August 8th, 2006)
-* Documentation fix: integration test scripts don't require integration_test. #4914 [Frederick Ros ]
-
-* ActionController::Base Summary documentation rewrite. #4900 [kevin.clark@gmail.com]
-
-* Fix text_helper.rb documentation rendering. #4725 [Frederick Ros]
-
-* Fixes bad rendering of JavaScriptMacrosHelper rdoc. #4910 [Frederick Ros]
-
-* Enhance documentation for setting headers in integration tests. Skip auto HTTP prepending when its already there. #4079 [Rick Olson]
-
-* Documentation for AbstractRequest. #4895 [kevin.clark@gmail.com]
-
-* Remove all remaining references to @params in the documentation. [Marcel Molina Jr.]
-
-* Add documentation for redirect_to :back's RedirectBackError exception. [Marcel Molina Jr.]
-
-* Update layout and content_for documentation to use yield rather than magic @content_for instance variables. [Marcel Molina Jr.]
-
* Cache CgiRequest#request_parameters so that multiple calls don't re-parse multipart data. [Rick]
* Fixed that remote_form_for can leave out the object parameter and default to the instance variable of the object_name, just like form_for [DHH]
@@ -1928,7 +2464,7 @@ Default YAML web services were retired, ActionController::Base.param_parsers car
Before:
module WeblogHelper
- def self.append_features(controller) #:nodoc:
+ def self.included(controller) #:nodoc:
controller.ancestors.include?(ActionController::Base) ? controller.add_template_helper(self) : super
end
end
@@ -2286,9 +2822,9 @@ Default YAML web services were retired, ActionController::Base.param_parsers car
* Added pluralize method to the TextHelper that makes it easy to get strings like "1 message", "3 messages"
-* Added proper escaping for the rescues [Andreas Schwartz]
+* Added proper escaping for the rescues [Andreas Schwarz]
-* Added proper escaping for the option and collection tags [Andreas Schwartz]
+* Added proper escaping for the option and collection tags [Andreas Schwarz]
* Fixed NaN errors on benchmarking [Jim Weirich]
diff --git a/vendor/rails/actionpack/MIT-LICENSE b/vendor/rails/actionpack/MIT-LICENSE
index 26f55e77..5856add6 100644
--- a/vendor/rails/actionpack/MIT-LICENSE
+++ b/vendor/rails/actionpack/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2004 David Heinemeier Hansson
+Copyright (c) 2004-2006 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/vendor/rails/actionpack/README b/vendor/rails/actionpack/README
index dc475a66..a700742c 100755
--- a/vendor/rails/actionpack/README
+++ b/vendor/rails/actionpack/README
@@ -34,7 +34,7 @@ A short rundown of the major features:
and can therefore share helper methods.
BlogController < ActionController::Base
- def display
+ def show
@customer = find_customer
end
@@ -100,7 +100,7 @@ A short rundown of the major features:
after_filter { |c| c.response.body = GZip::compress(c.response.body) }
after_filter LocalizeFilter
- def list
+ def index
# Before this action is run, the user will be authenticated, the cache
# will be examined to see if a valid copy of the results already
# exists, and the action will be logged for auditing.
@@ -139,7 +139,7 @@ A short rundown of the major features:
end
Layout file (called weblog_layout):
- <%= @content_for_layout %>
+ <%= yield %>
Template for hello_world action:
Hello world
@@ -155,7 +155,7 @@ A short rundown of the major features:
map.connect 'clients/:client_name/:project_name/:controller/:action'
Accessing /clients/37signals/basecamp/project/dash calls ProjectController#dash with
- { "client_name" => "37signals", "project_name" => "basecamp" } in @params["params"]
+ { "client_name" => "37signals", "project_name" => "basecamp" } in params[:params]
From that URL, you can rewrite the redirect in a number of ways:
@@ -296,9 +296,8 @@ A short rundown of the major features:
{Learn more}[link:classes/ActionController/Rescue.html]
-* Scaffolding for Action Record model objects
+* Scaffolding for Active Record model objects
- require 'account' # must be an Active Record class
class AccountController < ActionController::Base
scaffold :account
end
@@ -306,7 +305,7 @@ A short rundown of the major features:
The AccountController now has the full CRUD range of actions and default
templates: list, show, destroy, new, create, edit, update
- {Learn more}link:classes/ActionController/Scaffolding/ClassMethods.html
+ {Learn more}[link:classes/ActionController/Scaffolding/ClassMethods.html]
* Form building for Active Record model objects
@@ -338,10 +337,10 @@ A short rundown of the major features:
- This form generates a @params["post"] array that can be used directly in a save action:
+ This form generates a params[:post] array that can be used directly in a save action:
class WeblogController < ActionController::Base
- def save
+ def create
post = Post.create(params[:post])
redirect_to :action => "display", :id => post.id
end
@@ -350,10 +349,10 @@ A short rundown of the major features:
{Learn more}[link:classes/ActionView/Helpers/ActiveRecordHelper.html]
-* Runs on top of WEBrick, CGI, FCGI, and mod_ruby
+* Runs on top of WEBrick, Mongrel, CGI, FCGI, and mod_ruby
-== Simple example
+== Simple example (from outside of Rails)
This example will implement a simple weblog system using inline templates and
an Active Record model. So let's build that WeblogController with just a few
@@ -366,11 +365,11 @@ methods:
layout "weblog/layout"
def index
- @posts = Post.find_all
+ @posts = Post.find(:all)
end
def display
- @post = Post.find(:params[:id])
+ @post = Post.find(params[:id])
end
def new
@@ -394,7 +393,7 @@ And the templates look like this:
weblog/layout.rhtml:
- <%= @content_for_layout %>
+ <%= yield %>
weblog/index.rhtml:
@@ -431,6 +430,8 @@ template casing from content.
Please note that you might need to change the "shebang" line to
#!/usr/local/env ruby, if your Ruby is not placed in /usr/local/bin/ruby
+Also note that these examples are all for demonstrating using Action Pack on
+its own. Not for when it's used inside of Rails.
== Download
@@ -440,7 +441,7 @@ The latest version of Action Pack can be found at
Documentation can be found at
-* http://ap.rubyonrails.com
+* http://api.rubyonrails.com
== Installation
@@ -459,13 +460,10 @@ Action Pack is released under the MIT license.
== Support
-The Action Pack homepage is http://www.rubyonrails.com. You can find
+The Action Pack homepage is http://www.rubyonrails.org. You can find
the Action Pack RubyForge page at http://rubyforge.org/projects/actionpack.
And as Jim from Rake says:
Feel free to submit commits or feature requests. If you send a patch,
remember to update the corresponding unit tests. If fact, I prefer
- new feature to be submitted in the form of new unit tests.
-
-For other information, feel free to ask on the ruby-talk mailing list (which
-is mirrored to comp.lang.ruby) or contact mailto:david@loudthinking.com.
+ new feature to be submitted in the form of new unit tests.
\ No newline at end of file
diff --git a/vendor/rails/actionpack/Rakefile b/vendor/rails/actionpack/Rakefile
index 56aacf26..4f5b47b6 100755
--- a/vendor/rails/actionpack/Rakefile
+++ b/vendor/rails/actionpack/Rakefile
@@ -22,11 +22,14 @@ task :default => [ :test ]
# Run the unit tests
-Rake::TestTask.new { |t|
+desc "Run all unit tests"
+task :test => [:test_action_pack, :test_active_record_integration]
+
+Rake::TestTask.new(:test_action_pack) { |t|
t.libs << "test"
# make sure we include the controller tests (c*) first as on some systems
# this will not happen automatically and the tests (as a whole) will error
- t.test_files=Dir.glob( "test/c*/*_test.rb" ) + Dir.glob( "test/[ft]*/*_test.rb" )
+ t.test_files=Dir.glob( "test/c*/**/*_test.rb" ) + Dir.glob( "test/[ft]*/*_test.rb" )
# t.pattern = 'test/*/*_test.rb'
t.verbose = true
}
@@ -72,12 +75,12 @@ spec = Gem::Specification.new do |s|
s.has_rdoc = true
s.requirements << 'none'
- s.add_dependency('activesupport', '= 1.3.1' + PKG_BUILD)
+ s.add_dependency('activesupport', '= 1.4.1' + PKG_BUILD)
s.require_path = 'lib'
s.autorequire = 'action_controller'
- s.files = [ "Rakefile", "install.rb", "filler.txt", "README", "RUNNING_UNIT_TESTS", "CHANGELOG", "MIT-LICENSE", "examples/.htaccess" ]
+ s.files = [ "Rakefile", "install.rb", "README", "RUNNING_UNIT_TESTS", "CHANGELOG", "MIT-LICENSE", "examples/.htaccess" ]
dist_dirs.each do |dir|
s.files = s.files + Dir.glob( "#{dir}/**/*" ).delete_if { |item| item.include?( "\.svn" ) }
end
diff --git a/vendor/rails/actionpack/examples/address_book_controller.rb b/vendor/rails/actionpack/examples/address_book_controller.rb
index 01d498e1..9ca66125 100644
--- a/vendor/rails/actionpack/examples/address_book_controller.rb
+++ b/vendor/rails/actionpack/examples/address_book_controller.rb
@@ -28,11 +28,11 @@ class AddressBookController < ActionController::Base
end
def person
- @person = @address_book.find_person(@params["id"])
+ @person = @address_book.find_person(params[:id])
end
def create_person
- @address_book.create_person(@params["person"])
+ @address_book.create_person(params[:person])
redirect_to :action => "index"
end
@@ -49,4 +49,4 @@ begin
AddressBookController.process_cgi(CGI.new) if $0 == __FILE__
rescue => e
CGI.new.out { "#{e.class}: #{e.message}" }
-end
\ No newline at end of file
+end
diff --git a/vendor/rails/actionpack/examples/blog_controller.cgi b/vendor/rails/actionpack/examples/blog_controller.cgi
index e64fe85f..3868c306 100755
--- a/vendor/rails/actionpack/examples/blog_controller.cgi
+++ b/vendor/rails/actionpack/examples/blog_controller.cgi
@@ -14,7 +14,7 @@ class BlogController < ActionController::Base
render_template <<-"EOF"
- <%= @flash["alert"] %>
+ <%= flash["alert"] %>
Posts
<% @posts.each do |post| %>
<%= post.title %> <%= post.body %>
@@ -32,7 +32,7 @@ class BlogController < ActionController::Base
end
def create
- @session["posts"].unshift(Post.new(@params["post"]["title"], @params["post"]["body"]))
+ @session["posts"].unshift(Post.new(params[:post][:title], params[:post][:body]))
flash["alert"] = "New post added!"
redirect_to :action => "index"
end
@@ -50,4 +50,4 @@ begin
BlogController.process_cgi(CGI.new) if $0 == __FILE__
rescue => e
CGI.new.out { "#{e.class}: #{e.message}" }
-end
\ No newline at end of file
+end
diff --git a/vendor/rails/actionpack/examples/debate_controller.cgi b/vendor/rails/actionpack/examples/debate_controller.cgi
index b82ac625..dbe02256 100755
--- a/vendor/rails/actionpack/examples/debate_controller.cgi
+++ b/vendor/rails/actionpack/examples/debate_controller.cgi
@@ -25,19 +25,19 @@ class DebateController < ActionController::Base
end
def topic
- @topic = @debate.find_topic(@params["id"])
+ @topic = @debate.find_topic(params[:id])
end
# def new_topic() end <-- This is not needed as the template doesn't require any assigns
def create_topic
- @debate.create_topic(@params["topic"])
+ @debate.create_topic(params[:topic])
redirect_to :action => "index"
end
def create_reply
- @debate.create_reply(@params["reply"])
- redirect_to :action => "topic", :path_params => { "id" => @params["reply"]["topic_id"] }
+ @debate.create_reply(params[:reply])
+ redirect_to :action => "topic", :path_params => { "id" => params[:reply][:topic_id] }
end
private
@@ -54,4 +54,4 @@ begin
DebateController.process_cgi(CGI.new) if $0 == __FILE__
rescue => e
CGI.new.out { "#{e.class}: #{e.message}" }
-end
\ No newline at end of file
+end
diff --git a/vendor/rails/actionpack/lib/action_controller.rb b/vendor/rails/actionpack/lib/action_controller.rb
index 593a2838..42307327 100755
--- a/vendor/rails/actionpack/lib/action_controller.rb
+++ b/vendor/rails/actionpack/lib/action_controller.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004 David Heinemeier Hansson
+# Copyright (c) 2004-2006 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -30,7 +30,7 @@ unless defined?(ActiveSupport)
require 'active_support'
rescue LoadError
require 'rubygems'
- require_gem 'activesupport'
+ gem 'activesupport'
end
end
@@ -43,7 +43,7 @@ require 'action_controller/benchmarking'
require 'action_controller/flash'
require 'action_controller/filters'
require 'action_controller/layout'
-require 'action_controller/dependencies'
+require 'action_controller/deprecated_dependencies'
require 'action_controller/mime_responds'
require 'action_controller/pagination'
require 'action_controller/scaffolding'
diff --git a/vendor/rails/actionpack/lib/action_controller/assertions.rb b/vendor/rails/actionpack/lib/action_controller/assertions.rb
index 3fc65d5b..f3d4558e 100644
--- a/vendor/rails/actionpack/lib/action_controller/assertions.rb
+++ b/vendor/rails/actionpack/lib/action_controller/assertions.rb
@@ -1,320 +1,82 @@
require 'test/unit'
require 'test/unit/assertions'
-require 'rexml/document'
-require File.dirname(__FILE__) + "/vendor/html-scanner/html/document"
-module Test #:nodoc:
- module Unit #:nodoc:
- # In addition to these specific assertions, you also have easy access to various collections that the regular test/unit assertions
- # can be used against. These collections are:
- #
- # * assigns: Instance variables assigned in the action that are available for the view.
- # * session: Objects being saved in the session.
- # * flash: The flash objects currently in the session.
- # * cookies: Cookies being sent to the user on this request.
- #
- # These collections can be used just like any other hash:
- #
- # assert_not_nil assigns(:person) # makes sure that a @person instance variable was set
- # assert_equal "Dave", cookies[:name] # makes sure that a cookie called :name was set as "Dave"
- # assert flash.empty? # makes sure that there's nothing in the flash
- #
- # For historic reasons, the assigns hash uses string-based keys. So assigns[:person] won't work, but assigns["person"] will. To
- # appease our yearning for symbols, though, an alternative accessor has been deviced using a method call instead of index referencing.
- # So assigns(:person) will work just like assigns["person"], but again, assigns[:person] will not work.
- #
- # On top of the collections, you have the complete url that a given action redirected to available in redirect_to_url.
- #
- # For redirects within the same controller, you can even call follow_redirect and the redirect will be followed, triggering another
- # action call which can then be asserted against.
- #
- # == Manipulating the request collections
- #
- # The collections described above link to the response, so you can test if what the actions were expected to do happened. But
- # sometimes you also want to manipulate these collections in the incoming request. This is really only relevant for sessions
- # and cookies, though. For sessions, you just do:
- #
- # @request.session[:key] = "value"
- #
- # For cookies, you need to manually create the cookie, like this:
- #
- # @request.cookies["key"] = CGI::Cookie.new("key", "value")
- #
- # == Testing named routes
- #
- # If you're using named routes, they can be easily tested using the original named routes methods straight in the test case.
- # Example:
- #
- # assert_redirected_to page_url(:title => 'foo')
- module Assertions
- # Asserts that the response is one of the following types:
- #
- # * :success: Status code was 200
- # * :redirect: Status code was in the 300-399 range
- # * :missing: Status code was 404
- # * :error: Status code was in the 500-599 range
- #
- # You can also pass an explicit status code number as the type, like assert_response(501)
- def assert_response(type, message = nil)
- clean_backtrace do
- if [ :success, :missing, :redirect, :error ].include?(type) && @response.send("#{type}?")
- assert_block("") { true } # to count the assertion
- elsif type.is_a?(Fixnum) && @response.response_code == type
- assert_block("") { true } # to count the assertion
- else
- assert_block(build_message(message, "Expected response to be a >, but was >", type, @response.response_code)) { false }
- end
- end
+module ActionController #:nodoc:
+ # In addition to these specific assertions, you also have easy access to various collections that the regular test/unit assertions
+ # can be used against. These collections are:
+ #
+ # * assigns: Instance variables assigned in the action that are available for the view.
+ # * session: Objects being saved in the session.
+ # * flash: The flash objects currently in the session.
+ # * cookies: Cookies being sent to the user on this request.
+ #
+ # These collections can be used just like any other hash:
+ #
+ # assert_not_nil assigns(:person) # makes sure that a @person instance variable was set
+ # assert_equal "Dave", cookies[:name] # makes sure that a cookie called :name was set as "Dave"
+ # assert flash.empty? # makes sure that there's nothing in the flash
+ #
+ # For historic reasons, the assigns hash uses string-based keys. So assigns[:person] won't work, but assigns["person"] will. To
+ # appease our yearning for symbols, though, an alternative accessor has been deviced using a method call instead of index referencing.
+ # So assigns(:person) will work just like assigns["person"], but again, assigns[:person] will not work.
+ #
+ # On top of the collections, you have the complete url that a given action redirected to available in redirect_to_url.
+ #
+ # For redirects within the same controller, you can even call follow_redirect and the redirect will be followed, triggering another
+ # action call which can then be asserted against.
+ #
+ # == Manipulating the request collections
+ #
+ # The collections described above link to the response, so you can test if what the actions were expected to do happened. But
+ # sometimes you also want to manipulate these collections in the incoming request. This is really only relevant for sessions
+ # and cookies, though. For sessions, you just do:
+ #
+ # @request.session[:key] = "value"
+ #
+ # For cookies, you need to manually create the cookie, like this:
+ #
+ # @request.cookies["key"] = CGI::Cookie.new("key", "value")
+ #
+ # == Testing named routes
+ #
+ # If you're using named routes, they can be easily tested using the original named routes methods straight in the test case.
+ # Example:
+ #
+ # assert_redirected_to page_url(:title => 'foo')
+ module Assertions
+ def self.included(klass)
+ klass.class_eval do
+ include ActionController::Assertions::ResponseAssertions
+ include ActionController::Assertions::SelectorAssertions
+ include ActionController::Assertions::RoutingAssertions
+ include ActionController::Assertions::TagAssertions
+ include ActionController::Assertions::DomAssertions
+ include ActionController::Assertions::ModelAssertions
+ include ActionController::Assertions::DeprecatedAssertions
end
+ end
- # 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.
- def assert_redirected_to(options = {}, message=nil)
- clean_backtrace do
- assert_response(:redirect, message)
-
- if options.is_a?(String)
- msg = build_message(message, "expected a redirect to >, found one to >", options, @response.redirect_url)
- url_regexp = %r{^(\w+://.*?(/|$|\?))(.*)$}
- eurl, epath, url, path = [options, @response.redirect_url].collect do |url|
- u, p = (url_regexp =~ url) ? [$1, $3] : [nil, url]
- [u, (p[0..0] == '/') ? p : '/' + p]
- end.flatten
-
- assert_equal(eurl, url, msg) if eurl && url
- assert_equal(epath, path, msg) if epath && path
- else
- @response_diff = options.diff(@response.redirected_to) if options.is_a?(Hash) && @response.redirected_to.is_a?(Hash)
- msg = build_message(message, "response is not a redirection to all of the options supplied (redirection is >)#{', difference: >' if @response_diff}",
- @response.redirected_to || @response.redirect_url, @response_diff)
-
- assert_block(msg) do
- if options.is_a?(Symbol)
- @response.redirected_to == options
- else
- options.keys.all? do |k|
- if k == :controller then options[k] == ActionController::Routing.controller_relative_to(@response.redirected_to[k], @controller.class.controller_path)
- else options[k] == (@response.redirected_to[k].respond_to?(:to_param) ? @response.redirected_to[k].to_param : @response.redirected_to[k] unless @response.redirected_to[k].nil?)
- end
- end
- end
- end
- end
- end
- end
-
- # Asserts that the request was rendered with the appropriate template file.
- def assert_template(expected = nil, message=nil)
- clean_backtrace do
- rendered = expected ? @response.rendered_file(!expected.include?('/')) : @response.rendered_file
- msg = build_message(message, "expecting > but rendering with >", expected, rendered)
- assert_block(msg) do
- if expected.nil?
- !@response.rendered_with_file?
- else
- expected == rendered
- end
- end
- end
- end
-
- # Asserts that the routing of the given path was handled correctly and that the parsed options match.
- def assert_recognizes(expected_options, path, extras={}, message=nil)
- clean_backtrace do
- path = "/#{path}" unless path[0..0] == '/'
- # Load routes.rb if it hasn't been loaded.
- ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
-
- # Assume given controller
- request = ActionController::TestRequest.new({}, {}, nil)
- request.path = path
- ActionController::Routing::Routes.recognize!(request)
-
- expected_options = expected_options.clone
- extras.each_key { |key| expected_options.delete key } unless extras.nil?
-
- expected_options.stringify_keys!
- msg = build_message(message, "The recognized options > did not match >",
- request.path_parameters, expected_options)
- assert_block(msg) { request.path_parameters == expected_options }
- end
- end
-
- # Asserts that the provided options can be used to generate the provided path.
- def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)
- clean_backtrace do
- expected_path = "/#{expected_path}" unless expected_path[0] == ?/
- # Load routes.rb if it hasn't been loaded.
- ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty?
-
- generated_path, extra_keys = ActionController::Routing::Routes.generate(options, extras)
- found_extras = options.reject {|k, v| ! extra_keys.include? k}
-
- msg = build_message(message, "found extras >, not >", found_extras, extras)
- assert_block(msg) { found_extras == extras }
-
- msg = build_message(message, "The generated path > did not match >", generated_path,
- expected_path)
- assert_block(msg) { expected_path == generated_path }
- end
- end
-
- # Asserts that path and options match both ways; in other words, the URL generated from
- # options is the same as path, and also that the options recognized from path are the same as options
- def assert_routing(path, options, defaults={}, extras={}, message=nil)
- assert_recognizes(options, path, extras, message)
-
- controller, default_controller = options[:controller], defaults[:controller]
- if controller && controller.include?(?/) && default_controller && default_controller.include?(?/)
- options[:controller] = "/#{controller}"
- end
-
- assert_generates(path, options, defaults, extras, message)
- end
-
- # Asserts that there is a tag/node/element in the body of the response
- # that meets all of the given conditions. The +conditions+ parameter must
- # be a hash of any of the following keys (all are optional):
- #
- # * :tag: the node type must match the corresponding value
- # * :attributes: a hash. The node's attributes must match the
- # corresponding values in the hash.
- # * :parent: a hash. The node's parent must match the
- # corresponding hash.
- # * :child: a hash. At least one of the node's immediate children
- # must meet the criteria described by the hash.
- # * :ancestor: a hash. At least one of the node's ancestors must
- # meet the criteria described by the hash.
- # * :descendant: a hash. At least one of the node's descendants
- # must meet the criteria described by the hash.
- # * :sibling: a hash. At least one of the node's siblings must
- # meet the criteria described by the hash.
- # * :after: a hash. The node must be after any sibling meeting
- # the criteria described by the hash, and at least one sibling must match.
- # * :before: a hash. The node must be before any sibling meeting
- # the criteria described by the hash, and at least one sibling must match.
- # * :children: a hash, for counting children of a node. Accepts
- # the keys:
- # * :count: either a number or a range which must equal (or
- # include) the number of children that match.
- # * :less_than: the number of matching children must be less
- # than this number.
- # * :greater_than: the number of matching children must be
- # greater than this number.
- # * :only: another hash consisting of the keys to use
- # to match on the children, and only matching children will be
- # counted.
- # * :content: the textual content of the node must match the
- # given value. This will not match HTML tags in the body of a
- # tag--only text.
- #
- # Conditions are matched using the following algorithm:
- #
- # * if the condition is a string, it must be a substring of the value.
- # * if the condition is a regexp, it must match the value.
- # * if the condition is a number, the value must match number.to_s.
- # * if the condition is +true+, the value must not be +nil+.
- # * if the condition is +false+ or +nil+, the value must be +nil+.
- #
- # Usage:
- #
- # # assert that there is a "span" tag
- # assert_tag :tag => "span"
- #
- # # assert that there is a "span" tag with id="x"
- # assert_tag :tag => "span", :attributes => { :id => "x" }
- #
- # # assert that there is a "span" tag using the short-hand
- # assert_tag :span
- #
- # # assert that there is a "span" tag with id="x" using the short-hand
- # assert_tag :span, :attributes => { :id => "x" }
- #
- # # assert that there is a "span" inside of a "div"
- # assert_tag :tag => "span", :parent => { :tag => "div" }
- #
- # # assert that there is a "span" somewhere inside a table
- # assert_tag :tag => "span", :ancestor => { :tag => "table" }
- #
- # # assert that there is a "span" with at least one "em" child
- # assert_tag :tag => "span", :child => { :tag => "em" }
- #
- # # assert that there is a "span" containing a (possibly nested)
- # # "strong" tag.
- # assert_tag :tag => "span", :descendant => { :tag => "strong" }
- #
- # # assert that there is a "span" containing between 2 and 4 "em" tags
- # # as immediate children
- # assert_tag :tag => "span",
- # :children => { :count => 2..4, :only => { :tag => "em" } }
- #
- # # get funky: assert that there is a "div", with an "ul" ancestor
- # # and an "li" parent (with "class" = "enum"), and containing a
- # # "span" descendant that contains text matching /hello world/
- # assert_tag :tag => "div",
- # :ancestor => { :tag => "ul" },
- # :parent => { :tag => "li",
- # :attributes => { :class => "enum" } },
- # :descendant => { :tag => "span",
- # :child => /hello world/ }
- #
- # Please noteYou must explicitly
- # close all of your tags to use these assertions.
- def assert_tag(*opts)
- clean_backtrace do
- opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
- tag = find_tag(opts)
- assert tag, "expected tag, but no tag found matching #{opts.inspect} in:\n#{@response.body.inspect}"
- end
- end
-
- # Identical to #assert_tag, but asserts that a matching tag does _not_
- # exist. (See #assert_tag for a full discussion of the syntax.)
- def assert_no_tag(*opts)
- clean_backtrace do
- opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
- tag = find_tag(opts)
- assert !tag, "expected no tag, but found tag matching #{opts.inspect} in:\n#{@response.body.inspect}"
- end
- end
-
- # test 2 html strings to be equivalent, i.e. identical up to reordering of attributes
- def assert_dom_equal(expected, actual, message="")
- clean_backtrace do
- expected_dom = HTML::Document.new(expected).root
- actual_dom = HTML::Document.new(actual).root
- full_message = build_message(message, "> expected to be == to\n>.", expected_dom.to_s, actual_dom.to_s)
- assert_block(full_message) { expected_dom == actual_dom }
- end
- end
-
- # negated form of +assert_dom_equivalent+
- def assert_dom_not_equal(expected, actual, message="")
- clean_backtrace do
- expected_dom = HTML::Document.new(expected).root
- actual_dom = HTML::Document.new(actual).root
- full_message = build_message(message, "> expected to be != to\n>.", expected_dom.to_s, actual_dom.to_s)
- assert_block(full_message) { expected_dom != actual_dom }
- end
- end
-
- # ensures that the passed record is valid by active record standards. returns the error messages if not
- def assert_valid(record)
- clean_backtrace do
- assert record.valid?, record.errors.full_messages.join("\n")
- end
- end
-
- def clean_backtrace(&block)
- yield
- rescue AssertionFailedError => e
- path = File.expand_path(__FILE__)
- raise AssertionFailedError, e.message, e.backtrace.reject { |line| File.expand_path(line) =~ /#{path}/ }
- end
+ def clean_backtrace(&block)
+ yield
+ rescue Test::Unit::AssertionFailedError => e
+ path = File.expand_path(__FILE__)
+ raise Test::Unit::AssertionFailedError, e.message, e.backtrace.reject { |line| File.expand_path(line) =~ /#{path}/ }
end
end
end
+
+require File.dirname(__FILE__) + '/assertions/response_assertions'
+require File.dirname(__FILE__) + '/assertions/selector_assertions'
+require File.dirname(__FILE__) + '/assertions/tag_assertions'
+require File.dirname(__FILE__) + '/assertions/dom_assertions'
+require File.dirname(__FILE__) + '/assertions/routing_assertions'
+require File.dirname(__FILE__) + '/assertions/model_assertions'
+require File.dirname(__FILE__) + '/assertions/deprecated_assertions'
+
+module Test #:nodoc:
+ module Unit #:nodoc:
+ class TestCase #:nodoc:
+ include ActionController::Assertions
+ end
+ end
+end
\ No newline at end of file
diff --git a/vendor/rails/actionpack/lib/action_controller/base.rb b/vendor/rails/actionpack/lib/action_controller/base.rb
index 37b98be9..45d4cb18 100755
--- a/vendor/rails/actionpack/lib/action_controller/base.rb
+++ b/vendor/rails/actionpack/lib/action_controller/base.rb
@@ -2,8 +2,9 @@ require 'action_controller/mime_type'
require 'action_controller/request'
require 'action_controller/response'
require 'action_controller/routing'
-require 'action_controller/code_generation'
+require 'action_controller/resources'
require 'action_controller/url_rewriter'
+require 'action_controller/status_codes'
require 'drb'
require 'set'
@@ -27,6 +28,8 @@ module ActionController #:nodoc:
end
class MissingFile < ActionControllerError #:nodoc:
end
+ class RenderError < ActionControllerError #:nodoc:
+ end
class SessionOverflowError < ActionControllerError #:nodoc:
DEFAULT_MESSAGE = 'Your session data is larger than the data column in which it is to be stored. You must increase the size of your data column if you intend to store large data.'
@@ -35,23 +38,23 @@ module ActionController #:nodoc:
end
end
class DoubleRenderError < ActionControllerError #:nodoc:
- DEFAULT_MESSAGE = "Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and only once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like \"redirect_to(...) and return\". Finally, note that to cause a before filter to halt execution of the rest of the filter chain, the filter must return false, explicitly, so \"render(...) and return false\"."
+ DEFAULT_MESSAGE = "Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and only once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like \"redirect_to(...) and return\". Finally, note that to cause a before filter to halt execution of the rest of the filter chain, the filter must return false, explicitly, so \"render(...) and return false\"."
def initialize(message = nil)
super(message || DEFAULT_MESSAGE)
end
end
class RedirectBackError < ActionControllerError #:nodoc:
- DEFAULT_MESSAGE = 'No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify @request.env["HTTP_REFERER"].'
-
+ DEFAULT_MESSAGE = 'No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify request.env["HTTP_REFERER"].'
+
def initialize(message = nil)
super(message || DEFAULT_MESSAGE)
end
end
- # Action Controllers are the core of a web request in Rails. They are made up of one or more actions that are executed
+ # Action Controllers are the core of a web request in Rails. They are made up of one or more actions that are executed
# on request and then either render a template or redirect to another action. An action is defined as a public method
- # on the controller, which will automatically be made accessible to the web-server through Rails Routes.
+ # on the controller, which will automatically be made accessible to the web-server through Rails Routes.
#
# A sample controller could look like this:
#
@@ -59,7 +62,7 @@ module ActionController #:nodoc:
# def index
# @entries = Entry.find(:all)
# end
- #
+ #
# def sign
# Entry.create(params[:entry])
# redirect_to :action => "index"
@@ -67,11 +70,11 @@ module ActionController #:nodoc:
# end
#
# Actions, by default, render a template in the app/views directory corresponding to the name of the controller and action
- # after executing code in the action. For example, the +index+ action of the +GuestBookController+ would render the
+ # after executing code in the action. For example, the +index+ action of the +GuestBookController+ would render the
# template app/views/guestbook/index.rhtml by default after populating the @entries instance variable.
#
- # Unlike index, the sign action will not render a template. After performing its main purpose (creating a
- # new entry in the guest book), it initiates a redirect instead. This redirect works by returning an external
+ # Unlike index, the sign action will not render a template. After performing its main purpose (creating a
+ # new entry in the guest book), it initiates a redirect instead. This redirect works by returning an external
# "302 Moved" HTTP response that takes the user to the index action.
#
# The index and sign represent the two basic action archetypes used in Action Controllers. Get-and-show and do-and-redirect.
@@ -95,7 +98,7 @@ module ActionController #:nodoc:
# == Parameters
#
# All request parameters, whether they come from a GET or POST request, or from the URL, are available through the params method
- # which returns a hash. For example, an action that was performed through /weblog/list?category=All&limit=5 will include
+ # which returns a hash. For example, an action that was performed through /weblog/list?category=All&limit=5 will include
# { "category" => "All", "limit" => 5 } in params.
#
# It's also possible to construct multi-dimensional parameter hashes by specifying keys using brackets, such as:
@@ -104,14 +107,14 @@ module ActionController #:nodoc:
#
#
# A request stemming from a form holding these inputs will include { "post" => { "name" => "david", "address" => "hyacintvej" } }.
- # If the address input had been named "post[address][street]", the params would have included
+ # If the address input had been named "post[address][street]", the params would have included
# { "post" => { "address" => { "street" => "hyacintvej" } } }. There's no limit to the depth of the nesting.
#
# == Sessions
#
# Sessions allows you to store objects in between requests. This is useful for objects that are not yet ready to be persisted,
# such as a Signup object constructed in a multi-paged process, or objects that don't change much and are needed all the time, such
- # as a User object for a system that requires login. The session should not be used, however, as a cache for objects where it's likely
+ # as a User object for a system that requires login. The session should not be used, however, as a cache for objects where it's likely
# they could be changed unknowingly. It's usually too much work to keep it all synchronized -- something databases already excel at.
#
# You can place objects in the session by using the session method, which accesses a hash:
@@ -125,13 +128,13 @@ module ActionController #:nodoc:
# For removing objects from the session, you can either assign a single key to nil, like session[:person] = nil, or you can
# remove the entire session with reset_session.
#
- # By default, sessions are stored on the file system in RAILS_ROOT/tmp/sessions. Any object can be placed in the session
+ # By default, sessions are stored on the file system in RAILS_ROOT/tmp/sessions. Any object can be placed in the session
# (as long as it can be Marshalled). But remember that 1000 active sessions each storing a 50kb object could lead to a 50MB store on the filesystem.
# In other words, think carefully about size and caching before resorting to the use of the session on the filesystem.
#
# An alternative to storing sessions on disk is to use ActiveRecordStore to store sessions in your database, which can solve problems
# caused by storing sessions in the file system and may speed up your application. To use ActiveRecordStore, uncomment the line:
- #
+ #
# config.action_controller.session_store = :active_record_store
#
# in your environment.rb and run rake db:sessions:create.
@@ -205,9 +208,10 @@ module ActionController #:nodoc:
#
class Base
DEFAULT_RENDER_STATUS_CODE = "200 OK"
-
- include Reloadable::Subclasses
-
+
+ include Reloadable::Deprecated
+ include StatusCodes
+
# Determines whether the view has access to controller internals @request, @response, @session, and @template.
# By default, it does.
@@view_controller_internals = true
@@ -217,8 +221,8 @@ module ActionController #:nodoc:
@@protected_variables_cache = nil
cattr_accessor :protected_variables_cache
- # Prepends all the URL-generating helpers from AssetHelper. This makes it possible to easily move javascripts, stylesheets,
- # and images to a dedicated asset server away from the main web server. Example:
+ # Prepends all the URL-generating helpers from AssetHelper. This makes it possible to easily move javascripts, stylesheets,
+ # and images to a dedicated asset server away from the main web server. Example:
# ActionController::Base.asset_host = "http://assets.example.com"
@@asset_host = ""
cattr_accessor :asset_host
@@ -228,7 +232,7 @@ module ActionController #:nodoc:
# should instead be implemented in the controller to determine when debugging screens should be shown.
@@consider_all_requests_local = true
cattr_accessor :consider_all_requests_local
-
+
# Enable or disable the collection of failure information for RoutingErrors.
# This information can be extremely useful when tweaking custom routes, but is
# pointless once routes have been tested and verified.
@@ -241,43 +245,47 @@ module ActionController #:nodoc:
@@allow_concurrency = false
cattr_accessor :allow_concurrency
- # Modern REST web services often need to submit complex data to the web application.
- # The param_parsers hash lets you register handlers wich will process the http body and add parameters to the
+ # Modern REST web services often need to submit complex data to the web application.
+ # The param_parsers hash lets you register handlers which will process the http body and add parameters to the
# params hash. These handlers are invoked for post and put requests.
#
- # By default application/xml is enabled. A XmlSimple class with the same param name as the root will be instanciated
+ # By default application/xml is enabled. A XmlSimple class with the same param name as the root will be instanciated
# in the params. This allows XML requests to mask themselves as regular form submissions, so you can have one
# action serve both regular forms and web service requests.
- #
+ #
# Example of doing your own parser for a custom content type:
#
- # ActionController::Base.param_parsers[Mime::Type.lookup('application/atom+xml')] = Proc.new do |data|
- # node = REXML::Document.new(post)
+ # ActionController::Base.param_parsers[Mime::Type.lookup('application/atom+xml')] = Proc.new do |data|
+ # node = REXML::Document.new(post)
# { node.root.name => node.root }
# end
#
- # Note: Up until release 1.1 of Rails, Action Controller would default to using XmlSimple configured to discard the
+ # Note: Up until release 1.1 of Rails, Action Controller would default to using XmlSimple configured to discard the
# root node for such requests. The new default is to keep the root, such that "David" results
- # in params[:r][:name] for "David" instead of params[:name]. To get the old behavior, you can
+ # in params[:r][:name] for "David" instead of params[:name]. To get the old behavior, you can
# re-register XmlSimple as application/xml handler ike this:
#
- # ActionController::Base.param_parsers[Mime::XML] =
+ # ActionController::Base.param_parsers[Mime::XML] =
# Proc.new { |data| XmlSimple.xml_in(data, 'ForceArray' => false) }
#
# A YAML parser is also available and can be turned on with:
#
# ActionController::Base.param_parsers[Mime::YAML] = :yaml
@@param_parsers = { Mime::XML => :xml_simple }
- cattr_accessor :param_parsers
+ cattr_accessor :param_parsers
+
+ # Controls the default charset for all renders.
+ @@default_charset = "utf-8"
+ cattr_accessor :default_charset
# Template root determines the base from which template references will be made. So a call to render("test/template")
# will be converted to "#{template_root}/test/template.rhtml".
class_inheritable_accessor :template_root
-
+
# The logger is used for generating information on the action run-time (including benchmarking) if available.
# Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
cattr_accessor :logger
-
+
# Determines which template class should be used by ActionController.
cattr_accessor :template_class
@@ -286,39 +294,42 @@ module ActionController #:nodoc:
# Holds the request object that's primarily used to get environment variables through access like
# request.env["REQUEST_URI"].
- attr_accessor :request
-
+ attr_internal :request
+
# Holds a hash of all the GET, POST, and Url parameters passed to the action. Accessed like params["post_id"]
# to get the post_id. No type casts are made, so all values are returned as strings.
- attr_accessor :params
-
- # Holds the response object that's primarily used to set additional HTTP headers through access like
+ attr_internal :params
+
+ # Holds the response object that's primarily used to set additional HTTP headers through access like
# response.headers["Cache-Control"] = "no-cache". Can also be used to access the final body HTML after a template
# has been rendered through response.body -- useful for after_filters that wants to manipulate the output,
# such as a OutputCompressionFilter.
- attr_accessor :response
-
+ attr_internal :response
+
# Holds a hash of objects in the session. Accessed like session[:person] to get the object tied to the "person"
# key. The session will hold any type of object as values, but the key should be a string or symbol.
- attr_accessor :session
-
+ attr_internal :session
+
# Holds a hash of header names and values. Accessed like headers["Cache-Control"] to get the value of the Cache-Control
# directive. Values should always be specified as strings.
- attr_accessor :headers
-
+ attr_internal :headers
+
# Holds the hash of variables that are passed on to the template class to be made available to the view. This hash
# is generated by taking a snapshot of all the instance variables in the current scope just before a template is rendered.
attr_accessor :assigns
# Returns the name of the action this controller is processing.
attr_accessor :action_name
-
+
+ # Templates that are exempt from layouts
+ @@exempt_from_layout = Set.new([/\.rjs$/])
+
class << self
# Factory for the standard create, process loop where the controller is discarded after processing.
def process(request, response) #:nodoc:
new.process(request, response)
end
-
+
# Converts the class name from something like "OneModule::TwoModule::NeatController" to "NeatController".
def controller_class_name
@controller_class_name ||= name.demodulize
@@ -328,7 +339,7 @@ module ActionController #:nodoc:
def controller_name
@controller_name ||= controller_class_name.sub(/Controller$/, '').underscore
end
-
+
# Converts the class name from something like "OneModule::TwoModule::NeatController" to "one_module/two_module/neat".
def controller_path
@controller_path ||= name.gsub(/Controller$/, '').underscore
@@ -346,7 +357,7 @@ module ActionController #:nodoc:
def hide_action(*names)
write_inheritable_attribute(:hidden_actions, hidden_actions | names.collect { |n| n.to_s })
end
-
+
# Replace sensitive paramater data from the request log.
# Filters paramaters that have any of the arguments as a substring.
# Looks in all subhashes of the param hash for keys to filter.
@@ -368,7 +379,7 @@ module ActionController #:nodoc:
# => reverses the value to all keys matching /secret/i
#
# filter_parameter_logging(:foo, "bar") { |k,v| v.reverse! if k =~ /secret/i }
- # => reverses the value to all keys matching /secret/i, and
+ # => reverses the value to all keys matching /secret/i, and
# replaces the value to all keys matching /foo|bar/i with "[FILTERED]"
def filter_parameter_logging(*filter_words, &block)
parameter_filter = Regexp.new(filter_words.collect{ |s| s.to_s }.join('|'), true) if filter_words.length > 0
@@ -380,12 +391,12 @@ module ActionController #:nodoc:
if key =~ parameter_filter
filtered_parameters[key] = '[FILTERED]'
elsif value.is_a?(Hash)
- filtered_parameters[key] = filter_parameters(value)
+ filtered_parameters[key] = filter_parameters(value)
elsif block_given?
key, value = key.dup, value.dup
yield key, value
filtered_parameters[key] = value
- else
+ else
filtered_parameters[key] = value
end
end
@@ -393,9 +404,20 @@ module ActionController #:nodoc:
filtered_parameters
end
end
+
+ # Don't render layouts for templates with the given extensions.
+ def exempt_from_layout(*extensions)
+ @@exempt_from_layout.merge extensions.collect { |extension|
+ if extension.is_a?(Regexp)
+ extension
+ else
+ /\.#{Regexp.escape(extension.to_s)}$/
+ end
+ }
+ end
end
- public
+ public
# Extracts the action_name from the request parameters and performs that action.
def process(request, response, method = :perform_action, *arguments) #:nodoc:
initialize_template_class(response)
@@ -403,25 +425,26 @@ module ActionController #:nodoc:
initialize_current_url
assign_names
forget_variables_added_to_assigns
-
+
log_processing
send(method, *arguments)
-
+
+ assign_default_content_type_and_charset
response
ensure
process_cleanup
end
- # Returns a URL that has been rewritten according to the options hash and the defined Routes.
+ # Returns a URL that has been rewritten according to the options hash and the defined Routes.
# (For doing a complete redirect, use redirect_to).
#
# url_for is used to:
#
# All keys given to url_for are forwarded to the Route module, save for the following:
- # * :anchor -- specifies the anchor name to be appended to the path. For example,
- # url_for :controller => 'posts', :action => 'show', :id => 10, :anchor => 'comments'
+ # * :anchor -- specifies the anchor name to be appended to the path. For example,
+ # url_for :controller => 'posts', :action => 'show', :id => 10, :anchor => 'comments'
# will produce "/posts/show/10#comments".
- # * :only_path -- if true, returns the absolute URL (omitting the protocol, host name, and port)
+ # * :only_path -- if true, returns the relative URL (omitting the protocol, host name, and port) (false by default)
# * :trailing_slash -- if true, adds a trailing slash, as in "/archive/2005/". Note that this
# is currently not recommended since it breaks caching.
# * :host -- overrides the default (current) host if provided
@@ -472,7 +495,7 @@ module ActionController #:nodoc:
# displayed on:
#
# url_for :controller => 'posts', :action => nil
- #
+ #
# If you explicitly want to create a URL that's almost the same as the current URL, you can do so using the
# :overwrite_params options. Say for your posts you have different views for showing and printing them.
# Then, in the show view, you get the URL for the print view like this
@@ -483,9 +506,20 @@ module ActionController #:nodoc:
# would have slashed-off the path components after the changed action.
def url_for(options = {}, *parameters_for_method_reference) #:doc:
case options
- when String then options
- when Symbol then send(options, *parameters_for_method_reference)
- when Hash then @url.rewrite(rewrite_options(options))
+ when String
+ options
+
+ when Symbol
+ ActiveSupport::Deprecation.warn(
+ "You called url_for(:#{options}), which is a deprecated API call. Instead you should use the named " +
+ "route directly, like #{options}(). Using symbols and parameters with url_for will be removed from Rails 2.0.",
+ caller
+ )
+
+ send(options, *parameters_for_method_reference)
+
+ when Hash
+ @url.rewrite(rewrite_options(options))
end
end
@@ -499,6 +533,11 @@ module ActionController #:nodoc:
self.class.controller_name
end
+ # Converts the class name from something like "OneModule::TwoModule::NeatController" to "one_module/two_module/neat".
+ def controller_path
+ self.class.controller_path
+ end
+
def session_enabled?
request.session_options[:disabled] != false
end
@@ -507,7 +546,7 @@ module ActionController #:nodoc:
# Renders the content that will be returned to the browser as the response body.
#
# === Rendering an action
- #
+ #
# Action rendering is the most common form and the type used automatically by Action Controller when nothing else is
# specified. By default, actions are rendered within the current layout (if one exists).
#
@@ -523,47 +562,54 @@ module ActionController #:nodoc:
# render :action => "long_goal", :layout => "spectacular"
#
# _Deprecation_ _notice_: This used to have the signatures render_action("action", status = 200),
- # render_without_layout("controller/action", status = 200), and
+ # render_without_layout("controller/action", status = 200), and
# render_with_layout("controller/action", status = 200, layout).
#
# === Rendering partials
- #
- # Partial rendering is most commonly used together with Ajax calls that only update one or a few elements on a page
+ #
+ # Partial rendering in a controller is most commonly used together with Ajax calls that only update one or a few elements on a page
# without reloading. Rendering of partials from the controller makes it possible to use the same partial template in
# both the full-page rendering (by calling it from within the template) and when sub-page updates happen (from the
# controller action responding to Ajax calls). By default, the current layout is not used.
#
- # # Renders the partial located at app/views/controller/_win.r(html|xml)
- # render :partial => "win"
+ # # Renders the same partial with a local variable.
+ # render :partial => "person", :locals => { :name => "david" }
#
- # # Renders the partial with a status code of 500 (internal error)
+ # # Renders a collection of the same partial by making each element
+ # # of @winners available through the local variable "person" as it
+ # # builds the complete response.
+ # render :partial => "person", :collection => @winners
+ #
+ # # Renders the same collection of partials, but also renders the
+ # # person_divider partial between each person partial.
+ # render :partial => "person", :collection => @winners, :spacer_template => "person_divider"
+ #
+ # # Renders a collection of partials located in a view subfolder
+ # # outside of our current controller. In this example we will be
+ # # rendering app/views/shared/_note.r(html|xml) Inside the partial
+ # # each element of @new_notes is available as the local var "note".
+ # render :partial => "shared/note", :collection => @new_notes
+ #
+ # # Renders the partial with a status code of 500 (internal error).
# render :partial => "broken", :status => 500
#
- # # Renders the same partial but also makes a local variable available to it
- # render :partial => "win", :locals => { :name => "david" }
+ # Note that the partial filename must also be a valid Ruby variable name,
+ # so e.g. 2005 and register-user are invalid.
#
- # # Renders a collection of the same partial by making each element of @wins available through
- # # the local variable "win" as it builds the complete response
- # render :partial => "win", :collection => @wins
- #
- # # Renders the same collection of partials, but also renders the win_divider partial in between
- # # each win partial.
- # render :partial => "win", :collection => @wins, :spacer_template => "win_divider"
- #
- # _Deprecation_ _notice_: This used to have the signatures
+ # _Deprecation_ _notice_: This used to have the signatures
# render_partial(partial_path = default_template_name, object = nil, local_assigns = {}) and
# render_partial_collection(partial_name, collection, partial_spacer_template = nil, local_assigns = {}).
#
# === Rendering a template
- #
- # Template rendering works just like action rendering except that it takes a path relative to the template root.
+ #
+ # Template rendering works just like action rendering except that it takes a path relative to the template root.
# The current layout is automatically applied.
#
# # Renders the template located in [TEMPLATE_ROOT]/weblog/show.r(html|xml) (in Rails, app/views/weblog/show.rhtml)
# render :template => "weblog/show"
#
# === Rendering a file
- #
+ #
# File rendering works just like action rendering except that it takes a filesystem path. By default, the path
# is assumed to be absolute, and the current layout is not applied.
#
@@ -581,7 +627,7 @@ module ActionController #:nodoc:
# _Deprecation_ _notice_: This used to have the signature render_file(path, status = 200)
#
# === Rendering text
- #
+ #
# Rendering of text is usually used for tests or for rendering prepared content, such as a cache. By default, text
# rendering is not done within the active layout.
#
@@ -589,17 +635,38 @@ module ActionController #:nodoc:
# render :text => "hello world!"
#
# # Renders the clear text "Explosion!" with status code 500
- # render :text => "Explosion!", :status => 500
+ # render :text => "Explosion!", :status => 500
#
# # Renders the clear text "Hi there!" within the current active layout (if one exists)
# render :text => "Explosion!", :layout => true
#
- # # Renders the clear text "Hi there!" within the layout
+ # # Renders the clear text "Hi there!" within the layout
# # placed in "app/views/layouts/special.r(html|xml)"
# render :text => "Explosion!", :layout => "special"
#
+ # The :text option can also accept a Proc object, which can be used to manually control the page generation. This should
+ # generally be avoided, as it violates the separation between code and content, and because almost everything that can be
+ # done with this method can also be done more cleanly using one of the other rendering methods, most notably templates.
+ #
+ # # Renders "Hello from code!"
+ # render :text => proc { |response, output| output.write("Hello from code!") }
+ #
# _Deprecation_ _notice_: This used to have the signature render_text("text", status = 200)
#
+ # === Rendering JSON
+ #
+ # Rendering JSON sets the content type to text/x-json and optionally wraps the JSON in a callback. It is expected
+ # that the response will be eval'd for use as a data structure.
+ #
+ # # Renders '{name: "David"}'
+ # render :json => {:name => "David"}.to_json
+ #
+ # Sometimes the result isn't handled directly by a script (such as when the request comes from a SCRIPT tag),
+ # so the callback option is provided for these cases.
+ #
+ # # Renders 'show({name: "David"})'
+ # render :json => {:name => "David"}.to_json, :callback => 'show'
+ #
# === Rendering an inline template
#
# Rendering of an inline template works as a cross between text and action rendering where the source for the template
@@ -607,7 +674,7 @@ module ActionController #:nodoc:
# and the current layout is not used.
#
# # Renders "hello, hello, hello, again"
- # render :inline => "<%= 'hello, ' * 3 + 'again' %>"
+ # render :inline => "<%= 'hello, ' * 3 + 'again' %>"
#
# # Renders "
Good seeing you!
" using Builder
# render :inline => "xml.p { 'Good seeing you!' }", :type => :rxml
@@ -640,17 +707,27 @@ module ActionController #:nodoc:
def render(options = nil, deprecated_status = nil, &block) #:doc:
raise DoubleRenderError, "Can only render or redirect once per action" if performed?
- # Backwards compatibility
- unless options.is_a?(Hash)
- if options == :update
- options = {:update => true}
- else
- return render_file(options || default_template_name, deprecated_status, true)
+ if options.nil?
+ return render_file(default_template_name, deprecated_status, true)
+ else
+ # Backwards compatibility
+ unless options.is_a?(Hash)
+ if options == :update
+ options = { :update => true }
+ else
+ ActiveSupport::Deprecation.warn(
+ "You called render('#{options}'), which is a deprecated API call. Instead you use " +
+ "render :file => #{options}. Calling render with just a string will be removed from Rails 2.0.",
+ caller
+ )
+
+ return render_file(options, deprecated_status, true)
+ end
end
end
if content_type = options[:content_type]
- headers["Content-Type"] = content_type
+ response.content_type = content_type.to_s
end
if text = options[:text]
@@ -662,16 +739,21 @@ module ActionController #:nodoc:
elsif template = options[:template]
render_file(template, options[:status], true)
-
+
elsif inline = options[:inline]
render_template(inline, options[:status], options[:type], options[:locals] || {})
-
+
elsif action_name = options[:action]
- render_action(action_name, options[:status], options[:layout])
+ ActiveSupport::Deprecation.silence do
+ render_action(action_name, options[:status], options[:layout])
+ end
elsif xml = options[:xml]
render_xml(xml, options[:status])
+ elsif json = options[:json]
+ render_json(json, options[:callback], options[:status])
+
elsif partial = options[:partial]
partial = default_template_name if partial == true
if collection = options[:collection]
@@ -683,17 +765,17 @@ module ActionController #:nodoc:
elsif options[:update]
add_variables_to_assigns
@template.send :evaluate_assigns
-
+
generator = ActionView::Helpers::PrototypeHelper::JavaScriptGenerator.new(@template, &block)
render_javascript(generator.to_s)
elsif options[:nothing]
# Safari doesn't pass the headers of the return if the response is zero length
render_text(" ", options[:status])
-
+
else
render_file(default_template_name, options[:status], true)
-
+
end
end
end
@@ -701,21 +783,19 @@ module ActionController #:nodoc:
# Renders according to the same rules as render, but returns the result in a string instead
# of sending it as the response body to the browser.
def render_to_string(options = nil, &block) #:doc:
- result = render(options, &block)
-
+ ActiveSupport::Deprecation.silence { render(options, &block) }
+ ensure
erase_render_results
forget_variables_added_to_assigns
reset_variables_added_to_assigns
-
- result
- end
+ end
def render_action(action_name, status = nil, with_layout = true) #:nodoc:
template = default_template_name(action_name.to_s)
- if with_layout && !template_exempt_from_layout?(template)
- render_with_layout(template, status)
+ if with_layout && !template_exempt_from_layout?(template)
+ render_with_layout(:file => template, :status => status, :use_full_path => true, :layout => true)
else
- render_without_layout(template, status)
+ render_without_layout(:file => template, :status => status, :use_full_path => true)
end
end
@@ -731,22 +811,36 @@ module ActionController #:nodoc:
render_text(@template.render_template(type, template, nil, local_assigns), status)
end
- def render_text(text = nil, status = nil) #:nodoc:
+ def render_text(text = nil, status = nil, append_response = false) #:nodoc:
@performed_render = true
- @response.headers['Status'] = (status || DEFAULT_RENDER_STATUS_CODE).to_s
- @response.body = text
+
+ response.headers['Status'] = interpret_status(status || DEFAULT_RENDER_STATUS_CODE)
+
+ if append_response
+ response.body ||= ''
+ response.body << text
+ else
+ response.body = text
+ end
end
- def render_javascript(javascript, status = nil) #:nodoc:
- @response.headers['Content-Type'] = 'text/javascript; charset=UTF-8'
- render_text(javascript, status)
+ def render_javascript(javascript, status = nil, append_response = true) #:nodoc:
+ response.content_type = Mime::JS
+ render_text(javascript, status, append_response)
end
def render_xml(xml, status = nil) #:nodoc:
- @response.headers['Content-Type'] = 'application/xml'
+ response.content_type = Mime::XML
render_text(xml, status)
end
+ def render_json(json, callback = nil, status = nil) #:nodoc:
+ json = "#{callback}(#{json})" unless callback.blank?
+
+ response.content_type = Mime::JSON
+ render_text(json, status)
+ end
+
def render_nothing(status = nil) #:nodoc:
render_text(' ', status)
end
@@ -770,13 +864,52 @@ module ActionController #:nodoc:
end
+ # Return a response that has no content (merely headers). The options
+ # argument is interpreted to be a hash of header names and values.
+ # This allows you to easily return a response that consists only of
+ # significant headers:
+ #
+ # head :created, :location => person_path(@person)
+ #
+ # It can also be used to return exceptional conditions:
+ #
+ # return head(:method_not_allowed) unless request.post?
+ # return head(:bad_request) unless valid_request?
+ # render
+ def head(*args)
+ if args.length > 2
+ raise ArgumentError, "too many arguments to head"
+ elsif args.empty?
+ raise ArgumentError, "too few arguments to head"
+ elsif args.length == 2
+ status = args.shift
+ options = args.shift
+ elsif args.first.is_a?(Hash)
+ options = args.first
+ else
+ status = args.first
+ options = {}
+ end
+
+ raise ArgumentError, "head requires an options hash" if !options.is_a?(Hash)
+
+ status = interpret_status(status || options.delete(:status) || :ok)
+
+ options.each do |key, value|
+ headers[key.to_s.dasherize.split(/-/).map { |v| v.capitalize }.join("-")] = value.to_s
+ end
+
+ render :nothing => true, :status => status
+ end
+
+
# Clears the rendered results, allowing for another render to be performed.
def erase_render_results #:nodoc:
- @response.body = nil
+ response.body = nil
@performed_render = false
end
-
- # Clears the redirected results from the headers, resets the status to 200 and returns
+
+ # Clears the redirected results from the headers, resets the status to 200 and returns
# the URL that was used to redirect or nil if there was no redirected URL
# Note that +redirect_to+ will change the body of the response to indicate a redirection.
# The response body is not reset here, see +erase_render_results+
@@ -785,7 +918,7 @@ module ActionController #:nodoc:
response.redirected_to = nil
response.redirected_to_method_params = nil
response.headers['Status'] = DEFAULT_RENDER_STATUS_CODE
- response.headers.delete('location')
+ response.headers.delete('Location')
end
# Erase both render and redirect results
@@ -801,7 +934,7 @@ module ActionController #:nodoc:
options
end
end
-
+
# Overwrite to implement a number of default options that all url_for-based methods will use. The default options should come in
# the form of a hash, just like the one you would use for url_for directly. Example:
#
@@ -814,7 +947,7 @@ module ActionController #:nodoc:
# by this method.
def default_url_options(options) #:doc:
end
-
+
# Redirects the browser to the target specified in +options+. This parameter can take one of three forms:
#
# * Hash: The URL will be generated by calling url_for with the +options+.
@@ -822,7 +955,7 @@ module ActionController #:nodoc:
# * String not containing a protocol: The current protocol and host is prepended to the string.
# * :back: Back to the page that issued the request. Useful for forms that are triggered from multiple places.
# Short-hand for redirect_to(request.env["HTTP_REFERER"])
- #
+ #
# Examples:
# redirect_to :action => "show", :id => 5
# redirect_to "http://www.rubyonrails.org"
@@ -845,7 +978,7 @@ module ActionController #:nodoc:
when String
redirect_to(request.protocol + request.host_with_port + options)
-
+
when :back
request.env["HTTP_REFERER"] ? redirect_to(request.env["HTTP_REFERER"]) : raise(RedirectBackError)
@@ -854,12 +987,13 @@ module ActionController #:nodoc:
redirect_to(url_for(options))
response.redirected_to = options
else
+ # TOOD: Deprecate me!
redirect_to(url_for(options, *parameters_for_method_reference))
response.redirected_to, response.redirected_to_method_params = options, parameters_for_method_reference
end
end
end
-
+
# Sets a HTTP 1.1 Cache-Control header. Defaults to issuing a "private" instruction, so that
# intermediate caches shouldn't cache the response.
#
@@ -867,29 +1001,29 @@ module ActionController #:nodoc:
# expires_in 20.minutes
# expires_in 3.hours, :private => false
# expires in 3.hours, 'max-stale' => 5.hours, :private => nil, :public => true
- #
+ #
# This method will overwrite an existing Cache-Control header.
# See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html for more possibilities.
def expires_in(seconds, options = {}) #:doc:
cache_options = { 'max-age' => seconds, 'private' => true }.symbolize_keys.merge!(options.symbolize_keys)
cache_options.delete_if { |k,v| v.nil? or v == false }
cache_control = cache_options.map{ |k,v| v == true ? k.to_s : "#{k.to_s}=#{v.to_s}"}
- @response.headers["Cache-Control"] = cache_control.join(', ')
+ response.headers["Cache-Control"] = cache_control.join(', ')
end
-
+
# Sets a HTTP 1.1 Cache-Control header of "no-cache" so no caching should occur by the browser or
# intermediate caches (like caching proxy servers).
def expires_now #:doc:
- @response.headers["Cache-Control"] = "no-cache"
+ response.headers["Cache-Control"] = "no-cache"
end
# Resets the session by clearing out all the objects stored within and initializing a new session object.
def reset_session #:doc:
- @request.reset_session
- @session = @request.session
- @response.session = @session
+ request.reset_session
+ @_session = request.session
+ response.session = @_session
end
-
+
private
def self.view_class
@view_class ||=
@@ -905,48 +1039,71 @@ module ActionController #:nodoc:
def initialize_template_class(response)
raise "You must assign a template class through ActionController.template_class= before processing a request" unless @@template_class
-
+
response.template = self.class.view_class.new(self.class.view_root, {}, self)
response.redirected_to = nil
@performed_render = @performed_redirect = false
end
-
+
def assign_shortcuts(request, response)
- @request, @params, @cookies = request, request.parameters, request.cookies
+ @_request, @_params, @_cookies = request, request.parameters, request.cookies
- @response = response
- @response.session = request.session
+ @_response = response
+ @_response.session = request.session
- @session = @response.session
- @template = @response.template
- @assigns = @response.template.assigns
-
- @headers = @response.headers
+ @_session = @_response.session
+ @template = @_response.template
+ @assigns = @_response.template.assigns
+
+ @_headers = @_response.headers
+
+ assign_deprecated_shortcuts(request, response)
end
-
+
+
+ # TODO: assigns cookies headers params request response template
+ DEPRECATED_INSTANCE_VARIABLES = %w(cookies flash headers params request response session)
+
+ # Gone after 1.2.
+ def assign_deprecated_shortcuts(request, response)
+ DEPRECATED_INSTANCE_VARIABLES.each do |method|
+ var = "@#{method}"
+ if instance_variables.include?(var)
+ value = instance_variable_get(var)
+ unless ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy === value
+ raise "Deprecating #{var}, but it's already set to #{value.inspect}! Use the #{method}= writer method instead of setting #{var} directly."
+ end
+ end
+ instance_variable_set var, ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(self, method)
+ end
+ end
+
def initialize_current_url
- @url = UrlRewriter.new(@request, @params.clone())
+ @url = UrlRewriter.new(request, params.clone)
end
def log_processing
if logger
logger.info "\n\nProcessing #{controller_class_name}\##{action_name} (for #{request_origin}) [#{request.method.to_s.upcase}]"
- logger.info " Session ID: #{@session.session_id}" if @session and @session.respond_to?(:session_id)
- logger.info " Parameters: #{respond_to?(:filter_parameters) ? filter_parameters(@params).inspect : @params.inspect}"
+ logger.info " Session ID: #{@_session.session_id}" if @_session and @_session.respond_to?(:session_id)
+ logger.info " Parameters: #{respond_to?(:filter_parameters) ? filter_parameters(params).inspect : params.inspect}"
end
end
-
+
def perform_action
- if self.class.action_methods.include?(action_name) || self.class.action_methods.include?('method_missing')
+ if self.class.action_methods.include?(action_name)
send(action_name)
render unless performed?
+ elsif respond_to? :method_missing
+ send(:method_missing, action_name)
+ render unless performed?
elsif template_exists? && template_public?
render
else
raise UnknownAction, "No action responded to #{action_name}", caller
end
end
-
+
def performed?
@performed_render || @performed_redirect
end
@@ -954,7 +1111,16 @@ module ActionController #:nodoc:
def assign_names
@action_name = (params['action'] || 'index')
end
-
+
+ def assign_default_content_type_and_charset
+ response.content_type ||= Mime::HTML
+ response.charset ||= self.class.default_charset unless sending_file?
+ end
+
+ def sending_file?
+ response.headers["Content-Transfer-Encoding"] == "binary"
+ end
+
def action_methods
self.class.action_methods
end
@@ -970,17 +1136,17 @@ module ActionController #:nodoc:
@variables_added = true
end
end
-
+
def forget_variables_added_to_assigns
@variables_added = nil
end
-
+
def reset_variables_added_to_assigns
@template.instance_variable_set("@assigns_added", nil)
end
def add_instance_variables_to_assigns
- @@protected_variables_cache ||= protected_instance_variables.inject({}) { |h, k| h[k] = true; h }
+ @@protected_variables_cache ||= Set.new(protected_instance_variables)
instance_variables.each do |var|
next if @@protected_variables_cache.include?(var)
@assigns[var[1..-1]] = instance_variable_get(var)
@@ -988,33 +1154,36 @@ module ActionController #:nodoc:
end
def add_class_variables_to_assigns
- %w( template_root logger template_class ignore_missing_templates ).each do |cvar|
+ %w(template_root logger template_class ignore_missing_templates).each do |cvar|
@assigns[cvar] = self.send(cvar)
end
end
def protected_instance_variables
if view_controller_internals
- [ "@assigns", "@performed_redirect", "@performed_render" ]
+ %w(@assigns @performed_redirect @performed_render)
else
- [ "@assigns", "@performed_redirect", "@performed_render", "@request", "@response", "@session", "@cookies", "@template", "@request_origin", "@parent_controller" ]
+ %w(@assigns @performed_redirect @performed_render
+ @_request @request @_response @response @_params @params
+ @_session @session @_cookies @cookies
+ @template @request_origin @parent_controller)
end
end
def request_origin
# this *needs* to be cached!
# otherwise you'd get different results if calling it more than once
- @request_origin ||= "#{@request.remote_ip} at #{Time.now.to_s(:db)}"
+ @request_origin ||= "#{request.remote_ip} at #{Time.now.to_s(:db)}"
end
-
+
def complete_request_uri
- "#{@request.protocol}#{@request.host}#{@request.request_uri}"
+ "#{request.protocol}#{request.host}#{request.request_uri}"
end
def close_session
- @session.close unless @session.nil? || Hash === @session
+ @_session.close if @_session && @_session.respond_to?(:close)
end
-
+
def template_exists?(template_name = default_template_name)
@template.file_exists?(template_name)
end
@@ -1024,7 +1193,9 @@ module ActionController #:nodoc:
end
def template_exempt_from_layout?(template_name = default_template_name)
- template_name =~ /\.rjs$/ || (@template.pick_template_extension(template_name) == :rjs rescue false)
+ extension = @template.pick_template_extension(template_name) rescue nil
+ name_with_extension = !template_name.include?('.') && extension ? "#{template_name}.#{extension}" : template_name
+ extension == :rjs || @@exempt_from_layout.any? { |ext| name_with_extension =~ ext }
end
def assert_existence_of_template_file(template_name)
@@ -1044,11 +1215,11 @@ module ActionController #:nodoc:
end
"#{self.class.controller_path}/#{action_name}"
end
-
+
def strip_out_controller(path)
path.split('/', 2).last
end
-
+
def template_path_includes_controller?(path)
self.class.controller_path.split('/')[-1] == path.split('/')[0]
end
diff --git a/vendor/rails/actionpack/lib/action_controller/benchmarking.rb b/vendor/rails/actionpack/lib/action_controller/benchmarking.rb
index a30212c8..ae0dd3b9 100644
--- a/vendor/rails/actionpack/lib/action_controller/benchmarking.rb
+++ b/vendor/rails/actionpack/lib/action_controller/benchmarking.rb
@@ -8,11 +8,8 @@ module ActionController #:nodoc:
base.extend(ClassMethods)
base.class_eval do
- alias_method :perform_action_without_benchmark, :perform_action
- alias_method :perform_action, :perform_action_with_benchmark
-
- alias_method :render_without_benchmark, :render
- alias_method :render, :render_with_benchmark
+ alias_method_chain :perform_action, :benchmark
+ alias_method_chain :render, :benchmark
end
end
@@ -68,7 +65,7 @@ module ActionController #:nodoc:
else
runtime = [Benchmark::measure{ perform_action_without_benchmark }.real, 0.0001].max
log_message = "Completed in #{sprintf("%.5f", runtime)} (#{(1 / runtime).floor} reqs/sec)"
- log_message << rendering_runtime(runtime) if @rendering_runtime
+ log_message << rendering_runtime(runtime) if defined?(@rendering_runtime)
log_message << active_record_runtime(runtime) if Object.const_defined?("ActiveRecord") && ActiveRecord::Base.connected?
log_message << " | #{headers["Status"]}"
log_message << " [#{complete_request_uri rescue "unknown"}]"
diff --git a/vendor/rails/actionpack/lib/action_controller/caching.rb b/vendor/rails/actionpack/lib/action_controller/caching.rb
index 91da89ad..35dee4b4 100644
--- a/vendor/rails/actionpack/lib/action_controller/caching.rb
+++ b/vendor/rails/actionpack/lib/action_controller/caching.rb
@@ -1,4 +1,5 @@
require 'fileutils'
+require 'uri'
module ActionController #:nodoc:
# Caching is a cheap way of speeding up slow applications by keeping the result of calculations, renderings, and database calls
@@ -117,24 +118,24 @@ module ActionController #:nodoc:
return unless perform_caching
if options[:action].is_a?(Array)
options[:action].dup.each do |action|
- self.class.expire_page(url_for(options.merge({ :only_path => true, :skip_relative_url_root => true, :action => action })))
+ self.class.expire_page(url_for(options.merge(:only_path => true, :skip_relative_url_root => true, :action => action)))
end
else
- self.class.expire_page(url_for(options.merge({ :only_path => true, :skip_relative_url_root => true })))
+ self.class.expire_page(url_for(options.merge(:only_path => true, :skip_relative_url_root => true)))
end
end
- # Manually cache the +content+ in the key determined by +options+. If no content is provided, the contents of @response.body is used
+ # Manually cache the +content+ in the key determined by +options+. If no content is provided, the contents of response.body is used
# If no options are provided, the current +options+ for this action is used. Example:
# cache_page "I'm the cached content", :controller => "lists", :action => "show"
def cache_page(content = nil, options = {})
return unless perform_caching && caching_allowed
- self.class.cache_page(content || @response.body, url_for(options.merge({ :only_path => true, :skip_relative_url_root => true })))
+ self.class.cache_page(content || response.body, url_for(options.merge(:only_path => true, :skip_relative_url_root => true, :format => params[:format])))
end
private
def caching_allowed
- !@request.post? && @response.headers['Status'] && @response.headers['Status'].to_i < 400
+ request.get? && response.headers['Status'].to_i == 200
end
end
@@ -155,9 +156,12 @@ module ActionController #:nodoc:
# the current host and the path. So a page that is accessed at http://david.somewhere.com/lists/show/1 will result in a fragment named
# "david.somewhere.com/lists/show/1". This allows the cacher to differentiate between "david.somewhere.com/lists/" and
# "jamis.somewhere.com/lists/" -- which is a helpful way of assisting the subdomain-as-account-key pattern.
+ #
+ # Different representations of the same resource, e.g. http://david.somewhere.com/lists and http://david.somewhere.com/lists.xml
+ # are treated like separate requests and so are cached separately. Keep in mind when expiring an action cache that :action => 'lists' is not the same
+ # as :action => 'list', :format => :xml.
module Actions
- def self.append_features(base) #:nodoc:
- super
+ def self.included(base) #:nodoc:
base.extend(ClassMethods)
base.send(:attr_accessor, :rendered_action_cache)
end
@@ -173,22 +177,24 @@ module ActionController #:nodoc:
return unless perform_caching
if options[:action].is_a?(Array)
options[:action].dup.each do |action|
- expire_fragment(url_for(options.merge({ :action => action })).split("://").last)
+ expire_fragment(ActionCachePath.path_for(self, options.merge({ :action => action })))
end
else
- expire_fragment(url_for(options).split("://").last)
+ expire_fragment(ActionCachePath.path_for(self, options))
end
end
class ActionCacheFilter #:nodoc:
- def initialize(*actions)
+ def initialize(*actions, &block)
@actions = actions
end
def before(controller)
return unless @actions.include?(controller.action_name.intern)
- if cache = controller.read_fragment(controller.url_for.split("://").last)
+ action_cache_path = ActionCachePath.new(controller)
+ if cache = controller.read_fragment(action_cache_path.path)
controller.rendered_action_cache = true
+ set_content_type!(action_cache_path)
controller.send(:render_text, cache)
false
end
@@ -196,8 +202,60 @@ module ActionController #:nodoc:
def after(controller)
return if !@actions.include?(controller.action_name.intern) || controller.rendered_action_cache
- controller.write_fragment(controller.url_for.split("://").last, controller.response.body)
+ controller.write_fragment(ActionCachePath.path_for(controller), controller.response.body)
end
+
+ private
+
+ def set_content_type!(action_cache_path)
+ if extention = action_cache_path.extension
+ content_type = Mime::EXTENSION_LOOKUP[extention]
+ action_cache_path.controller.response.content_type = content_type.to_s
+ end
+ end
+
+ end
+
+ class ActionCachePath
+ attr_reader :controller, :options
+
+ class << self
+ def path_for(*args, &block)
+ new(*args).path
+ end
+ end
+
+ def initialize(controller, options = {})
+ @controller = controller
+ @options = options
+ end
+
+ def path
+ return @path if @path
+ @path = controller.url_for(options).split('://').last
+ normalize!
+ add_extension!
+ URI.unescape(@path)
+ end
+
+ def extension
+ @extension ||= extract_extension(controller.request.path)
+ end
+
+ private
+ def normalize!
+ @path << 'index' if @path.last == '/'
+ end
+
+ def add_extension!
+ @path << ".#{extension}" if extension
+ end
+
+ def extract_extension(file_path)
+ # Don't want just what comes after the last '.' to accomodate multi part extensions
+ # such as tar.gz.
+ file_path[/^[^.]+\.(.+)$/, 1]
+ end
end
end
@@ -208,7 +266,7 @@ module ActionController #:nodoc:
# Hello <%= @name %>
# <% cache do %>
# All the topics in the system:
- # <%= render_collection_of_partials "topic", Topic.find_all %>
+ # <%= render :partial => "topic", :collection => Topic.find(:all) %>
# <% end %>
#
# This cache will bind to the name of action that called it. So you would be able to invalidate it using
@@ -246,8 +304,7 @@ module ActionController #:nodoc:
# ActionController::Base.fragment_cache_store = :mem_cache_store, "localhost"
# ActionController::Base.fragment_cache_store = MyOwnStore.new("parameter")
module Fragments
- def self.append_features(base) #:nodoc:
- super
+ def self.included(base) #:nodoc:
base.class_eval do
@@fragment_cache_store = MemoryStore.new
cattr_reader :fragment_cache_store
@@ -306,7 +363,12 @@ module ActionController #:nodoc:
# Name can take one of three forms:
# * String: This would normally take the form of a path like "pages/45/notes"
# * Hash: Is treated as an implicit call to url_for, like { :controller => "pages", :action => "notes", :id => 45 }
- # * Regexp: Will destroy all the matched fragments, example: %r{pages/\d*/notes} Ensure you do not specify start and finish in the regex (^$) because the actual filename matched looks like ./cache/filename/path.cache
+ # * Regexp: Will destroy all the matched fragments, example:
+ # %r{pages/\d*/notes}
+ # Ensure you do not specify start and finish in the regex (^$) because
+ # the actual filename matched looks like ./cache/filename/path.cache
+ # Regexp expiration is not supported on caches which can't iterate over
+ # all keys, such as memcached.
def expire_fragment(name, options = nil)
return unless perform_caching
@@ -327,6 +389,7 @@ module ActionController #:nodoc:
def expire_matched_fragments(matcher = /.*/, options = nil) #:nodoc:
expire_fragment(matcher, options)
end
+ deprecate :expire_matched_fragments => :expire_fragment
class UnthreadedMemoryStore #:nodoc:
@@ -430,7 +493,7 @@ module ActionController #:nodoc:
if f =~ matcher
begin
File.delete(f)
- rescue Object => e
+ rescue SystemCallError => e
# If there's no cache, then there's nothing to complain about
end
end
@@ -493,8 +556,7 @@ module ActionController #:nodoc:
#
# In the example above, four actions are cached and three actions are responsible for expiring those caches.
module Sweeping
- def self.append_features(base) #:nodoc:
- super
+ def self.included(base) #:nodoc:
base.extend(ClassMethods)
end
@@ -503,8 +565,7 @@ module ActionController #:nodoc:
return unless perform_caching
configuration = sweepers.last.is_a?(Hash) ? sweepers.pop : {}
sweepers.each do |sweeper|
- observer(sweeper)
-
+ ActiveRecord::Base.observers << sweeper if defined?(ActiveRecord) and defined?(ActiveRecord::Base)
sweeper_instance = Object.const_get(Inflector.classify(sweeper)).instance
if sweeper_instance.is_a?(Sweeper)
@@ -523,7 +584,7 @@ module ActionController #:nodoc:
# ActiveRecord::Observer will mark this class as reloadable even though it should not be.
# However, subclasses of ActionController::Caching::Sweeper should be Reloadable
- include Reloadable::Subclasses
+ include Reloadable::Deprecated
def before(controller)
self.controller = controller
diff --git a/vendor/rails/actionpack/lib/action_controller/cgi_ext/cgi_ext.rb b/vendor/rails/actionpack/lib/action_controller/cgi_ext/cgi_ext.rb
index d2973c0c..06958272 100755
--- a/vendor/rails/actionpack/lib/action_controller/cgi_ext/cgi_ext.rb
+++ b/vendor/rails/actionpack/lib/action_controller/cgi_ext/cgi_ext.rb
@@ -27,13 +27,6 @@ class CGI #:nodoc:
def request_parameters
CGIMethods.parse_request_parameters(params, env_table)
end
-
- def redirect(where)
- header({
- "Status" => "302 Moved",
- "location" => "#{where}"
- })
- end
def session(parameters = nil)
parameters = {} if parameters.nil?
diff --git a/vendor/rails/actionpack/lib/action_controller/cgi_ext/cgi_methods.rb b/vendor/rails/actionpack/lib/action_controller/cgi_ext/cgi_methods.rb
index 941646c5..55bece29 100755
--- a/vendor/rails/actionpack/lib/action_controller/cgi_ext/cgi_methods.rb
+++ b/vendor/rails/actionpack/lib/action_controller/cgi_ext/cgi_methods.rb
@@ -1,217 +1,211 @@
require 'cgi'
-require 'action_controller/vendor/xml_simple'
require 'action_controller/vendor/xml_node'
+require 'strscan'
# Static methods for parsing the query and request parameters that can be used in
# a CGI extension class or testing in isolation.
class CGIMethods #:nodoc:
- public
- # Returns a hash with the pairs from the query string. The implicit hash construction that is done in
- # parse_request_params is not done here.
- def CGIMethods.parse_query_parameters(query_string)
- parsed_params = {}
-
- query_string.split(/[&;]/).each { |p|
- # Ignore repeated delimiters.
- next if p.empty?
+ class << self
+ # DEPRECATED: Use parse_form_encoded_parameters
+ def parse_query_parameters(query_string)
+ pairs = query_string.split('&').collect do |chunk|
+ next if chunk.empty?
+ key, value = chunk.split('=', 2)
+ next if key.empty?
+ value = (value.nil? || value.empty?) ? nil : CGI.unescape(value)
+ [ CGI.unescape(key), value ]
+ end.compact
- k, v = p.split('=',2)
- v = nil if (v && v.empty?)
-
- k = CGI.unescape(k) if k
- v = CGI.unescape(v) if v
-
- unless k.include?(?[)
- parsed_params[k] = v
- else
- keys = split_key(k)
- last_key = keys.pop
- last_key = keys.pop if (use_array = last_key.empty?)
- parent = keys.inject(parsed_params) {|h, k| h[k] ||= {}}
-
- if use_array then (parent[last_key] ||= []) << v
- else parent[last_key] = v
- end
- end
- }
-
- parsed_params
+ FormEncodedPairParser.new(pairs).result
end
- # Returns the request (POST/GET) parameters in a parsed form where pairs such as "customer[address][street]" /
- # "Somewhere cool!" are translated into a full hash hierarchy, like
- # { "customer" => { "address" => { "street" => "Somewhere cool!" } } }
- def CGIMethods.parse_request_parameters(params)
- parsed_params = {}
+ # DEPRECATED: Use parse_form_encoded_parameters
+ def parse_request_parameters(params)
+ parser = FormEncodedPairParser.new
- for key, value in params
- value = [value] if key =~ /.*\[\]$/
- unless key.include?('[')
- # much faster to test for the most common case first (GET)
- # and avoid the call to build_deep_hash
- parsed_params[key] = get_typed_value(value[0])
- else
- build_deep_hash(get_typed_value(value[0]), parsed_params, get_levels(key))
+ params = params.dup
+ until params.empty?
+ for key, value in params
+ if key.blank?
+ params.delete key
+ elsif !key.include?('[')
+ # much faster to test for the most common case first (GET)
+ # and avoid the call to build_deep_hash
+ parser.result[key] = get_typed_value(value[0])
+ params.delete key
+ elsif value.is_a?(Array)
+ parser.parse(key, get_typed_value(value.shift))
+ params.delete key if value.empty?
+ else
+ raise TypeError, "Expected array, found #{value.inspect}"
+ end
end
end
- parsed_params
+ parser.result
end
- def self.parse_formatted_request_parameters(mime_type, raw_post_data)
- params = case strategy = ActionController::Base.param_parsers[mime_type]
+ def parse_formatted_request_parameters(mime_type, raw_post_data)
+ case strategy = ActionController::Base.param_parsers[mime_type]
when Proc
strategy.call(raw_post_data)
when :xml_simple
- raw_post_data.blank? ? nil :
- typecast_xml_value(XmlSimple.xml_in(raw_post_data,
- 'forcearray' => false,
- 'forcecontent' => true,
- 'keeproot' => true,
- 'contentkey' => '__content__'))
+ raw_post_data.blank? ? {} : Hash.from_xml(raw_post_data)
when :yaml
YAML.load(raw_post_data)
when :xml_node
node = XmlNode.from_xml(raw_post_data)
{ node.node_name => node }
end
-
- dasherize_keys(params || {})
- rescue Object => e
+ rescue Exception => e # YAML, XML or Ruby code block errors
{ "exception" => "#{e.message} (#{e.class})", "backtrace" => e.backtrace,
"raw_post_data" => raw_post_data, "format" => mime_type }
end
- def self.typecast_xml_value(value)
- case value
- when Hash
- if value.has_key?("__content__")
- content = translate_xml_entities(value["__content__"])
- case value["type"]
- when "integer" then content.to_i
- when "boolean" then content == "true"
- when "datetime" then Time.parse(content)
- when "date" then Date.parse(content)
- else content
- end
- else
- value.empty? ? nil : value.inject({}) do |h,(k,v)|
- h[k] = typecast_xml_value(v)
- h
- end
- end
- when Array
- value.map! { |i| typecast_xml_value(i) }
- case value.length
- when 0 then nil
- when 1 then value.first
- else value
- end
- else
- raise "can't typecast #{value.inspect}"
- end
- end
+ private
+ def get_typed_value(value)
+ case value
+ when String
+ value
+ when NilClass
+ ''
+ when Array
+ value.map { |v| get_typed_value(v) }
+ else
+ # Uploaded file provides content type and filename.
+ if value.respond_to?(:content_type) &&
+ !value.content_type.blank? &&
+ !value.original_filename.blank?
+ unless value.respond_to?(:full_original_filename)
+ class << value
+ alias_method :full_original_filename, :original_filename
- private
-
- def self.translate_xml_entities(value)
- value.gsub(/</, "<").
- gsub(/>/, ">").
- gsub(/"/, '"').
- gsub(/'/, "'").
- gsub(/&/, "&")
- end
-
- def self.dasherize_keys(params)
- case params.class.to_s
- when "Hash"
- params.inject({}) do |h,(k,v)|
- h[k.to_s.tr("-", "_")] = dasherize_keys(v)
- h
- end
- when "Array"
- params.map { |v| dasherize_keys(v) }
- else
- params
- end
- end
-
- # Splits the given key into several pieces. Example keys are 'name', 'person[name]',
- # 'person[name][first]', and 'people[]'. In each instance, an Array instance is returned.
- # 'person[name][first]' produces ['person', 'name', 'first']; 'people[]' produces ['people', '']
- def CGIMethods.split_key(key)
- if /^([^\[]+)((?:\[[^\]]*\])+)$/ =~ key
- keys = [$1]
-
- keys.concat($2[1..-2].split(']['))
- keys << '' if key[-2..-1] == '[]' # Have to add it since split will drop empty strings
-
- keys
- else
- [key]
- end
- end
-
- def CGIMethods.get_typed_value(value)
- # test most frequent case first
- if value.is_a?(String)
- value
- elsif value.respond_to?(:content_type) && ! value.content_type.blank?
- # Uploaded file
- unless value.respond_to?(:full_original_filename)
- class << value
- alias_method :full_original_filename, :original_filename
-
- # Take the basename of the upload's original filename.
- # This handles the full Windows paths given by Internet Explorer
- # (and perhaps other broken user agents) without affecting
- # those which give the lone filename.
- # The Windows regexp is adapted from Perl's File::Basename.
- def original_filename
- if md = /^(?:.*[:\\\/])?(.*)/m.match(full_original_filename)
- md.captures.first
- else
- File.basename full_original_filename
+ # Take the basename of the upload's original filename.
+ # This handles the full Windows paths given by Internet Explorer
+ # (and perhaps other broken user agents) without affecting
+ # those which give the lone filename.
+ # The Windows regexp is adapted from Perl's File::Basename.
+ def original_filename
+ if md = /^(?:.*[:\\\/])?(.*)/m.match(full_original_filename)
+ md.captures.first
+ else
+ File.basename full_original_filename
+ end
+ end
+ end
end
+
+ # Return the same value after overriding original_filename.
+ value
+
+ # Multipart values may have content type, but no filename.
+ elsif value.respond_to?(:read)
+ result = value.read
+ value.rewind
+ result
+
+ # Unknown value, neither string nor multipart.
+ else
+ raise "Unknown form value: #{value.inspect}"
end
+ end
+ end
+ end
+
+ class FormEncodedPairParser < StringScanner #:nodoc:
+ attr_reader :top, :parent, :result
+
+ def initialize(pairs = [])
+ super('')
+ @result = {}
+ pairs.each { |key, value| parse(key, value) }
+ end
+
+ KEY_REGEXP = %r{([^\[\]=&]+)}
+ BRACKETED_KEY_REGEXP = %r{\[([^\[\]=&]+)\]}
+
+ # Parse the query string
+ def parse(key, value)
+ self.string = key
+ @top, @parent = result, nil
+
+ # First scan the bare key
+ key = scan(KEY_REGEXP) or return
+ key = post_key_check(key)
+
+ # Then scan as many nestings as present
+ until eos?
+ r = scan(BRACKETED_KEY_REGEXP) or return
+ key = self[1]
+ key = post_key_check(key)
+ end
+
+ bind(key, value)
+ end
+
+ private
+ # After we see a key, we must look ahead to determine our next action. Cases:
+ #
+ # [] follows the key. Then the value must be an array.
+ # = follows the key. (A value comes next)
+ # & or the end of string follows the key. Then the key is a flag.
+ # otherwise, a hash follows the key.
+ def post_key_check(key)
+ if scan(/\[\]/) # a[b][] indicates that b is an array
+ container(key, Array)
+ nil
+ elsif check(/\[[^\]]/) # a[b] indicates that a is a hash
+ container(key, Hash)
+ nil
+ else # End of key? We do nothing.
+ key
+ end
+ end
+
+ # Add a container to the stack.
+ #
+ def container(key, klass)
+ type_conflict! klass, top[key] if top.is_a?(Hash) && top.key?(key) && ! top[key].is_a?(klass)
+ value = bind(key, klass.new)
+ type_conflict! klass, value unless value.is_a?(klass)
+ push(value)
+ end
+
+ # Push a value onto the 'stack', which is actually only the top 2 items.
+ def push(value)
+ @parent, @top = @top, value
+ end
+
+ # Bind a key (which may be nil for items in an array) to the provided value.
+ def bind(key, value)
+ if top.is_a? Array
+ if key
+ if top[-1].is_a?(Hash) && ! top[-1].key?(key)
+ top[-1][key] = value
+ else
+ top << {key => value}.with_indifferent_access
+ push top.last
+ end
+ else
+ top << value
end
+ elsif top.is_a? Hash
+ key = CGI.unescape(key)
+ parent << (@top = {}) if top.key?(key) && parent.is_a?(Array)
+ return top[key] ||= value
+ else
+ raise ArgumentError, "Don't know what to do: top is #{top.inspect}"
end
- # Return the same value after overriding original_filename.
- value
-
- elsif value.respond_to?(:read)
- # Value as part of a multipart request
- value.read
- elsif value.class == Array
- value.collect { |v| CGIMethods.get_typed_value(v) }
- else
- # other value (neither string nor a multipart request)
- value.to_s
+ return value
end
- end
-
- PARAMS_HASH_RE = /^([^\[]+)(\[.*\])?(.)?.*$/
- def CGIMethods.get_levels(key)
- all, main, bracketed, trailing = PARAMS_HASH_RE.match(key).to_a
- if main.nil?
- []
- elsif trailing
- [key]
- elsif bracketed
- [main] + bracketed.slice(1...-1).split('][')
- else
- [main]
- end
- end
-
- def CGIMethods.build_deep_hash(value, hash, levels)
- if levels.length == 0
- value
- elsif hash.nil?
- { levels.first => CGIMethods.build_deep_hash(value, nil, levels[1..-1]) }
- else
- hash.update({ levels.first => CGIMethods.build_deep_hash(value, hash[levels.first], levels[1..-1]) })
+
+ def type_conflict!(klass, value)
+ raise TypeError,
+ "Conflicting types for parameter containers. " +
+ "Expected an instance of #{klass}, but found an instance of #{value.class}. " +
+ "This can be caused by passing Array and Hash based paramters qs[]=value&qs[key]=value. "
end
+
end
end
diff --git a/vendor/rails/actionpack/lib/action_controller/cgi_ext/raw_post_data_fix.rb b/vendor/rails/actionpack/lib/action_controller/cgi_ext/raw_post_data_fix.rb
index 3057dba1..4c124cb2 100644
--- a/vendor/rails/actionpack/lib/action_controller/cgi_ext/raw_post_data_fix.rb
+++ b/vendor/rails/actionpack/lib/action_controller/cgi_ext/raw_post_data_fix.rb
@@ -1,27 +1,48 @@
class CGI #:nodoc:
- # Add @request.env['RAW_POST_DATA'] for the vegans.
module QueryExtension
# Initialize the data from the query.
#
# Handles multipart forms (in particular, forms that involve file uploads).
# Reads query parameters in the @params field, and cookies into @cookies.
- def initialize_query()
+ def initialize_query
@cookies = CGI::Cookie::parse(env_table['HTTP_COOKIE'] || env_table['COOKIE'])
- #fix some strange request environments
+ # Fix some strange request environments.
if method = env_table['REQUEST_METHOD']
method = method.to_s.downcase.intern
else
method = :get
end
- if method == :post && (boundary = multipart_form_boundary)
- @multipart = true
- @params = read_multipart(boundary, Integer(env_table['CONTENT_LENGTH']))
- else
- @multipart = false
- @params = CGI::parse(read_query_params(method) || "")
+ # POST assumes missing Content-Type is application/x-www-form-urlencoded.
+ content_type = env_table['CONTENT_TYPE']
+ if content_type.blank? && method == :post
+ content_type = 'application/x-www-form-urlencoded'
end
+
+ # Force content length to zero if missing.
+ content_length = env_table['CONTENT_LENGTH'].to_i
+
+ # Set multipart to false by default.
+ @multipart = false
+
+ # POST and PUT may have params in entity body. If content type is
+ # missing for POST, assume urlencoded. If content type is missing
+ # for PUT, don't assume anything and don't parse the parameters:
+ # it's likely binary data.
+ #
+ # The other HTTP methods have their params in the query string.
+ if method == :post || method == :put
+ if boundary = extract_multipart_form_boundary(content_type)
+ @multipart = true
+ @params = read_multipart(boundary, content_length)
+ elsif content_type.blank? || content_type !~ %r{application/x-www-form-urlencoded}i
+ read_params(method, content_length)
+ @params = {}
+ end
+ end
+
+ @params ||= CGI.parse(read_params(method, content_length))
end
private
@@ -29,16 +50,16 @@ class CGI #:nodoc:
MULTIPART_FORM_BOUNDARY_RE = %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)\"?|n #"
end
- def multipart_form_boundary
- MULTIPART_FORM_BOUNDARY_RE.match(env_table['CONTENT_TYPE']).to_a.pop
+ def extract_multipart_form_boundary(content_type)
+ MULTIPART_FORM_BOUNDARY_RE.match(content_type).to_a.pop
end
if defined? MOD_RUBY
- def read_params_from_query
+ def read_query
Apache::request.args || ''
end
else
- def read_params_from_query
+ def read_query
# fixes CGI querystring parsing for lighttpd
env_qs = env_table['QUERY_STRING']
if env_qs.blank? && !(uri = env_table['REQUEST_URI']).blank?
@@ -49,25 +70,25 @@ class CGI #:nodoc:
end
end
- def read_params_from_post
+ def read_body(content_length)
stdinput.binmode if stdinput.respond_to?(:binmode)
- content = stdinput.read(Integer(env_table['CONTENT_LENGTH'])) || ''
- # fix for Safari Ajax postings that always append \000
+ content = stdinput.read(content_length) || ''
+ # Fix for Safari Ajax postings that always append \000
content.chop! if content[-1] == 0
- content.gsub! /&_=$/, ''
+ content.gsub!(/&_=$/, '')
env_table['RAW_POST_DATA'] = content.freeze
end
- def read_query_params(method)
+ def read_params(method, content_length)
case method
when :get
- read_params_from_query
+ read_query
when :post, :put
- read_params_from_post
+ read_body(content_length)
when :cmd
read_from_cmdline
- else # when :head, :delete, :options
- read_params_from_query
+ else # :head, :delete, :options, :trace, :connect
+ read_query
end
end
end # module QueryExtension
diff --git a/vendor/rails/actionpack/lib/action_controller/cgi_process.rb b/vendor/rails/actionpack/lib/action_controller/cgi_process.rb
index 09a6000b..49c5680f 100644
--- a/vendor/rails/actionpack/lib/action_controller/cgi_process.rb
+++ b/vendor/rails/actionpack/lib/action_controller/cgi_process.rb
@@ -8,13 +8,13 @@ module ActionController #:nodoc:
# sessions (large performance increase if sessions are not needed). The session_options are the same as for CGI::Session:
#
# * :database_manager - standard options are CGI::Session::FileStore, CGI::Session::MemoryStore, and CGI::Session::PStore
- # (default). Additionally, there is CGI::Session::DRbStore and CGI::Session::ActiveRecordStore. Read more about these in
+ # (default). Additionally, there is CGI::Session::DRbStore and CGI::Session::ActiveRecordStore. Read more about these in
# lib/action_controller/session.
# * :session_key - the parameter name used for the session id. Defaults to '_session_id'.
# * :session_id - the session id to use. If not provided, then it is retrieved from the +session_key+ parameter
# of the request, or automatically generated for a new session.
# * :new_session - if true, force creation of a new session. If not set, a new session is only created if none currently
- # exists. If false, a new session is never created, and if none currently exists and the +session_id+ option is not set,
+ # exists. If false, a new session is never created, and if none currently exists and the +session_id+ option is not set,
# an ArgumentError is raised.
# * :session_expires - the time the current session expires, as a +Time+ object. If not set, the session will continue
# indefinitely.
@@ -22,10 +22,10 @@ module ActionController #:nodoc:
# server.
# * :session_secure - if +true+, this session will only work over HTTPS.
# * :session_path - the path for which this session applies. Defaults to the directory of the CGI script.
- def self.process_cgi(cgi = CGI.new, session_options = {})
+ def self.process_cgi(cgi = CGI.new, session_options = {})
new.process_cgi(cgi, session_options)
end
-
+
def process_cgi(cgi, session_options = {}) #:nodoc:
process(CgiRequest.new(cgi, session_options), CgiResponse.new(cgi)).out
end
@@ -51,7 +51,7 @@ module ActionController #:nodoc:
if (qs = @cgi.query_string) && !qs.empty?
qs
elsif uri = @env['REQUEST_URI']
- parts = uri.split('?')
+ parts = uri.split('?')
parts.shift
parts.join('?')
else
@@ -60,7 +60,8 @@ module ActionController #:nodoc:
end
def query_parameters
- (qs = self.query_string).empty? ? {} : CGIMethods.parse_query_parameters(qs)
+ @query_parameters ||=
+ (qs = self.query_string).empty? ? {} : CGIMethods.parse_query_parameters(qs)
end
def request_parameters
@@ -71,7 +72,7 @@ module ActionController #:nodoc:
CGIMethods.parse_request_parameters(@cgi.params)
end
end
-
+
def cookies
@cgi.cookies.freeze
end
@@ -101,15 +102,26 @@ module ActionController #:nodoc:
end
def session
- unless @session
+ unless defined?(@session)
if @session_options == false
@session = Hash.new
else
stale_session_check! do
- if session_options_with_string_keys['new_session'] == true
- @session = new_session
- else
- @session = CGI::Session.new(@cgi, session_options_with_string_keys)
+ case value = session_options_with_string_keys['new_session']
+ when true
+ @session = new_session
+ when false
+ begin
+ @session = CGI::Session.new(@cgi, session_options_with_string_keys)
+ # CGI::Session raises ArgumentError if 'new_session' == false
+ # and no session cookie or query param is present.
+ rescue ArgumentError
+ @session = Hash.new
+ end
+ when nil
+ @session = CGI::Session.new(@cgi, session_options_with_string_keys)
+ else
+ raise ArgumentError, "Invalid new_session option: #{value}"
end
@session['__valid_session']
end
@@ -119,7 +131,7 @@ module ActionController #:nodoc:
end
def reset_session
- @session.delete if CGI::Session === @session
+ @session.delete if defined?(@session) && @session.is_a?(CGI::Session)
@session = new_session
end
@@ -141,11 +153,11 @@ module ActionController #:nodoc:
def stale_session_check!
yield
rescue ArgumentError => argument_error
- if argument_error.message =~ %r{undefined class/module (\w+)}
+ if argument_error.message =~ %r{undefined class/module ([\w:]+)}
begin
Module.const_missing($1)
rescue LoadError, NameError => const_error
- raise ActionController::SessionRestoreError, < e
- # lost connection to the FCGI process -- ignore the output, then
+ rescue Errno::EPIPE, Errno::ECONNRESET
+ # lost connection to parent process, ignore output
end
end
private
- def convert_content_type!(headers)
- if header = headers.delete("Content-Type")
- headers["type"] = header
+ def convert_content_type!
+ if content_type = @headers.delete("Content-Type")
+ @headers["type"] = content_type
end
- if header = headers.delete("Content-type")
- headers["type"] = header
+ if content_type = @headers.delete("Content-type")
+ @headers["type"] = content_type
end
- if header = headers.delete("content-type")
- headers["type"] = header
+ if content_type = @headers.delete("content-type")
+ @headers["type"] = content_type
end
end
+
+ # Don't set the Content-Length for block-based bodies as that would mean reading it all into memory. Not nice
+ # for, say, a 2GB streaming file.
+ def set_content_length!
+ @headers["Content-Length"] = @body.size unless @body.respond_to?(:call)
+ end
end
end
diff --git a/vendor/rails/actionpack/lib/action_controller/components.rb b/vendor/rails/actionpack/lib/action_controller/components.rb
index 75005daa..5d5a48eb 100644
--- a/vendor/rails/actionpack/lib/action_controller/components.rb
+++ b/vendor/rails/actionpack/lib/action_controller/components.rb
@@ -50,14 +50,9 @@ module ActionController #:nodoc:
base.send :attr_accessor, :parent_controller
base.class_eval do
- alias_method :process_cleanup_without_components, :process_cleanup
- alias_method :process_cleanup, :process_cleanup_with_components
-
- alias_method :set_session_options_without_components, :set_session_options
- alias_method :set_session_options, :set_session_options_with_components
-
- alias_method :flash_without_components, :flash
- alias_method :flash, :flash_with_components
+ alias_method_chain :process_cleanup, :components
+ alias_method_chain :set_session_options, :components
+ alias_method_chain :flash, :components
alias_method :component_request?, :parent_controller
end
@@ -80,11 +75,13 @@ module ActionController #:nodoc:
# will also use /code/weblog/components as template root
# and find templates in /code/weblog/components/admin/parties/users/
def uses_component_template_root
- path_of_calling_controller = File.dirname(caller[0].split(/:\d+:/).first)
- path_of_controller_root = path_of_calling_controller.sub(/#{controller_path.split("/")[0..-2]}$/, "") # " (for ruby-mode)
+ path_of_calling_controller = File.dirname(caller[1].split(/:\d+:/, 2).first)
+ path_of_controller_root = path_of_calling_controller.sub(/#{Regexp.escape(File.dirname(controller_path))}$/, "")
self.template_root = path_of_controller_root
end
+
+ deprecate :uses_component_template_root => 'Components are deprecated and will be removed in Rails 2.0.'
end
module InstanceMethods
@@ -116,27 +113,26 @@ module ActionController #:nodoc:
end
def flash_with_components(refresh = false) #:nodoc:
- if @flash.nil? || refresh
- @flash =
- if @parent_controller
+ if !defined?(@_flash) || refresh
+ @_flash =
+ if defined?(@parent_controller)
@parent_controller.flash
else
flash_without_components
end
end
-
- @flash
+ @_flash
end
private
def component_response(options, reuse_response)
klass = component_class(options)
request = request_for_component(klass.controller_name, options)
- response = reuse_response ? @response : @response.dup
+ new_response = reuse_response ? response : response.dup
- klass.process_with_components(request, response, self)
+ klass.process_with_components(request, new_response, self)
end
-
+
# determine the controller class for the component request
def component_class(options)
if controller = options[:controller]
@@ -145,22 +141,22 @@ module ActionController #:nodoc:
self.class
end
end
-
+
# Create a new request object based on the current request.
# The new request inherits the session from the current request,
# bypassing any session options set for the component controller's class
def request_for_component(controller_name, options)
- request = @request.dup
- request.session = @request.session
-
- request.instance_variable_set(
+ new_request = request.dup
+ new_request.session = request.session
+
+ new_request.instance_variable_set(
:@parameters,
(options[:params] || {}).with_indifferent_access.update(
"controller" => controller_name, "action" => options[:action], "id" => options[:id]
)
)
-
- request
+
+ new_request
end
def component_logging(options)
diff --git a/vendor/rails/actionpack/lib/action_controller/cookies.rb b/vendor/rails/actionpack/lib/action_controller/cookies.rb
index 5785805b..52423aa6 100644
--- a/vendor/rails/actionpack/lib/action_controller/cookies.rb
+++ b/vendor/rails/actionpack/lib/action_controller/cookies.rb
@@ -4,13 +4,14 @@ module ActionController #:nodoc:
# itself back -- just the value it holds). Examples for writing:
#
# cookies[:user_name] = "david" # => Will set a simple session cookie
- # cookies[:login] = { :value => "XJ-122", :expires => Time.now + 360} # => Will set a cookie that expires in 1 hour
- #
+ # cookies[:login] = { :value => "XJ-122", :expires => 1.hour.from_now }
+ # # => Will set a cookie that expires in 1 hour
+ #
# Examples for reading:
#
# cookies[:user_name] # => "david"
# cookies.size # => 2
- #
+ #
# Example for deleting:
#
# cookies.delete :user_name
@@ -32,13 +33,13 @@ module ActionController #:nodoc:
# Deprecated cookie writer method
def cookie(*options)
- @response.headers["cookie"] << CGI::Cookie.new(*options)
+ response.headers['cookie'] << CGI::Cookie.new(*options)
end
end
-
+
class CookieJar < Hash #:nodoc:
def initialize(controller)
- @controller, @cookies = controller, controller.instance_variable_get("@cookies")
+ @controller, @cookies = controller, controller.request.cookies
super()
update(@cookies)
end
@@ -48,7 +49,7 @@ module ActionController #:nodoc:
def [](name)
@cookies[name.to_s].value.first if @cookies[name.to_s] && @cookies[name.to_s].respond_to?(:value)
end
-
+
def []=(name, options)
if options.is_a?(Hash)
options = options.inject({}) { |options, pair| options[pair.first.to_s] = pair.last; options }
@@ -56,10 +57,10 @@ module ActionController #:nodoc:
else
options = { "name" => name.to_s, "value" => options }
end
-
+
set_cookie(options)
end
-
+
# Removes the cookie on the client machine by setting the value to an empty string
# and setting its expiration date into the past
def delete(name)
diff --git a/vendor/rails/actionpack/lib/action_controller/filters.rb b/vendor/rails/actionpack/lib/action_controller/filters.rb
index 01a4b9fb..3290deff 100644
--- a/vendor/rails/actionpack/lib/action_controller/filters.rb
+++ b/vendor/rails/actionpack/lib/action_controller/filters.rb
@@ -5,19 +5,14 @@ module ActionController #:nodoc:
base.send(:include, ActionController::Filters::InstanceMethods)
end
- # Filters enable controllers to run shared pre and post processing code for its actions. These filters can be used to do
- # authentication, caching, or auditing before the intended action is performed. Or to do localization or output
- # compression after the action has been performed.
- #
- # Filters have access to the request, response, and all the instance variables set by other filters in the chain
- # or by the action (in the case of after filters). Additionally, it's possible for a pre-processing before_filter
- # to halt the processing before the intended action is processed by returning false or performing a redirect or render.
- # This is especially useful for filters like authentication where you're not interested in allowing the action to be
- # performed if the proper credentials are not in order.
+ # Filters enable controllers to run shared pre and post processing code for its actions. These filters can be used to do
+ # authentication, caching, or auditing before the intended action is performed. Or to do localization or output
+ # compression after the action has been performed. Filters have access to the request, response, and all the instance
+ # variables set by other filters in the chain or by the action (in the case of after filters).
#
# == Filter inheritance
#
- # Controller inheritance hierarchies share filters downwards, but subclasses can also add new filters without
+ # Controller inheritance hierarchies share filters downwards, but subclasses can also add or skip filters without
# affecting the superclass. For example:
#
# class BankController < ActionController::Base
@@ -39,7 +34,7 @@ module ActionController #:nodoc:
# end
#
# Now any actions performed on the BankController will have the audit method called before. On the VaultController,
- # first the audit method is called, then the verify_credentials method. If the audit method returns false, then
+ # first the audit method is called, then the verify_credentials method. If the audit method returns false, then
# verify_credentials and the intended action are never called.
#
# == Filter types
@@ -64,7 +59,7 @@ module ActionController #:nodoc:
# The filter method is passed the controller instance and is hence granted access to all aspects of the controller and can
# manipulate them as it sees fit.
#
- # The inline method (using a proc) can be used to quickly do something small that doesn't require a lot of explanation.
+ # The inline method (using a proc) can be used to quickly do something small that doesn't require a lot of explanation.
# Or just as a quick test. It works like this:
#
# class WeblogController < ActionController::Base
@@ -76,6 +71,9 @@ module ActionController #:nodoc:
# session, template, and assigns. Note: The inline method doesn't strictly have to be a block; any object that responds to call
# and returns 1 or -1 on arity will do (such as a Proc or an Method object).
#
+ # Please note that around_filters function a little differently than the normal before and after filters with regard to filter
+ # types. Please see the section dedicated to around_filters below.
+ #
# == Filter chain ordering
#
# Using before_filter and after_filter appends the specified filters to the existing chain. That's usually
@@ -83,14 +81,14 @@ module ActionController #:nodoc:
# can use prepend_before_filter and prepend_after_filter. Filters added by these methods will be put at the
# beginning of their respective chain and executed before the rest. For example:
#
- # class ShoppingController
+ # class ShoppingController < ActionController::Base
# before_filter :verify_open_shop
#
- # class CheckoutController
+ # class CheckoutController < ShoppingController
# prepend_before_filter :ensure_items_in_cart, :ensure_items_in_stock
#
# The filter chain for the CheckoutController is now :ensure_items_in_cart, :ensure_items_in_stock,
- # :verify_open_shop. So if either of the ensure filters return false, we'll never get around to see if the shop
+ # :verify_open_shop. So if either of the ensure filters return false, we'll never get around to see if the shop
# is open or not.
#
# You may pass multiple filter arguments of each type as well as a filter block.
@@ -98,250 +96,511 @@ module ActionController #:nodoc:
#
# == Around filters
#
- # In addition to the individual before and after filters, it's also possible to specify that a single object should handle
- # both the before and after call. That's especially useful when you need to keep state active between the before and after,
- # such as the example of a benchmark filter below:
- #
- # class WeblogController < ActionController::Base
- # around_filter BenchmarkingFilter.new
- #
- # # Before this action is performed, BenchmarkingFilter#before(controller) is executed
- # def index
+ # Around filters wrap an action, executing code both before and after.
+ # They may be declared as method references, blocks, or objects responding
+ # to #filter or to both #before and #after.
+ #
+ # To use a method as an around_filter, pass a symbol naming the Ruby method.
+ # Yield (or block.call) within the method to run the action.
+ #
+ # around_filter :catch_exceptions
+ #
+ # private
+ # def catch_exceptions
+ # yield
+ # rescue => exception
+ # logger.debug "Caught exception! #{exception}"
+ # raise
# end
- # # After this action has been performed, BenchmarkingFilter#after(controller) is executed
+ #
+ # To use a block as an around_filter, pass a block taking as args both
+ # the controller and the action block. You can't call yield directly from
+ # an around_filter block; explicitly call the action block instead:
+ #
+ # around_filter do |controller, action|
+ # logger.debug "before #{controller.action_name}"
+ # action.call
+ # logger.debug "after #{controller.action_name}"
# end
#
+ # To use a filter object with around_filter, pass an object responding
+ # to :filter or both :before and :after. With a filter method, yield to
+ # the block as above:
+ #
+ # around_filter BenchmarkingFilter
+ #
# class BenchmarkingFilter
- # def initialize
- # @runtime
- # end
- #
- # def before
- # start_timer
- # end
- #
- # def after
- # stop_timer
- # report_result
+ # def self.filter(controller, &block)
+ # Benchmark.measure(&block)
# end
# end
#
+ # With before and after methods:
+ #
+ # around_filter Authorizer.new
+ #
+ # class Authorizer
+ # # This will run before the action. Returning false aborts the action.
+ # def before(controller)
+ # if user.authorized?
+ # return true
+ # else
+ # redirect_to login_url
+ # return false
+ # end
+ # end
+ #
+ # # This will run after the action if and only if before returned true.
+ # def after(controller)
+ # end
+ # end
+ #
+ # If the filter has before and after methods, the before method will be
+ # called before the action. If before returns false, the filter chain is
+ # halted and after will not be run. See Filter Chain Halting below for
+ # an example.
+ #
# == Filter chain skipping
#
- # Some times its convenient to specify a filter chain in a superclass that'll hold true for the majority of the
- # subclasses, but not necessarily all of them. The subclasses that behave in exception can then specify which filters
- # they would like to be relieved of. Examples
+ # Declaring a filter on a base class conveniently applies to its subclasses,
+ # but sometimes a subclass should skip some of its superclass' filters:
#
# class ApplicationController < ActionController::Base
# before_filter :authenticate
+ # around_filter :catch_exceptions
# end
#
# class WeblogController < ApplicationController
- # # will run the :authenticate filter
+ # # Will run the :authenticate and :catch_exceptions filters.
# end
#
# class SignupController < ApplicationController
- # # will not run the :authenticate filter
+ # # Skip :authenticate, run :catch_exceptions.
# skip_before_filter :authenticate
# end
#
+ # class ProjectsController < ApplicationController
+ # # Skip :catch_exceptions, run :authenticate.
+ # skip_filter :catch_exceptions
+ # end
+ #
+ # class ClientsController < ApplicationController
+ # # Skip :catch_exceptions and :authenticate unless action is index.
+ # skip_filter :catch_exceptions, :authenticate, :except => :index
+ # end
+ #
# == Filter conditions
#
- # Filters can be limited to run for only specific actions. This can be expressed either by listing the actions to
- # exclude or the actions to include when executing the filter. Available conditions are +:only+ or +:except+, both
- # of which accept an arbitrary number of method references. For example:
+ # Filters may be limited to specific actions by declaring the actions to
+ # include or exclude. Both options accept single actions (:only => :index)
+ # or arrays of actions (:except => [:foo, :bar]).
#
# class Journal < ActionController::Base
- # # only require authentication if the current action is edit or delete
- # before_filter :authorize, :only => [ :edit, :delete ]
- #
+ # # Require authentication for edit and delete.
+ # before_filter :authorize, :only => [:edit, :delete]
+ #
+ # # Passing options to a filter with a block.
+ # around_filter(:except => :index) do |controller, action_block|
+ # results = Profiler.run(&action_block)
+ # controller.response.sub! "", "#{results}"
+ # end
+ #
# private
# def authorize
- # # redirect to login unless authenticated
+ # # Redirect to login unless authenticated.
# end
# end
- #
- # When setting conditions on inline method (proc) filters the condition must come first and be placed in parentheses.
#
- # class UserPreferences < ActionController::Base
- # before_filter(:except => :new) { # some proc ... }
- # # ...
- # end
+ # == Filter Chain Halting
#
+ # before_filter and around_filter may halt the request
+ # before controller action is run. This is useful, for example, to deny
+ # access to unauthenticated users or to redirect from http to https.
+ # Simply return false from the filter or call render or redirect.
+ #
+ # Around filters halt the request unless the action block is called.
+ # Given these filters
+ # after_filter :after
+ # around_filter :around
+ # before_filter :before
+ #
+ # The filter chain will look like:
+ #
+ # ...
+ # . \
+ # . #around (code before yield)
+ # . . \
+ # . . #before (actual filter code is run)
+ # . . . \
+ # . . . execute controller action
+ # . . . /
+ # . . ...
+ # . . /
+ # . #around (code after yield)
+ # . /
+ # #after (actual filter code is run)
+ #
+ # If #around returns before yielding, only #after will be run. The #before
+ # filter and controller action will not be run. If #before returns false,
+ # the second half of #around and all of #after will still run but the
+ # action will not.
module ClassMethods
- # The passed filters will be appended to the array of filters that's run _before_ actions
- # on this controller are performed.
+ # The passed filters will be appended to the filter_chain and
+ # will execute before the action on this controller is performed.
def append_before_filter(*filters, &block)
- conditions = extract_conditions!(filters)
- filters << block if block_given?
- add_action_conditions(filters, conditions)
- append_filter_to_chain('before', filters)
+ append_filter_to_chain(filters, :before, &block)
end
- # The passed filters will be prepended to the array of filters that's run _before_ actions
- # on this controller are performed.
+ # The passed filters will be prepended to the filter_chain and
+ # will execute before the action on this controller is performed.
def prepend_before_filter(*filters, &block)
- conditions = extract_conditions!(filters)
- filters << block if block_given?
- add_action_conditions(filters, conditions)
- prepend_filter_to_chain('before', filters)
+ prepend_filter_to_chain(filters, :before, &block)
end
- # Short-hand for append_before_filter since that's the most common of the two.
+ # Shorthand for append_before_filter since it's the most common.
alias :before_filter :append_before_filter
-
- # The passed filters will be appended to the array of filters that's run _after_ actions
- # on this controller are performed.
+
+ # The passed filters will be appended to the array of filters
+ # that run _after_ actions on this controller are performed.
def append_after_filter(*filters, &block)
- conditions = extract_conditions!(filters)
- filters << block if block_given?
- add_action_conditions(filters, conditions)
- append_filter_to_chain('after', filters)
+ prepend_filter_to_chain(filters, :after, &block)
end
- # The passed filters will be prepended to the array of filters that's run _after_ actions
- # on this controller are performed.
+ # The passed filters will be prepended to the array of filters
+ # that run _after_ actions on this controller are performed.
def prepend_after_filter(*filters, &block)
- conditions = extract_conditions!(filters)
- filters << block if block_given?
- add_action_conditions(filters, conditions)
- prepend_filter_to_chain("after", filters)
+ append_filter_to_chain(filters, :after, &block)
end
- # Short-hand for append_after_filter since that's the most common of the two.
+ # Shorthand for append_after_filter since it's the most common.
alias :after_filter :append_after_filter
-
- # The passed filters will have their +before+ method appended to the array of filters that's run both before actions
- # on this controller are performed and have their +after+ method prepended to the after actions. The filter objects must all
- # respond to both +before+ and +after+. So if you do append_around_filter A.new, B.new, the callstack will look like:
+
+
+ # If you append_around_filter A.new, B.new, the filter chain looks like
#
# B#before
# A#before
+ # # run the action
# A#after
# B#after
- def append_around_filter(*filters)
- conditions = extract_conditions!(filters)
- for filter in filters.flatten
- ensure_filter_responds_to_before_and_after(filter)
- append_before_filter(conditions || {}) { |c| filter.before(c) }
- prepend_after_filter(conditions || {}) { |c| filter.after(c) }
+ #
+ # With around filters which yield to the action block, #before and #after
+ # are the code before and after the yield.
+ def append_around_filter(*filters, &block)
+ filters, conditions = extract_conditions(filters, &block)
+ filters.map { |f| proxy_before_and_after_filter(f) }.each do |filter|
+ append_filter_to_chain([filter, conditions])
end
- end
+ end
- # The passed filters will have their +before+ method prepended to the array of filters that's run both before actions
- # on this controller are performed and have their +after+ method appended to the after actions. The filter objects must all
- # respond to both +before+ and +after+. So if you do prepend_around_filter A.new, B.new, the callstack will look like:
+ # If you prepend_around_filter A.new, B.new, the filter chain looks like:
#
# A#before
# B#before
+ # # run the action
# B#after
# A#after
- def prepend_around_filter(*filters)
- for filter in filters.flatten
- ensure_filter_responds_to_before_and_after(filter)
- prepend_before_filter { |c| filter.before(c) }
- append_after_filter { |c| filter.after(c) }
+ #
+ # With around filters which yield to the action block, #before and #after
+ # are the code before and after the yield.
+ def prepend_around_filter(*filters, &block)
+ filters, conditions = extract_conditions(filters, &block)
+ filters.map { |f| proxy_before_and_after_filter(f) }.each do |filter|
+ prepend_filter_to_chain([filter, conditions])
end
- end
+ end
- # Short-hand for append_around_filter since that's the most common of the two.
+ # Shorthand for append_around_filter since it's the most common.
alias :around_filter :append_around_filter
-
- # Removes the specified filters from the +before+ filter chain. Note that this only works for skipping method-reference
+
+ # Removes the specified filters from the +before+ filter chain. Note that this only works for skipping method-reference
# filters, not procs. This is especially useful for managing the chain in inheritance hierarchies where only one out
# of many sub-controllers need a different hierarchy.
#
- # You can control the actions to skip the filter for with the :only and :except options,
+ # You can control the actions to skip the filter for with the :only and :except options,
# just like when you apply the filters.
def skip_before_filter(*filters)
- if conditions = extract_conditions!(filters)
- remove_contradicting_conditions!(filters, conditions)
- conditions[:only], conditions[:except] = conditions[:except], conditions[:only]
- add_action_conditions(filters, conditions)
- else
- for filter in filters.flatten
- write_inheritable_attribute("before_filters", read_inheritable_attribute("before_filters") - [ filter ])
- end
- end
+ skip_filter_in_chain(*filters, &:before?)
end
- # Removes the specified filters from the +after+ filter chain. Note that this only works for skipping method-reference
+ # Removes the specified filters from the +after+ filter chain. Note that this only works for skipping method-reference
# filters, not procs. This is especially useful for managing the chain in inheritance hierarchies where only one out
# of many sub-controllers need a different hierarchy.
#
- # You can control the actions to skip the filter for with the :only and :except options,
+ # You can control the actions to skip the filter for with the :only and :except options,
# just like when you apply the filters.
def skip_after_filter(*filters)
- if conditions = extract_conditions!(filters)
- remove_contradicting_conditions!(filters, conditions)
- conditions[:only], conditions[:except] = conditions[:except], conditions[:only]
- add_action_conditions(filters, conditions)
- else
- for filter in filters.flatten
- write_inheritable_attribute("after_filters", read_inheritable_attribute("after_filters") - [ filter ])
- end
- end
+ skip_filter_in_chain(*filters, &:after?)
end
-
+
+ # Removes the specified filters from the filter chain. This only works for method reference (symbol)
+ # filters, not procs. This method is different from skip_after_filter and skip_before_filter in that
+ # it will match any before, after or yielding around filter.
+ #
+ # You can control the actions to skip the filter for with the :only and :except options,
+ # just like when you apply the filters.
+ def skip_filter(*filters)
+ skip_filter_in_chain(*filters)
+ end
+
+ # Returns an array of Filter objects for this controller.
+ def filter_chain
+ read_inheritable_attribute("filter_chain") || []
+ end
+
# Returns all the before filters for this class and all its ancestors.
+ # This method returns the actual filter that was assigned in the controller to maintain existing functionality.
def before_filters #:nodoc:
- @before_filters ||= read_inheritable_attribute("before_filters") || []
+ filter_chain.select(&:before?).map(&:filter)
end
-
+
# Returns all the after filters for this class and all its ancestors.
+ # This method returns the actual filter that was assigned in the controller to maintain existing functionality.
def after_filters #:nodoc:
- @after_filters ||= read_inheritable_attribute("after_filters") || []
+ filter_chain.select(&:after?).map(&:filter)
end
-
+
# Returns a mapping between filters and the actions that may run them.
def included_actions #:nodoc:
- @included_actions ||= read_inheritable_attribute("included_actions") || {}
+ read_inheritable_attribute("included_actions") || {}
end
-
+
# Returns a mapping between filters and actions that may not run them.
def excluded_actions #:nodoc:
- @excluded_actions ||= read_inheritable_attribute("excluded_actions") || {}
+ read_inheritable_attribute("excluded_actions") || {}
end
-
- private
- def append_filter_to_chain(condition, filters)
- write_inheritable_array("#{condition}_filters", filters)
+
+ # Find a filter in the filter_chain where the filter method matches the _filter_ param
+ # and (optionally) the passed block evaluates to true (mostly used for testing before?
+ # and after? on the filter). Useful for symbol filters.
+ #
+ # The object of type Filter is passed to the block when yielded, not the filter itself.
+ def find_filter(filter, &block) #:nodoc:
+ filter_chain.select { |f| f.filter == filter && (!block_given? || yield(f)) }.first
+ end
+
+ # Returns true if the filter is excluded from the given action
+ def filter_excluded_from_action?(filter,action) #:nodoc:
+ if (ia = included_actions[filter]) && !ia.empty?
+ !ia.include?(action)
+ else
+ (excluded_actions[filter] || []).include?(action)
+ end
+ end
+
+ # Filter class is an abstract base class for all filters. Handles all of the included/excluded actions but
+ # contains no logic for calling the actual filters.
+ class Filter #:nodoc:
+ attr_reader :filter, :included_actions, :excluded_actions
+
+ def initialize(filter)
+ @filter = filter
end
- def prepend_filter_to_chain(condition, filters)
- old_filters = read_inheritable_attribute("#{condition}_filters") || []
- write_inheritable_attribute("#{condition}_filters", filters + old_filters)
+ def before?
+ false
end
- def ensure_filter_responds_to_before_and_after(filter)
- unless filter.respond_to?(:before) && filter.respond_to?(:after)
- raise ActionControllerError, "Filter object must respond to both before and after"
+ def after?
+ false
+ end
+
+ def around?
+ true
+ end
+
+ def call(controller, &block)
+ raise(ActionControllerError, 'No filter type: Nothing to do here.')
+ end
+ end
+
+ # Abstract base class for filter proxies. FilterProxy objects are meant to mimic the behaviour of the old
+ # before_filter and after_filter by moving the logic into the filter itself.
+ class FilterProxy < Filter #:nodoc:
+ def filter
+ @filter.filter
+ end
+
+ def around?
+ false
+ end
+ end
+
+ class BeforeFilterProxy < FilterProxy #:nodoc:
+ def before?
+ true
+ end
+
+ def call(controller, &block)
+ if false == @filter.call(controller) # must only stop if equal to false. only filters returning false are halted.
+ controller.halt_filter_chain(@filter, :returned_false)
+ else
+ yield
+ end
+ end
+ end
+
+ class AfterFilterProxy < FilterProxy #:nodoc:
+ def after?
+ true
+ end
+
+ def call(controller, &block)
+ yield
+ @filter.call(controller)
+ end
+ end
+
+ class SymbolFilter < Filter #:nodoc:
+ def call(controller, &block)
+ controller.send(@filter, &block)
+ end
+ end
+
+ class ProcFilter < Filter #:nodoc:
+ def call(controller)
+ @filter.call(controller)
+ rescue LocalJumpError # a yield from a proc... no no bad dog.
+ raise(ActionControllerError, 'Cannot yield from a Proc type filter. The Proc must take two arguments and execute #call on the second argument.')
+ end
+ end
+
+ class ProcWithCallFilter < Filter #:nodoc:
+ def call(controller, &block)
+ @filter.call(controller, block)
+ rescue LocalJumpError # a yield from a proc... no no bad dog.
+ raise(ActionControllerError, 'Cannot yield from a Proc type filter. The Proc must take two arguments and execute #call on the second argument.')
+ end
+ end
+
+ class MethodFilter < Filter #:nodoc:
+ def call(controller, &block)
+ @filter.call(controller, &block)
+ end
+ end
+
+ class ClassFilter < Filter #:nodoc:
+ def call(controller, &block)
+ @filter.filter(controller, &block)
+ end
+ end
+
+ protected
+ def append_filter_to_chain(filters, position = :around, &block)
+ write_inheritable_array('filter_chain', create_filters(filters, position, &block) )
+ end
+
+ def prepend_filter_to_chain(filters, position = :around, &block)
+ write_inheritable_attribute('filter_chain', create_filters(filters, position, &block) + filter_chain)
+ end
+
+ def create_filters(filters, position, &block) #:nodoc:
+ filters, conditions = extract_conditions(filters, &block)
+ filters.map! { |filter| find_or_create_filter(filter,position) }
+ update_conditions(filters, conditions)
+ filters
+ end
+
+ def find_or_create_filter(filter,position)
+ if found_filter = find_filter(filter) { |f| f.send("#{position}?") }
+ found_filter
+ else
+ f = class_for_filter(filter).new(filter)
+ # apply proxy to filter if necessary
+ case position
+ when :before
+ BeforeFilterProxy.new(f)
+ when :after
+ AfterFilterProxy.new(f)
+ else
+ f
+ end
end
end
- def extract_conditions!(filters)
- return nil unless filters.last.is_a? Hash
- filters.pop
+ # The determination of the filter type was once done at run time.
+ # This method is here to extract as much logic from the filter run time as possible
+ def class_for_filter(filter) #:nodoc:
+ case
+ when filter.is_a?(Symbol)
+ SymbolFilter
+ when filter.respond_to?(:call)
+ if filter.is_a?(Method)
+ MethodFilter
+ elsif filter.arity == 1
+ ProcFilter
+ else
+ ProcWithCallFilter
+ end
+ when filter.respond_to?(:filter)
+ ClassFilter
+ else
+ raise(ActionControllerError, 'A filters must be a Symbol, Proc, Method, or object responding to filter.')
+ end
end
- def add_action_conditions(filters, conditions)
- return unless conditions
- included, excluded = conditions[:only], conditions[:except]
- write_inheritable_hash('included_actions', condition_hash(filters, included)) && return if included
- write_inheritable_hash('excluded_actions', condition_hash(filters, excluded)) if excluded
+ def extract_conditions(*filters, &block) #:nodoc:
+ filters.flatten!
+ conditions = filters.last.is_a?(Hash) ? filters.pop : {}
+ filters << block if block_given?
+ return filters, conditions
+ end
+
+ def update_conditions(filters, conditions)
+ return if conditions.empty?
+ if conditions[:only]
+ write_inheritable_hash('included_actions', condition_hash(filters, conditions[:only]))
+ else
+ write_inheritable_hash('excluded_actions', condition_hash(filters, conditions[:except])) if conditions[:except]
+ end
end
def condition_hash(filters, *actions)
- filters.inject({}) {|hash, filter| hash.merge(filter => actions.flatten.map {|action| action.to_s})}
+ actions = actions.flatten.map(&:to_s)
+ filters.inject({}) { |h,f| h.update( f => (actions.blank? ? nil : actions)) }
end
-
- def remove_contradicting_conditions!(filters, conditions)
- return unless conditions[:only]
- filters.each do |filter|
- next unless included_actions_for_filter = (read_inheritable_attribute('included_actions') || {})[filter]
- [*conditions[:only]].each do |conditional_action|
- conditional_action = conditional_action.to_s
- included_actions_for_filter.delete(conditional_action) if included_actions_for_filter.include?(conditional_action)
+
+ def skip_filter_in_chain(*filters, &test) #:nodoc:
+ filters, conditions = extract_conditions(filters)
+ filters.map! { |f| block_given? ? find_filter(f, &test) : find_filter(f) }
+ filters.compact!
+
+ if conditions.empty?
+ delete_filters_in_chain(filters)
+ else
+ remove_actions_from_included_actions!(filters,conditions[:only] || [])
+ conditions[:only], conditions[:except] = conditions[:except], conditions[:only]
+ update_conditions(filters,conditions)
+ end
+ end
+
+ def remove_actions_from_included_actions!(filters,*actions)
+ actions = actions.flatten.map(&:to_s)
+ updated_hash = filters.inject(included_actions) do |hash,filter|
+ ia = (hash[filter] || []) - actions
+ ia.blank? ? hash.delete(filter) : hash[filter] = ia
+ hash
+ end
+ write_inheritable_attribute('included_actions', updated_hash)
+ end
+
+ def delete_filters_in_chain(filters) #:nodoc:
+ write_inheritable_attribute('filter_chain', filter_chain.reject { |f| filters.include?(f) })
+ end
+
+ def filter_responds_to_before_and_after(filter) #:nodoc:
+ filter.respond_to?(:before) && filter.respond_to?(:after)
+ end
+
+ def proxy_before_and_after_filter(filter) #:nodoc:
+ return filter unless filter_responds_to_before_and_after(filter)
+ Proc.new do |controller, action|
+ unless filter.before(controller) == false
+ begin
+ action.call
+ ensure
+ filter.after(controller)
+ end
end
end
end
@@ -350,26 +609,14 @@ module ActionController #:nodoc:
module InstanceMethods # :nodoc:
def self.included(base)
base.class_eval do
- alias_method :perform_action_without_filters, :perform_action
- alias_method :perform_action, :perform_action_with_filters
-
- alias_method :process_without_filters, :process
- alias_method :process, :process_with_filters
-
- alias_method :process_cleanup_without_filters, :process_cleanup
- alias_method :process_cleanup, :process_cleanup_with_filters
+ alias_method_chain :perform_action, :filters
+ alias_method_chain :process, :filters
+ alias_method_chain :process_cleanup, :filters
end
end
def perform_action_with_filters
- before_action_result = before_action
-
- unless before_action_result == false || performed?
- perform_action_without_filters
- after_action
- end
-
- @before_filter_chain_aborted = (before_action_result == false)
+ call_filter(self.class.filter_chain, 0)
end
def process_with_filters(request, response, method = :perform_action, *arguments) #:nodoc:
@@ -377,61 +624,37 @@ module ActionController #:nodoc:
process_without_filters(request, response, method, *arguments)
end
- # Calls all the defined before-filter filters, which are added by using "before_filter :method".
- # If any of the filters return false, no more filters will be executed and the action is aborted.
- def before_action #:doc:
- call_filters(self.class.before_filters)
+ def filter_chain
+ self.class.filter_chain
end
- # Calls all the defined after-filter filters, which are added by using "after_filter :method".
- # If any of the filters return false, no more filters will be executed.
- def after_action #:doc:
- call_filters(self.class.after_filters)
+ def call_filter(chain, index)
+ return (performed? || perform_action_without_filters) if index >= chain.size
+ filter = chain[index]
+ return call_filter(chain, index.next) if self.class.filter_excluded_from_action?(filter,action_name)
+
+ halted = false
+ filter.call(self) do
+ halted = call_filter(chain, index.next)
+ end
+ halt_filter_chain(filter.filter, :no_yield) if halted == false unless @before_filter_chain_aborted
+ halted
end
-
+
+ def halt_filter_chain(filter, reason)
+ if logger
+ case reason
+ when :no_yield
+ logger.info "Filter chain halted as [#{filter.inspect}] did not yield."
+ when :returned_false
+ logger.info "Filter chain halted as [#{filter.inspect}] returned false."
+ end
+ end
+ @before_filter_chain_aborted = true
+ return false
+ end
+
private
- def call_filters(filters)
- filters.each do |filter|
- next if action_exempted?(filter)
-
- filter_result = case
- when filter.is_a?(Symbol)
- self.send(filter)
- when filter_block?(filter)
- filter.call(self)
- when filter_class?(filter)
- filter.filter(self)
- else
- raise(
- ActionControllerError,
- 'Filters need to be either a symbol, proc/method, or class implementing a static filter method'
- )
- end
-
- if filter_result == false
- logger.info "Filter chain halted as [#{filter}] returned false" if logger
- return false
- end
- end
- end
-
- def filter_block?(filter)
- filter.respond_to?('call') && (filter.arity == 1 || filter.arity == -1)
- end
-
- def filter_class?(filter)
- filter.respond_to?('filter')
- end
-
- def action_exempted?(filter)
- case
- when ia = self.class.included_actions[filter]
- !ia.include?(action_name)
- when ea = self.class.excluded_actions[filter]
- ea.include?(action_name)
- end
- end
-
def process_cleanup_with_filters
if @before_filter_chain_aborted
close_session
diff --git a/vendor/rails/actionpack/lib/action_controller/flash.rb b/vendor/rails/actionpack/lib/action_controller/flash.rb
index 8877c337..9f50b957 100644
--- a/vendor/rails/actionpack/lib/action_controller/flash.rb
+++ b/vendor/rails/actionpack/lib/action_controller/flash.rb
@@ -17,7 +17,7 @@ module ActionController #:nodoc:
# end
#
# display.rhtml
- # <% if @flash[:notice] %>
<%= @flash[:notice] %>
<% end %>
+ # <% if flash[:notice] %>
<%= flash[:notice] %>
<% end %>
#
# This example just places a string in the flash, but you can put any object in there. And of course, you can put as many
# as you like at a time too. Just remember: They'll be gone by the time the next action has been performed.
@@ -28,11 +28,9 @@ module ActionController #:nodoc:
base.send :include, InstanceMethods
base.class_eval do
- alias_method :assign_shortcuts_without_flash, :assign_shortcuts
- alias_method :assign_shortcuts, :assign_shortcuts_with_flash
-
- alias_method :process_cleanup_without_flash, :process_cleanup
- alias_method :process_cleanup, :process_cleanup_with_flash
+ alias_method_chain :assign_shortcuts, :flash
+ alias_method_chain :process_cleanup, :flash
+ alias_method_chain :reset_session, :flash
end
end
@@ -94,7 +92,7 @@ module ActionController #:nodoc:
#
# flash.keep # keeps the entire flash
# flash.keep(:notice) # keeps only the "notice" entry, the rest of the flash is discarded
- def keep(k=nil)
+ def keep(k = nil)
use(k, false)
end
@@ -102,7 +100,7 @@ module ActionController #:nodoc:
#
# flash.keep # keep entire flash available for the next action
# flash.discard(:warning) # discard the "warning" entry (it'll still be available for the current action)
- def discard(k=nil)
+ def discard(k = nil)
use(k)
end
@@ -118,6 +116,7 @@ module ActionController #:nodoc:
@used.delete(k)
end
end
+
(@used.keys - keys).each{|k| @used.delete k } # clean up after keys that could have been left over by calling reject! or shift on the flash
end
@@ -143,36 +142,41 @@ module ActionController #:nodoc:
end
def process_cleanup_with_flash
- flash.sweep if @session
+ flash.sweep if @_session
process_cleanup_without_flash
end
+
+ def reset_session_with_flash
+ reset_session_without_flash
+ remove_instance_variable(:@_flash)
+ flash(:refresh)
+ end
protected
# Access the contents of the flash. Use flash["notice"] to read a notice you put there or
# flash["notice"] = "hello" to put a new one.
# Note that if sessions are disabled only flash.now will work.
def flash(refresh = false) #:doc:
- if @flash.nil? || refresh
- @flash =
- if @session.is_a?(Hash)
- # @session is a Hash, if sessions are disabled
- # we don't put the flash in the session in this case
+ if !defined?(@_flash) || refresh
+ @_flash =
+ if session.is_a?(Hash)
+ # don't put flash in session if disabled
FlashHash.new
else
- # otherwise, @session is a CGI::Session or a TestSession
+ # otherwise, session is a CGI::Session or a TestSession
# so make sure it gets retrieved from/saved to session storage after request processing
- @session["flash"] ||= FlashHash.new
+ session["flash"] ||= FlashHash.new
end
end
-
- @flash
+
+ @_flash
end
# deprecated. use flash.keep instead
def keep_flash #:doc:
- warn 'keep_flash is deprecated; use flash.keep instead.'
+ ActiveSupport::Deprecation.warn 'keep_flash is deprecated; use flash.keep instead.', caller
flash.keep
end
end
end
-end
\ No newline at end of file
+end
diff --git a/vendor/rails/actionpack/lib/action_controller/helpers.rb b/vendor/rails/actionpack/lib/action_controller/helpers.rb
index e2d97b8f..dfc77851 100644
--- a/vendor/rails/actionpack/lib/action_controller/helpers.rb
+++ b/vendor/rails/actionpack/lib/action_controller/helpers.rb
@@ -1,8 +1,6 @@
module ActionController #:nodoc:
module Helpers #:nodoc:
- def self.append_features(base)
- super
-
+ def self.included(base)
# Initialize the base module to aggregate its helpers.
base.class_inheritable_accessor :master_helper_module
base.master_helper_module = Module.new
@@ -13,8 +11,7 @@ module ActionController #:nodoc:
base.class_eval do
# Wrap inherited to create a new master helper module for subclasses.
class << self
- alias_method :inherited_without_helper, :inherited
- alias_method :inherited, :inherited_with_helper
+ alias_method_chain :inherited, :helper
end
end
end
diff --git a/vendor/rails/actionpack/lib/action_controller/integration.rb b/vendor/rails/actionpack/lib/action_controller/integration.rb
index 74817c4b..d77540a2 100644
--- a/vendor/rails/actionpack/lib/action_controller/integration.rb
+++ b/vendor/rails/actionpack/lib/action_controller/integration.rb
@@ -1,6 +1,7 @@
require 'dispatcher'
require 'stringio'
require 'uri'
+require 'action_controller/test_process'
module ActionController
module Integration #:nodoc:
@@ -13,6 +14,7 @@ module ActionController
# rather than instantiating Integration::Session directly.
class Session
include Test::Unit::Assertions
+ include ActionController::Assertions
include ActionController::TestProcess
# The integer HTTP status code of the last request.
@@ -73,11 +75,11 @@ module ActionController
unless @named_routes_configured
# install the named routes in this session instance.
klass = class< "XMLHttpRequest")
+ headers = (headers || {}).merge(
+ "X-Requested-With" => "XMLHttpRequest",
+ "Accept" => "text/javascript, text/html, application/xml, text/xml, */*"
+ )
+
post(path, parameters, headers)
end
@@ -174,7 +194,6 @@ module ActionController
end
private
-
class MockCGI < CGI #:nodoc:
attr_accessor :stdinput, :stdoutput, :env_table
@@ -224,7 +243,7 @@ module ActionController
(headers || {}).each do |key, value|
key = key.to_s.upcase.gsub(/-/, "_")
- key = "HTTP_#{key}" unless env.has_key?(key) || env =~ /^X|HTTP/
+ key = "HTTP_#{key}" unless env.has_key?(key) || key =~ /^HTTP_/
env[key] = value
end
@@ -247,6 +266,8 @@ module ActionController
# tests.
@response.extend(TestResponseBehavior)
+ @html_document = nil
+
parse_result
return status
end
@@ -317,9 +338,8 @@ module ActionController
def self.included(base)
base.extend(ClassMethods)
base.class_eval do
- class <
+ # // The header part of this layout
# <%= yield %>
- #
+ # // The footer part of this layout -->
#
# And then you have content pages that look like this:
#
@@ -37,9 +38,9 @@ module ActionController #:nodoc:
# Not a word about common structures. At rendering time, the content page is computed and then inserted in the layout,
# like this:
#
- #
+ # // The header part of this layout
# hello world
- #
+ # // The footer part of this layout -->
#
# == Accessing shared variables
#
@@ -182,7 +183,6 @@ module ActionController #:nodoc:
private
def inherited_with_layout(child)
inherited_without_layout(child)
- child.send :include, Reloadable
layout_match = child.name.underscore.sub(/_controller$/, '').sub(/^controllers\//, '')
child.layout(layout_match) unless layout_list.grep(%r{layouts/#{layout_match}\.[a-z][0-9a-z]*$}).empty?
end
@@ -235,6 +235,8 @@ module ActionController #:nodoc:
template_with_options = options.is_a?(Hash)
if apply_layout?(template_with_options, options) && (layout = pick_layout(template_with_options, options, deprecated_layout))
+ assert_existence_of_template_file(layout)
+
options = options.merge :layout => false if template_with_options
logger.info("Rendering #{options} within #{layout}") if logger
@@ -248,6 +250,7 @@ module ActionController #:nodoc:
erase_render_results
add_variables_to_assigns
@template.instance_variable_set("@content_for_layout", content_for_layout)
+ response.layout = layout
render_text(@template.render_file(layout, true), deprecated_status)
else
render_with_no_layout(options, deprecated_status, &block)
@@ -263,7 +266,7 @@ module ActionController #:nodoc:
def candidate_for_layout?(options)
(options.has_key?(:layout) && options[:layout] != false) ||
- options.values_at(:text, :xml, :file, :inline, :partial, :nothing).compact.empty? &&
+ options.values_at(:text, :xml, :json, :file, :inline, :partial, :nothing).compact.empty? &&
!template_exempt_from_layout?(default_template_name(options[:action] || options[:template]))
end
diff --git a/vendor/rails/actionpack/lib/action_controller/macros/auto_complete.rb b/vendor/rails/actionpack/lib/action_controller/macros/auto_complete.rb
index 917f151e..8282e2c1 100644
--- a/vendor/rails/actionpack/lib/action_controller/macros/auto_complete.rb
+++ b/vendor/rails/actionpack/lib/action_controller/macros/auto_complete.rb
@@ -4,11 +4,12 @@ module ActionController
# backing.
module Macros
module AutoComplete #:nodoc:
- def self.append_features(base) #:nodoc:
- super
+ def self.included(base) #:nodoc:
base.extend(ClassMethods)
end
+ # DEPRECATION WARNING: This method will become a separate plugin when Rails 2.0 ships.
+ #
# Example:
#
# # Controller
diff --git a/vendor/rails/actionpack/lib/action_controller/macros/in_place_editing.rb b/vendor/rails/actionpack/lib/action_controller/macros/in_place_editing.rb
index 30e94c51..d04f1ce1 100644
--- a/vendor/rails/actionpack/lib/action_controller/macros/in_place_editing.rb
+++ b/vendor/rails/actionpack/lib/action_controller/macros/in_place_editing.rb
@@ -1,11 +1,12 @@
module ActionController
module Macros
module InPlaceEditing #:nodoc:
- def self.append_features(base) #:nodoc:
- super
+ def self.included(base) #:nodoc:
base.extend(ClassMethods)
end
+ # DEPRECATION WARNING: This method will become a separate plugin when Rails 2.0 ships.
+ #
# Example:
#
# # Controller
diff --git a/vendor/rails/actionpack/lib/action_controller/mime_responds.rb b/vendor/rails/actionpack/lib/action_controller/mime_responds.rb
index 555ffda1..ff07c3c1 100644
--- a/vendor/rails/actionpack/lib/action_controller/mime_responds.rb
+++ b/vendor/rails/actionpack/lib/action_controller/mime_responds.rb
@@ -8,18 +8,18 @@ module ActionController #:nodoc:
# Without web-service support, an action which collects the data for displaying a list of people
# might look something like this:
#
- # def list
+ # def index
# @people = Person.find(:all)
# end
#
# Here's the same action, with web-service support baked in:
#
- # def list
+ # def index
# @people = Person.find(:all)
#
- # respond_to do |wants|
- # wants.html
- # wants.xml { render :xml => @people.to_xml }
+ # respond_to do |format|
+ # format.html
+ # format.xml { render :xml => @people.to_xml }
# end
# end
#
@@ -30,7 +30,7 @@ module ActionController #:nodoc:
# Supposing you have an action that adds a new person, optionally creating their company
# (by name) if it does not already exist, without web-services, it might look like this:
#
- # def add
+ # def create
# @company = Company.find_or_create_by_name(params[:company][:name])
# @person = @company.people.create(params[:person])
#
@@ -39,15 +39,15 @@ module ActionController #:nodoc:
#
# Here's the same action, with web-service support baked in:
#
- # def add
+ # def create
# company = params[:person].delete(:company)
# @company = Company.find_or_create_by_name(company[:name])
# @person = @company.people.create(params[:person])
#
- # respond_to do |wants|
- # wants.html { redirect_to(person_list_url) }
- # wants.js
- # wants.xml { render :xml => @person.to_xml(:include => @company) }
+ # respond_to do |format|
+ # format.html { redirect_to(person_list_url) }
+ # format.js
+ # format.xml { render :xml => @person.to_xml(:include => @company) }
# end
# end
#
@@ -97,9 +97,8 @@ module ActionController #:nodoc:
# environment.rb as follows.
#
# Mime::Type.register "image/jpg", :jpg
- #
def respond_to(*types, &block)
- raise ArgumentError, "respond_to takes either types or a block, never bot" unless types.any? ^ block
+ raise ArgumentError, "respond_to takes either types or a block, never both" unless types.any? ^ block
block ||= lambda { |responder| types.each { |type| responder.send(type) } }
responder = Responder.new(block.binding)
block.call(responder)
@@ -108,15 +107,19 @@ module ActionController #:nodoc:
end
class Responder #:nodoc:
- DEFAULT_BLOCKS = {
- :html => 'Proc.new { render }',
- :js => 'Proc.new { render :action => "#{action_name}.rjs" }',
- :xml => 'Proc.new { render :action => "#{action_name}.rxml" }'
- }
+ DEFAULT_BLOCKS = [:html, :js, :xml].inject({}) do |blocks, ext|
+ template_extension = (ext == :html ? '' : ".r#{ext}")
+ blocks.update ext => %(Proc.new { render :action => "\#{action_name}#{template_extension}", :content_type => Mime::#{ext.to_s.upcase} })
+ end
def initialize(block_binding)
@block_binding = block_binding
- @mime_type_priority = eval("request.accepts", block_binding)
+ @mime_type_priority = eval(
+ "(params[:format] && Mime::EXTENSION_LOOKUP[params[:format]]) ? " +
+ "[ Mime::EXTENSION_LOOKUP[params[:format]] ] : request.accepts",
+ block_binding
+ )
+
@order = []
@responses = {}
end
@@ -127,24 +130,33 @@ module ActionController #:nodoc:
@order << mime_type
if block_given?
- @responses[mime_type] = block
- else
- @responses[mime_type] = eval(DEFAULT_BLOCKS[mime_type.to_sym], @block_binding)
- end
- end
-
- for mime_type in %w( all html js xml rss atom yaml )
- eval <<-EOT
- def #{mime_type}(&block)
- custom(Mime::#{mime_type.upcase}, &block)
+ @responses[mime_type] = Proc.new do
+ eval "response.content_type = '#{mime_type.to_s}'", @block_binding
+ block.call
end
- EOT
+ else
+ if source = DEFAULT_BLOCKS[mime_type.to_sym]
+ @responses[mime_type] = eval(source, @block_binding)
+ else
+ raise ActionController::RenderError, "Expected a block but none was given for custom mime handler #{mime_type}"
+ end
+ end
end
def any(*args, &block)
args.each { |type| send(type, &block) }
end
+ def method_missing(symbol, &block)
+ mime_constant = symbol.to_s.upcase
+
+ if Mime::SET.include?(Mime.const_get(mime_constant))
+ custom(Mime.const_get(mime_constant), &block)
+ else
+ super
+ end
+ end
+
def respond
for priority in @mime_type_priority
if priority == Mime::ALL
diff --git a/vendor/rails/actionpack/lib/action_controller/mime_type.rb b/vendor/rails/actionpack/lib/action_controller/mime_type.rb
index 30cea88a..76bf680a 100644
--- a/vendor/rails/actionpack/lib/action_controller/mime_type.rb
+++ b/vendor/rails/actionpack/lib/action_controller/mime_type.rb
@@ -1,5 +1,18 @@
module Mime
- class Type #:nodoc:
+ # Encapsulates the notion of a mime type. Can be used at render time, for example, with:
+ #
+ # class PostsController < ActionController::Base
+ # def show
+ # @post = Post.find(params[:id])
+ #
+ # respond_to do |format|
+ # format.html
+ # format.ics { render :text => post.to_ics, :mime_type => Mime::Type["text/calendar"] }
+ # format.xml { render :xml => @people.to_xml }
+ # end
+ # end
+ # end
+ class Type
# A simple helper class used in parsing the accept header
class AcceptItem #:nodoc:
attr_accessor :order, :name, :q
@@ -31,14 +44,20 @@ module Mime
LOOKUP[string]
end
+ def register(string, symbol, synonyms = [])
+ Mime.send :const_set, symbol.to_s.upcase, Type.new(string, symbol, synonyms)
+ SET << Mime.send(:const_get, symbol.to_s.upcase)
+ LOOKUP[string] = EXTENSION_LOOKUP[symbol.to_s] = SET.last
+ end
+
def parse(accept_header)
# keep track of creation order to keep the subsequent sort stable
index = 0
- list = accept_header.split(/,/).
- map! { |i| AcceptItem.new(index += 1, *i.split(/;\s*q=/)) }.sort!
+ list = accept_header.split(/,/).map! do |i|
+ AcceptItem.new(index += 1, *i.split(/;\s*q=/))
+ end.sort!
# Take care of the broken text/xml entry by renaming or deleting it
-
text_xml = list.index("text/xml")
app_xml = list.index("application/xml")
@@ -112,31 +131,70 @@ module Mime
end
ALL = Type.new "*/*", :all
+ TEXT = Type.new "text/plain", :text
HTML = Type.new "text/html", :html, %w( application/xhtml+xml )
JS = Type.new "text/javascript", :js, %w( application/javascript application/x-javascript )
+ ICS = Type.new "text/calendar", :ics
+ CSV = Type.new "text/csv", :csv
XML = Type.new "application/xml", :xml, %w( text/xml application/x-xml )
RSS = Type.new "application/rss+xml", :rss
ATOM = Type.new "application/atom+xml", :atom
YAML = Type.new "application/x-yaml", :yaml, %w( text/yaml )
+ JSON = Type.new "application/json", :json, %w( text/x-json )
- LOOKUP = Hash.new { |h, k| h[k] = Type.new(k) }
+ SET = [ ALL, TEXT, HTML, JS, ICS, XML, RSS, ATOM, YAML, JSON ]
+
+ LOOKUP = Hash.new { |h, k| h[k] = Type.new(k) unless k == "" }
LOOKUP["*/*"] = ALL
+ LOOKUP["text/plain"] = TEXT
+
LOOKUP["text/html"] = HTML
LOOKUP["application/xhtml+xml"] = HTML
- LOOKUP["application/xml"] = XML
- LOOKUP["text/xml"] = XML
- LOOKUP["application/x-xml"] = XML
-
LOOKUP["text/javascript"] = JS
LOOKUP["application/javascript"] = JS
LOOKUP["application/x-javascript"] = JS
+ LOOKUP["text/calendar"] = ICS
+
+ LOOKUP["text/csv"] = CSV
+
+ LOOKUP["application/xml"] = XML
+ LOOKUP["text/xml"] = XML
+ LOOKUP["application/x-xml"] = XML
+
LOOKUP["text/yaml"] = YAML
LOOKUP["application/x-yaml"] = YAML
LOOKUP["application/rss+xml"] = RSS
LOOKUP["application/atom+xml"] = ATOM
-end
\ No newline at end of file
+
+ LOOKUP["application/json"] = JSON
+ LOOKUP["text/x-json"] = JSON
+
+
+ EXTENSION_LOOKUP = Hash.new { |h, k| h[k] = Type.new(k) unless k == "" }
+
+ EXTENSION_LOOKUP["html"] = HTML
+ EXTENSION_LOOKUP["xhtml"] = HTML
+
+ EXTENSION_LOOKUP["txt"] = TEXT
+
+ EXTENSION_LOOKUP["xml"] = XML
+
+ EXTENSION_LOOKUP["js"] = JS
+
+ EXTENSION_LOOKUP["ics"] = ICS
+
+ EXTENSION_LOOKUP["csv"] = CSV
+
+ EXTENSION_LOOKUP["yml"] = YAML
+ EXTENSION_LOOKUP["yaml"] = YAML
+
+ EXTENSION_LOOKUP["rss"] = RSS
+ EXTENSION_LOOKUP["atom"] = ATOM
+
+ EXTENSION_LOOKUP["json"] = JSON
+end
diff --git a/vendor/rails/actionpack/lib/action_controller/pagination.rb b/vendor/rails/actionpack/lib/action_controller/pagination.rb
index a1053e65..595a08c7 100644
--- a/vendor/rails/actionpack/lib/action_controller/pagination.rb
+++ b/vendor/rails/actionpack/lib/action_controller/pagination.rb
@@ -1,6 +1,8 @@
module ActionController
# === Action Pack pagination for Active Record collections
#
+ # DEPRECATION WARNING: Pagination will be separated into its own plugin with Rails 2.0.
+ #
# The Pagination module aids in the process of paging large collections of
# Active Record objects. It offers macro-style automatic fetching of your
# model for multiple views, or explicit fetching for single actions. And if
@@ -104,8 +106,7 @@ module ActionController
# ClassMethods#paginate.
#
# +options+ are:
- # :singular_name:: the singular name to use, if it can't be inferred by
- # singularizing the collection name
+ # :singular_name:: the singular name to use, if it can't be inferred by singularizing the collection name
# :class_name:: the class name to use, if it can't be inferred by
# camelizing the singular name
# :per_page:: the maximum number of items to include in a
@@ -192,7 +193,7 @@ module ActionController
def paginator_and_collection_for(collection_id, options) #:nodoc:
klass = options[:class_name].constantize
- page = @params[options[:parameter]]
+ page = params[options[:parameter]]
count = count_collection_for_pagination(klass, options)
paginator = Paginator.new(self, count, options[:per_page], page)
collection = find_collection_for_pagination(klass, options, paginator)
diff --git a/vendor/rails/actionpack/lib/action_controller/request.rb b/vendor/rails/actionpack/lib/action_controller/request.rb
index 86547919..b1cb1252 100755
--- a/vendor/rails/actionpack/lib/action_controller/request.rb
+++ b/vendor/rails/actionpack/lib/action_controller/request.rb
@@ -13,12 +13,18 @@ module ActionController
@parameters ||= request_parameters.update(query_parameters).update(path_parameters).with_indifferent_access
end
- # Returns the HTTP request method as a lowercase symbol (:get, for example)
+ # Returns the HTTP request method as a lowercase symbol (:get, for example). Note, HEAD is returned as :get
+ # since the two are supposedly to be functionaly equivilent for all purposes except that HEAD won't return a response
+ # body (which Rails also takes care of elsewhere).
def method
- @request_method ||= @env['REQUEST_METHOD'].downcase.to_sym
+ @request_method ||= (!parameters[:_method].blank? && @env['REQUEST_METHOD'] == 'POST') ?
+ parameters[:_method].to_s.downcase.to_sym :
+ @env['REQUEST_METHOD'].downcase.to_sym
+
+ @request_method == :head ? :get : @request_method
end
- # Is this a GET request? Equivalent to request.method == :get
+ # Is this a GET (or HEAD) request? Equivalent to request.method == :get
def get?
method == :get
end
@@ -38,9 +44,10 @@ module ActionController
method == :delete
end
- # Is this a HEAD request? Equivalent to request.method == :head
+ # Is this a HEAD request? HEAD is mapped as :get for request.method, so here we ask the
+ # REQUEST_METHOD header directly. Thus, for head, both get? and head? will return true.
def head?
- method == :head
+ @env['REQUEST_METHOD'].downcase.to_sym == :head
end
# Determine whether the body of a HTTP call is URL-encoded (default)
@@ -128,19 +135,21 @@ module ActionController
@env['RAW_POST_DATA']
end
- # Returns the request URI correctly, taking into account the idiosyncracies
- # of the various servers.
+ # Return the request URI, accounting for server idiosyncracies.
+ # WEBrick includes the full URL. IIS leaves REQUEST_URI blank.
def request_uri
if uri = @env['REQUEST_URI']
- (%r{^\w+\://[^/]+(/.*|$)$} =~ uri) ? $1 : uri # Remove domain, which webrick puts into the request_uri.
- else # REQUEST_URI is blank under IIS - get this from PATH_INFO and SCRIPT_NAME
+ # Remove domain, which webrick puts into the request_uri.
+ (%r{^\w+\://[^/]+(/.*|$)$} =~ uri) ? $1 : uri
+ else
+ # Construct IIS missing REQUEST_URI from SCRIPT_NAME and PATH_INFO.
script_filename = @env['SCRIPT_NAME'].to_s.match(%r{[^/]+$})
uri = @env['PATH_INFO']
uri = uri.sub(/#{script_filename}\//, '') unless script_filename.nil?
unless (env_qs = @env['QUERY_STRING']).nil? || env_qs.empty?
uri << '?' << env_qs
end
- uri
+ @env['REQUEST_URI'] = uri
end
end
@@ -159,11 +168,10 @@ module ActionController
path = (uri = request_uri) ? uri.split('?').first : ''
# Cut off the path to the installation directory if given
- root = relative_url_root
- path[0, root.length] = '' if root
- path || ''
+ path.sub!(%r/^#{relative_url_root}/, '')
+ path || ''
end
-
+
# Returns the path minus the web server relative installation directory.
# This can be set with the environment variable RAILS_RELATIVE_URL_ROOT.
# It can be automatically extracted for Apache setups. If the server is not
diff --git a/vendor/rails/actionpack/lib/action_controller/rescue.rb b/vendor/rails/actionpack/lib/action_controller/rescue.rb
index d97a2949..3746fb56 100644
--- a/vendor/rails/actionpack/lib/action_controller/rescue.rb
+++ b/vendor/rails/actionpack/lib/action_controller/rescue.rb
@@ -6,12 +6,10 @@ module ActionController #:nodoc:
#
# You can tailor the rescuing behavior and appearance by overwriting the following two stub methods.
module Rescue
- def self.append_features(base) #:nodoc:
- super
+ def self.included(base) #:nodoc:
base.extend(ClassMethods)
base.class_eval do
- alias_method :perform_action_without_rescue, :perform_action
- alias_method :perform_action, :perform_action_with_rescue
+ alias_method_chain :perform_action, :rescue
end
end
@@ -36,23 +34,26 @@ module ActionController #:nodoc:
# Overwrite to implement custom logging of errors. By default logs as fatal.
def log_error(exception) #:doc:
- if ActionView::TemplateError === exception
- logger.fatal(exception.to_s)
- else
- logger.fatal(
- "\n\n#{exception.class} (#{exception.message}):\n " +
- clean_backtrace(exception).join("\n ") +
- "\n\n"
- )
+ ActiveSupport::Deprecation.silence do
+ if ActionView::TemplateError === exception
+ logger.fatal(exception.to_s)
+ else
+ logger.fatal(
+ "\n\n#{exception.class} (#{exception.message}):\n " +
+ clean_backtrace(exception).join("\n ") +
+ "\n\n"
+ )
+ end
end
end
# Overwrite to implement public exception handling (for requests answering false to local_request?).
def rescue_action_in_public(exception) #:doc:
case exception
- when RoutingError, UnknownAction then
+ when RoutingError, UnknownAction
render_text(IO.read(File.join(RAILS_ROOT, 'public', '404.html')), "404 Not Found")
- else render_text "
Application error (Rails)
"
+ else
+ render_text(IO.read(File.join(RAILS_ROOT, 'public', '500.html')), "500 Internal Error")
end
end
@@ -60,19 +61,19 @@ module ActionController #:nodoc:
# the remote IP being 127.0.0.1. For example, this could include the IP of the developer machine when debugging
# remotely.
def local_request? #:doc:
- [@request.remote_addr, @request.remote_ip] == ["127.0.0.1"] * 2
+ [request.remote_addr, request.remote_ip] == ["127.0.0.1"] * 2
end
# Renders a detailed diagnostics screen on action exceptions.
def rescue_action_locally(exception)
add_variables_to_assigns
@template.instance_variable_set("@exception", exception)
- @template.instance_variable_set("@rescues_path", File.dirname(__FILE__) + "/templates/rescues/")
+ @template.instance_variable_set("@rescues_path", File.dirname(rescues_path("stub")))
@template.send(:assign_variables_from_controller)
@template.instance_variable_set("@contents", @template.render_file(template_path_for_local_rescue(exception), false))
- @headers["Content-Type"] = "text/html"
+ response.content_type = Mime::HTML
render_file(rescues_path("layout"), response_code_for_rescue(exception))
end
@@ -80,8 +81,8 @@ module ActionController #:nodoc:
def perform_action_with_rescue #:nodoc:
begin
perform_action_without_rescue
- rescue Object => exception
- if defined?(Breakpoint) && @params["BP-RETRY"]
+ rescue Exception => exception # errors from action performed
+ if defined?(Breakpoint) && params["BP-RETRY"]
msg = exception.backtrace.first
if md = /^(.+?):(\d+)(?::in `(.+)')?$/.match(msg) then
origin_file, origin_line = md[1], md[2].to_i
@@ -89,7 +90,7 @@ module ActionController #:nodoc:
set_trace_func(lambda do |type, file, line, method, context, klass|
if file == origin_file and line == origin_line then
set_trace_func(nil)
- @params["BP-RETRY"] = false
+ params["BP-RETRY"] = false
callstack = caller
callstack.slice!(0) if callstack.first["rescue.rb"]
@@ -127,8 +128,10 @@ module ActionController #:nodoc:
def response_code_for_rescue(exception)
case exception
- when UnknownAction, RoutingError then "404 Page Not Found"
- else "500 Internal Error"
+ when UnknownAction, RoutingError
+ "404 Page Not Found"
+ else
+ "500 Internal Error"
end
end
diff --git a/vendor/rails/actionpack/lib/action_controller/response.rb b/vendor/rails/actionpack/lib/action_controller/response.rb
index 746d6097..a6438a13 100755
--- a/vendor/rails/actionpack/lib/action_controller/response.rb
+++ b/vendor/rails/actionpack/lib/action_controller/response.rb
@@ -1,15 +1,33 @@
module ActionController
class AbstractResponse #:nodoc:
DEFAULT_HEADERS = { "Cache-Control" => "no-cache" }
- attr_accessor :body, :headers, :session, :cookies, :assigns, :template, :redirected_to, :redirected_to_method_params
+ attr_accessor :body, :headers, :session, :cookies, :assigns, :template, :redirected_to, :redirected_to_method_params, :layout
def initialize
@body, @headers, @session, @assigns = "", DEFAULT_HEADERS.merge("cookie" => []), [], []
end
+ def content_type=(mime_type)
+ @headers["Content-Type"] = charset ? "#{mime_type}; charset=#{charset}" : mime_type
+ end
+
+ def content_type
+ content_type = String(@headers["Content-Type"]).split(";")[0]
+ content_type.blank? ? nil : content_type
+ end
+
+ def charset=(encoding)
+ @headers["Content-Type"] = "#{content_type || "text/html"}; charset=#{encoding}"
+ end
+
+ def charset
+ charset = String(@headers["Content-Type"]).split(";")[1]
+ charset.blank? ? nil : charset.strip.split("=")[1]
+ end
+
def redirect(to_url, permanently = false)
@headers["Status"] = "302 Found" unless @headers["Status"] == "301 Moved Permanently"
- @headers["location"] = to_url
+ @headers["Location"] = to_url
@body = "You are being redirected."
end
diff --git a/vendor/rails/actionpack/lib/action_controller/routing.rb b/vendor/rails/actionpack/lib/action_controller/routing.rb
index e0b9b845..dee2e66e 100644
--- a/vendor/rails/actionpack/lib/action_controller/routing.rb
+++ b/vendor/rails/actionpack/lib/action_controller/routing.rb
@@ -1,716 +1,1340 @@
+require 'cgi'
+
+class Object
+ def to_param
+ to_s
+ end
+end
+
+class TrueClass
+ def to_param
+ self
+ end
+end
+
+class FalseClass
+ def to_param
+ self
+ end
+end
+
+class NilClass
+ def to_param
+ self
+ end
+end
+
+class Regexp #:nodoc:
+ def number_of_captures
+ Regexp.new("|#{source}").match('').captures.length
+ end
+
+ class << self
+ def optionalize(pattern)
+ case unoptionalize(pattern)
+ when /\A(.|\(.*\))\Z/ then "#{pattern}?"
+ else "(?:#{pattern})?"
+ end
+ end
+
+ def unoptionalize(pattern)
+ [/\A\(\?:(.*)\)\?\Z/, /\A(.|\(.*\))\?\Z/].each do |regexp|
+ return $1 if regexp =~ pattern
+ end
+ return pattern
+ end
+ end
+end
+
module ActionController
- module Routing #:nodoc:
+ # == Routing
+ #
+ # The routing module provides URL rewriting in native Ruby. It's a way to
+ # redirect incoming requests to controllers and actions. This replaces
+ # mod_rewrite rules. Best of all Rails' Routing works with any web server.
+ # Routes are defined in routes.rb in your RAILS_ROOT/config directory.
+ #
+ # Consider the following route, installed by Rails when you generate your
+ # application:
+ #
+ # map.connect ':controller/:action/:id'
+ #
+ # This route states that it expects requests to consist of a
+ # :controller followed by an :action that in turns is fed by some :id
+ #
+ # Suppose you get an incoming request for /blog/edit/22, you'll end up
+ # with:
+ #
+ # params = { :controller => 'blog',
+ # :action => 'edit'
+ # :id => '22'
+ # }
+ #
+ # Think of creating routes as drawing a map for your requests. The map tells
+ # them where to go based on some predefined pattern:
+ #
+ # ActionController::Routing::Routes.draw do |map|
+ # Pattern 1 tells some request to go to one place
+ # Pattern 2 tell them to go to another
+ # ...
+ # end
+ #
+ # The following symbols are special:
+ #
+ # :controller maps to your controller name
+ # :action maps to an action with your controllers
+ #
+ # Other names simply map to a parameter as in the case of +:id+.
+ #
+ # == Route priority
+ #
+ # Not all routes are created equally. Routes have priority defined by the
+ # order of appearance of the routes in the routes.rb file. The priority goes
+ # from top to bottom. The last route in that file is at the lowest priority
+ # will be applied last. If no route matches, 404 is returned.
+ #
+ # Within blocks, the empty pattern goes first i.e. is at the highest priority.
+ # In practice this works out nicely:
+ #
+ # ActionController::Routing::Routes.draw do |map|
+ # map.with_options :controller => 'blog' do |blog|
+ # blog.show '', :action => 'list'
+ # end
+ # map.connect ':controller/:action/:view
+ # end
+ #
+ # In this case, invoking blog controller (with an URL like '/blog/')
+ # without parameters will activate the 'list' action by default.
+ #
+ # == Defaults routes and default parameters
+ #
+ # Setting a default route is straightforward in Rails because by appending a
+ # Hash to the end of your mapping you can set default parameters.
+ #
+ # Example:
+ # ActionController::Routing:Routes.draw do |map|
+ # map.connect ':controller/:action/:id', :controller => 'blog'
+ # end
+ #
+ # This sets up +blog+ as the default controller if no other is specified.
+ # This means visiting '/' would invoke the blog controller.
+ #
+ # More formally, you can define defaults in a route with the +:defaults+ key.
+ #
+ # map.connect ':controller/:id/:action', :action => 'show', :defaults => { :page => 'Dashboard' }
+ #
+ # == Named routes
+ #
+ # Routes can be named with the syntax map.name_of_route options,
+ # allowing for easy reference within your source as +name_of_route_url+
+ # for the full URL and +name_of_route_path+ for the URI path.
+ #
+ # Example:
+ # # In routes.rb
+ # map.login 'login', :controller => 'accounts', :action => 'login'
+ #
+ # # With render, redirect_to, tests, etc.
+ # redirect_to login_url
+ #
+ # Arguments can be passed as well.
+ #
+ # redirect_to show_item_path(:id => 25)
+ #
+ # Use map.root as a shorthand to name a route for the root path ""
+ #
+ # # In routes.rb
+ # map.root :controller => 'blogs'
+ #
+ # # would recognize http://www.example.com/ as
+ # params = { :controller => 'blogs', :action => 'index' }
+ #
+ # # and provide these named routes
+ # root_url # => 'http://www.example.com/'
+ # root_path # => ''
+ #
+ # Note: when using +with_options+, the route is simply named after the
+ # method you call on the block parameter rather than map.
+ #
+ # # In routes.rb
+ # map.with_options :controller => 'blog' do |blog|
+ # blog.show '', :action => 'list'
+ # blog.delete 'delete/:id', :action => 'delete',
+ # blog.edit 'edit/:id', :action => 'edit'
+ # end
+ #
+ # # provides named routes for show, delete, and edit
+ # link_to @article.title, show_path(:id => @article.id)
+ #
+ # == Pretty URLs
+ #
+ # Routes can generate pretty URLs. For example:
+ #
+ # map.connect 'articles/:year/:month/:day',
+ # :controller => 'articles',
+ # :action => 'find_by_date',
+ # :year => /\d{4}/,
+ # :month => /\d{1,2}/,
+ # :day => /\d{1,2}/
+ #
+ # # Using the route above, the url below maps to:
+ # # params = {:year => '2005', :month => '11', :day => '06'}
+ # # http://localhost:3000/articles/2005/11/06
+ #
+ # == Regular Expressions and parameters
+ # You can specify a reqular expression to define a format for a parameter.
+ #
+ # map.geocode 'geocode/:postalcode', :controller => 'geocode',
+ # :action => 'show', :postalcode => /\d{5}(-\d{4})?/
+ #
+ # or more formally:
+ #
+ # map.geocode 'geocode/:postalcode', :controller => 'geocode',
+ # :action => 'show',
+ # :requirements { :postalcode => /\d{5}(-\d{4})?/ }
+ #
+ # == Route globbing
+ #
+ # Specifying *[string] as part of a rule like :
+ #
+ # map.connect '*path' , :controller => 'blog' , :action => 'unrecognized?'
+ #
+ # will glob all remaining parts of the route that were not recognized earlier. This idiom must appear at the end of the path. The globbed values are in params[:path] in this case.
+ #
+ # == Reloading routes
+ #
+ # You can reload routes if you feel you must:
+ #
+ # Action::Controller::Routes.reload
+ #
+ # This will clear all named routes and reload routes.rb
+ #
+ # == Testing Routes
+ #
+ # The two main methods for testing your routes:
+ #
+ # === +assert_routing+
+ #
+ # def test_movie_route_properly_splits
+ # opts = {:controller => "plugin", :action => "checkout", :id => "2"}
+ # assert_routing "plugin/checkout/2", opts
+ # end
+ #
+ # +assert_routing+ lets you test whether or not the route properly resolves into options.
+ #
+ # === +assert_recognizes+
+ #
+ # def test_route_has_options
+ # opts = {:controller => "plugin", :action => "show", :id => "12"}
+ # assert_recognizes opts, "/plugins/show/12"
+ # end
+ #
+ # Note the subtle difference between the two: +assert_routing+ tests that
+ # an URL fits options while +assert_recognizes+ tests that an URL
+ # breaks into parameters properly.
+ #
+ # In tests you can simply pass the URL or named route to +get+ or +post+.
+ #
+ # def send_to_jail
+ # get '/jail'
+ # assert_response :success
+ # assert_template "jail/front"
+ # end
+ #
+ # def goes_to_login
+ # get login_url
+ # #...
+ # end
+ #
+ module Routing
+ SEPARATORS = %w( / ; . , ? )
+
+ # The root paths which may contain controller files
+ mattr_accessor :controller_paths
+ self.controller_paths = []
+
class << self
- def expiry_hash(options, recall)
- k = v = nil
- expire_on = {}
- options.each {|k, v| expire_on[k] = ((rcv = recall[k]) && (rcv != v))}
- expire_on
+ def with_controllers(names)
+ prior_controllers = @possible_controllers
+ use_controllers! names
+ yield
+ ensure
+ use_controllers! prior_controllers
end
- def extract_parameter_value(parameter) #:nodoc:
- CGI.escape((parameter.respond_to?(:to_param) ? parameter.to_param : parameter).to_s)
+ def normalize_paths(paths)
+ # do the hokey-pokey of path normalization...
+ paths = paths.collect do |path|
+ path = path.
+ gsub("//", "/"). # replace double / chars with a single
+ gsub("\\\\", "\\"). # replace double \ chars with a single
+ gsub(%r{(.)[\\/]$}, '\1') # drop final / or \ if path ends with it
+
+ # eliminate .. paths where possible
+ re = %r{\w+[/\\]\.\.[/\\]}
+ path.gsub!(%r{\w+[/\\]\.\.[/\\]}, "") while path.match(re)
+ path
+ end
+
+ # start with longest path, first
+ paths = paths.uniq.sort_by { |path| - path.length }
end
+
+ def possible_controllers
+ unless @possible_controllers
+ @possible_controllers = []
+
+ paths = controller_paths.select { |path| File.directory?(path) && path != "." }
+
+ seen_paths = Hash.new {|h, k| h[k] = true; false}
+ normalize_paths(paths).each do |load_path|
+ Dir["#{load_path}/**/*_controller.rb"].collect do |path|
+ next if seen_paths[path.gsub(%r{^\.[/\\]}, "")]
+
+ controller_name = path[(load_path.length + 1)..-1]
+
+ controller_name.gsub!(/_controller\.rb\Z/, '')
+ @possible_controllers << controller_name
+ end
+ end
+
+ # remove duplicates
+ @possible_controllers.uniq!
+ end
+ @possible_controllers
+ end
+
+ def use_controllers!(controller_names)
+ @possible_controllers = controller_names
+ end
+
def controller_relative_to(controller, previous)
if controller.nil? then previous
elsif controller[0] == ?/ then controller[1..-1]
elsif %r{^(.*)/} =~ previous then "#{$1}/#{controller}"
else controller
- end
+ end
+ end
+ end
+
+ class Route #:nodoc:
+ attr_accessor :segments, :requirements, :conditions
+
+ def initialize
+ @segments = []
+ @requirements = {}
+ @conditions = {}
end
+
+ # Write and compile a +generate+ method for this Route.
+ def write_generation
+ # Build the main body of the generation
+ body = "expired = false\n#{generation_extraction}\n#{generation_structure}"
+
+ # If we have conditions that must be tested first, nest the body inside an if
+ body = "if #{generation_requirements}\n#{body}\nend" if generation_requirements
+ args = "options, hash, expire_on = {}"
- def treat_hash(hash, keys_to_delete = [])
- k = v = nil
- hash.each do |k, v|
- if v then hash[k] = (v.respond_to? :to_param) ? v.to_param.to_s : v.to_s
+ # Nest the body inside of a def block, and then compile it.
+ raw_method = method_decl = "def generate_raw(#{args})\npath = begin\n#{body}\nend\n[path, hash]\nend"
+ instance_eval method_decl, "generated code (#{__FILE__}:#{__LINE__})"
+
+ # expire_on.keys == recall.keys; in other words, the keys in the expire_on hash
+ # are the same as the keys that were recalled from the previous request. Thus,
+ # we can use the expire_on.keys to determine which keys ought to be used to build
+ # the query string. (Never use keys from the recalled request when building the
+ # query string.)
+
+ method_decl = "def generate(#{args})\npath, hash = generate_raw(options, hash, expire_on)\nappend_query_string(path, hash, extra_keys(hash, expire_on))\nend"
+ instance_eval method_decl, "generated code (#{__FILE__}:#{__LINE__})"
+
+ method_decl = "def generate_extras(#{args})\npath, hash = generate_raw(options, hash, expire_on)\n[path, extra_keys(hash, expire_on)]\nend"
+ instance_eval method_decl, "generated code (#{__FILE__}:#{__LINE__})"
+ raw_method
+ end
+
+ # Build several lines of code that extract values from the options hash. If any
+ # of the values are missing or rejected then a return will be executed.
+ def generation_extraction
+ segments.collect do |segment|
+ segment.extraction_code
+ end.compact * "\n"
+ end
+
+ # Produce a condition expression that will check the requirements of this route
+ # upon generation.
+ def generation_requirements
+ requirement_conditions = requirements.collect do |key, req|
+ if req.is_a? Regexp
+ value_regexp = Regexp.new "\\A#{req.source}\\Z"
+ "hash[:#{key}] && #{value_regexp.inspect} =~ options[:#{key}]"
else
- hash.delete k
- keys_to_delete << k
+ "hash[:#{key}] == #{req.inspect}"
end
end
- hash
+ requirement_conditions * ' && ' unless requirement_conditions.empty?
+ end
+ def generation_structure
+ segments.last.string_structure segments[0..-2]
+ end
+
+ # Write and compile a +recognize+ method for this Route.
+ def write_recognition
+ # Create an if structure to extract the params from a match if it occurs.
+ body = "params = parameter_shell.dup\n#{recognition_extraction * "\n"}\nparams"
+ body = "if #{recognition_conditions.join(" && ")}\n#{body}\nend"
+
+ # Build the method declaration and compile it
+ method_decl = "def recognize(path, env={})\n#{body}\nend"
+ instance_eval method_decl, "generated code (#{__FILE__}:#{__LINE__})"
+ method_decl
+ end
+
+ # Plugins may override this method to add other conditions, like checks on
+ # host, subdomain, and so forth. Note that changes here only affect route
+ # recognition, not generation.
+ def recognition_conditions
+ result = ["(match = #{Regexp.new(recognition_pattern).inspect}.match(path))"]
+ result << "conditions[:method] === env[:method]" if conditions[:method]
+ result
+ end
+
+ # Build the regular expression pattern that will match this route.
+ def recognition_pattern(wrap = true)
+ pattern = ''
+ segments.reverse_each do |segment|
+ pattern = segment.build_pattern pattern
+ end
+ wrap ? ("\\A" + pattern + "\\Z") : pattern
end
- def test_condition(expression, condition)
- case condition
- when String then "(#{expression} == #{condition.inspect})"
- when Regexp then
- condition = Regexp.new("^#{condition.source}$") unless /^\^.*\$$/ =~ condition.source
- "(#{condition.inspect} =~ #{expression})"
- when Array then
- conds = condition.collect do |condition|
- cond = test_condition(expression, condition)
- (cond[0, 1] == '(' && cond[-1, 1] == ')') ? cond : "(#{cond})"
- end
- "(#{conds.join(' || ')})"
- when true then expression
- when nil then "! #{expression}"
- else
- raise ArgumentError, "Valid criteria are strings, regular expressions, true, or nil"
+ # Write the code to extract the parameters from a matched route.
+ def recognition_extraction
+ next_capture = 1
+ extraction = segments.collect do |segment|
+ x = segment.match_extraction next_capture
+ next_capture += Regexp.new(segment.regexp_chunk).number_of_captures
+ x
end
+ extraction.compact
end
- end
-
- class Component #:nodoc:
- def dynamic?() false end
- def optional?() false end
-
- def key() nil end
- def self.new(string, *args)
- return super(string, *args) unless self == Component
- case string
- when ':controller' then ControllerComponent.new(:controller, *args)
- when /^:(\w+)$/ then DynamicComponent.new($1, *args)
- when /^\*(\w+)$/ then PathComponent.new($1, *args)
- else StaticComponent.new(string, *args)
- end
- end
- end
-
- class StaticComponent < Component #:nodoc:
- attr_reader :value
-
- def initialize(value)
- @value = value
+ # Write the real generation implementation and then resend the message.
+ def generate(options, hash, expire_on = {})
+ write_generation
+ generate options, hash, expire_on
end
- def write_recognition(g)
- g.if_next_matches(value) do |gp|
- gp.move_forward {|gpp| gpp.continue}
+ def generate_extras(options, hash, expire_on = {})
+ write_generation
+ generate_extras options, hash, expire_on
+ end
+
+ # Generate the query string with any extra keys in the hash and append
+ # it to the given path, returning the new path.
+ def append_query_string(path, hash, query_keys=nil)
+ return nil unless path
+ query_keys ||= extra_keys(hash)
+ "#{path}#{build_query_string(hash, query_keys)}"
+ end
+
+ # Determine which keys in the given hash are "extra". Extra keys are
+ # those that were not used to generate a particular route. The extra
+ # keys also do not include those recalled from the prior request, nor
+ # do they include any keys that were implied in the route (like a
+ # :controller that is required, but not explicitly used in the text of
+ # the route.)
+ def extra_keys(hash, recall={})
+ (hash || {}).keys.map { |k| k.to_sym } - (recall || {}).keys - significant_keys
+ end
+
+ # Build a query string from the keys of the given hash. If +only_keys+
+ # is given (as an array), only the keys indicated will be used to build
+ # the query string. The query string will correctly build array parameter
+ # values.
+ def build_query_string(hash, only_keys=nil)
+ elements = []
+
+ only_keys ||= hash.keys
+
+ only_keys.each do |key|
+ value = hash[key] or next
+ key = CGI.escape key.to_s
+ if value.class == Array
+ key << '[]'
+ else
+ value = [ value ]
+ end
+ value.each { |val| elements << "#{key}=#{CGI.escape(val.to_param.to_s)}" }
+ end
+
+ query_string = "?#{elements.join("&")}" unless elements.empty?
+ query_string || ""
+ end
+
+ # Write the real recognition implementation and then resend the message.
+ def recognize(path, environment={})
+ write_recognition
+ recognize path, environment
+ end
+
+ # A route's parameter shell contains parameter values that are not in the
+ # route's path, but should be placed in the recognized hash.
+ #
+ # For example, +{:controller => 'pages', :action => 'show'} is the shell for the route:
+ #
+ # map.connect '/page/:id', :controller => 'pages', :action => 'show', :id => /\d+/
+ #
+ def parameter_shell
+ @parameter_shell ||= returning({}) do |shell|
+ requirements.each do |key, requirement|
+ shell[key] = requirement unless requirement.is_a? Regexp
+ end
+ end
+ end
+
+ # Return an array containing all the keys that are used in this route. This
+ # includes keys that appear inside the path, and keys that have requirements
+ # placed upon them.
+ def significant_keys
+ @significant_keys ||= returning [] do |sk|
+ segments.each { |segment| sk << segment.key if segment.respond_to? :key }
+ sk.concat requirements.keys
+ sk.uniq!
end
end
- def write_generation(g)
- g.add_segment(value) {|gp| gp.continue }
+ # Return a hash of key/value pairs representing the keys in the route that
+ # have defaults, or which are specified by non-regexp requirements.
+ def defaults
+ @defaults ||= returning({}) do |hash|
+ segments.each do |segment|
+ next unless segment.respond_to? :default
+ hash[segment.key] = segment.default unless segment.default.nil?
+ end
+ requirements.each do |key,req|
+ next if Regexp === req || req.nil?
+ hash[key] = req
+ end
+ end
end
+
+ def matches_controller_and_action?(controller, action)
+ unless @matching_prepared
+ @controller_requirement = requirement_for(:controller)
+ @action_requirement = requirement_for(:action)
+ @matching_prepared = true
+ end
+
+ (@controller_requirement.nil? || @controller_requirement === controller) &&
+ (@action_requirement.nil? || @action_requirement === action)
+ end
+
+ def to_s
+ @to_s ||= begin
+ segs = segments.inject("") { |str,s| str << s.to_s }
+ "%-6s %-40s %s" % [(conditions[:method] || :any).to_s.upcase, segs, requirements.inspect]
+ end
+ end
+
+ protected
+ def requirement_for(key)
+ return requirements[key] if requirements.key? key
+ segments.each do |segment|
+ return segment.regexp if segment.respond_to?(:key) && segment.key == key
+ end
+ nil
+ end
+
end
- class DynamicComponent < Component #:nodoc:
- attr_reader :key, :default
- attr_accessor :condition
+ class Segment #:nodoc:
+ attr_accessor :is_optional
+ alias_method :optional?, :is_optional
+
+ def initialize
+ self.is_optional = false
+ end
+
+ def extraction_code
+ nil
+ end
- def dynamic?() true end
- def optional?() @optional end
-
- def default=(default)
- @optional = true
- @default = default
- end
-
- def initialize(key, options = {})
- @key = key.to_sym
- @optional = false
- default, @condition = options[:default], options[:condition]
- self.default = default if options.key?(:default)
- end
-
- def default_check(g)
- presence = "#{g.hash_value(key, !! default)}"
- if default
- "!(#{presence} && #{g.hash_value(key, false)} != #{default.to_s.inspect})"
+ # Continue generating string for the prior segments.
+ def continue_string_structure(prior_segments)
+ if prior_segments.empty?
+ interpolation_statement(prior_segments)
else
- "! #{presence}"
+ new_priors = prior_segments[0..-2]
+ prior_segments.last.string_structure(new_priors)
end
end
- def write_generation(g)
- wrote_dropout = write_dropout_generation(g)
- write_continue_generation(g, wrote_dropout)
- end
-
- def write_dropout_generation(g)
- return false unless optional? && g.after.all? {|c| c.optional?}
-
- check = [default_check(g)]
- gp = g.dup # Use another generator to write the conditions after the first &&
- # We do this to ensure that the generator will not assume x_value is set. It will
- # not be set if it follows a false condition -- for example, false && (x = 2)
-
- check += gp.after.map {|c| c.default_check gp}
- gp.if(check.join(' && ')) { gp.finish } # If this condition is met, we stop here
- true
- end
-
- def write_continue_generation(g, use_else)
- test = Routing.test_condition(g.hash_value(key, true, default), condition || true)
- check = (use_else && condition.nil? && default) ? [:else] : [use_else ? :elsif : :if, test]
-
- g.send(*check) do |gp|
- gp.expire_for_keys(key) unless gp.after.empty?
- add_segments_to(gp) {|gpp| gpp.continue}
- end
- end
-
- def add_segments_to(g)
- g.add_segment(%(\#{CGI.escape(#{g.hash_value(key, true, default)})})) {|gp| yield gp}
+ # Return a string interpolation statement for this segment and those before it.
+ def interpolation_statement(prior_segments)
+ chunks = prior_segments.collect { |s| s.interpolation_chunk }
+ chunks << interpolation_chunk
+ "\"#{chunks * ''}\"#{all_optionals_available_condition(prior_segments)}"
end
- def recognition_check(g)
- test_type = [true, nil].include?(condition) ? :presence : :constraint
-
- prefix = condition.is_a?(Regexp) ? "#{g.next_segment(true)} && " : ''
- check = prefix + Routing.test_condition(g.next_segment(true), condition || true)
-
- g.if(check) {|gp| yield gp, test_type}
+ def string_structure(prior_segments)
+ optional? ? continue_string_structure(prior_segments) : interpolation_statement(prior_segments)
end
- def write_recognition(g)
- test_type = nil
- recognition_check(g) do |gp, test_type|
- assign_result(gp) {|gpp| gpp.continue}
- end
-
- if optional? && g.after.all? {|c| c.optional?}
- call = (test_type == :presence) ? [:else] : [:elsif, "! #{g.next_segment(true)}"]
-
- g.send(*call) do |gp|
- assign_default(gp)
- gp.after.each {|c| c.assign_default(gp)}
- gp.finish(false)
- end
- end
+ # Return an if condition that is true if all the prior segments can be generated.
+ # If there are no optional segments before this one, then nil is returned.
+ def all_optionals_available_condition(prior_segments)
+ optional_locals = prior_segments.collect { |s| s.local_name if s.optional? && s.respond_to?(:local_name) }.compact
+ optional_locals.empty? ? nil : " if #{optional_locals * ' && '}"
end
-
- def assign_result(g, with_default = false)
- g.result key, "CGI.unescape(#{g.next_segment(true, with_default ? default : nil)})"
- g.move_forward {|gp| yield gp}
+
+ # Recognition
+
+ def match_extraction(next_capture)
+ nil
end
-
- def assign_default(g)
- g.constant_result key, default unless default.nil?
+
+ # Warning
+
+ # Returns true if this segment is optional? because of a default. If so, then
+ # no warning will be emitted regarding this segment.
+ def optionality_implied?
+ false
end
end
- class ControllerComponent < DynamicComponent #:nodoc:
- def key() :controller end
-
- def add_segments_to(g)
- g.add_segment(%(\#{#{g.hash_value(key, true, default)}})) {|gp| yield gp}
- end
-
- def recognition_check(g)
- g << "controller_result = ::ActionController::Routing::ControllerComponent.traverse_to_controller(#{g.path_name}, #{g.index_name})"
- g.if('controller_result') do |gp|
- gp << 'controller_value, segments_to_controller = controller_result'
- if condition
- gp << "controller_path = #{gp.path_name}[#{gp.index_name},segments_to_controller].join('/')"
- gp.if(Routing.test_condition("controller_path", condition)) do |gpp|
- gpp.move_forward('segments_to_controller') {|gppp| yield gppp, :constraint}
- end
- else
- gp.move_forward('segments_to_controller') {|gpp| yield gpp, :constraint}
- end
- end
- end
-
- def assign_result(g)
- g.result key, 'controller_value'
- yield g
- end
-
- def assign_default(g)
- ControllerComponent.assign_controller(g, default)
+ class StaticSegment < Segment #:nodoc:
+ attr_accessor :value, :raw
+ alias_method :raw?, :raw
+
+ def initialize(value = nil)
+ super()
+ self.value = value
end
- class << self
- def assign_controller(g, controller)
- expr = "::#{controller.split('/').collect {|c| c.camelize}.join('::')}Controller"
- g.result :controller, expr, true
+ def interpolation_chunk
+ raw? ? value : CGI.escape(value)
+ end
+
+ def regexp_chunk
+ chunk = Regexp.escape value
+ optional? ? Regexp.optionalize(chunk) : chunk
+ end
+
+ def build_pattern(pattern)
+ escaped = Regexp.escape(value)
+ if optional? && ! pattern.empty?
+ "(?:#{Regexp.optionalize escaped}\\Z|#{escaped}#{Regexp.unoptionalize pattern})"
+ elsif optional?
+ Regexp.optionalize escaped
+ else
+ escaped + pattern
end
+ end
+
+ def to_s
+ value
+ end
+ end
- def traverse_to_controller(segments, start_at = 0)
- mod = ::Object
- length = segments.length
- index = start_at
- mod_name = controller_name = segment = nil
- while index < length
- return nil unless /\A[A-Za-z][A-Za-z\d_]*\Z/ =~ (segment = segments[index])
- index += 1
-
- mod_name = segment.camelize
- controller_name = "#{mod_name}Controller"
- path_suffix = File.join(segments[start_at..(index - 1)])
- next_mod = nil
-
- # If the controller is already present, or if we load it, return it.
- if mod.const_defined?(controller_name) || attempt_load(mod, controller_name, path_suffix + "_controller") == :defined
- controller = mod.const_get(controller_name)
- return nil unless controller.is_a?(Class) && controller.ancestors.include?(ActionController::Base) # it's not really a controller?
- return [controller, (index - start_at)]
- end
-
- # No controller? Look for the module
- if mod.const_defined? mod_name
- next_mod = mod.send(:const_get, mod_name)
- next_mod = nil unless next_mod.is_a?(Module)
- else
- # Try to load a file that defines the module we want.
- case attempt_load(mod, mod_name, path_suffix)
- when :defined then next_mod = mod.const_get mod_name
- when :dir then # We didn't find a file, but there's a dir.
- next_mod = Module.new # So create a module for the directory
- mod.send :const_set, mod_name, next_mod
- else
- return nil
- end
- end
- mod = next_mod
-
- return nil unless mod && mod.is_a?(Module)
- end
- nil
+ class DividerSegment < StaticSegment #:nodoc:
+ def initialize(value = nil)
+ super(value)
+ self.raw = true
+ self.is_optional = true
+ end
+
+ def optionality_implied?
+ true
+ end
+ end
+
+ class DynamicSegment < Segment #:nodoc:
+ attr_accessor :key, :default, :regexp
+
+ def initialize(key = nil, options = {})
+ super()
+ self.key = key
+ self.default = options[:default] if options.key? :default
+ self.is_optional = true if options[:optional] || options.key?(:default)
+ end
+
+ def to_s
+ ":#{key}"
+ end
+
+ # The local variable name that the value of this segment will be extracted to.
+ def local_name
+ "#{key}_value"
+ end
+
+ def extract_value
+ "#{local_name} = hash[:#{key}] #{"|| #{default.inspect}" if default}"
+ end
+ def value_check
+ if default # Then we know it won't be nil
+ "#{value_regexp.inspect} =~ #{local_name}" if regexp
+ elsif optional?
+ # If we have a regexp check that the value is not given, or that it matches.
+ # If we have no regexp, return nil since we do not require a condition.
+ "#{local_name}.nil? || #{value_regexp.inspect} =~ #{local_name}" if regexp
+ else # Then it must be present, and if we have a regexp, it must match too.
+ "#{local_name} #{"&& #{value_regexp.inspect} =~ #{local_name}" if regexp}"
end
-
- protected
- def safe_load_paths #:nodoc:
- if defined?(RAILS_ROOT)
- $LOAD_PATH.select do |base|
- base = File.expand_path(base)
- extended_root = File.expand_path(RAILS_ROOT)
- # Exclude all paths that are not nested within app, lib, or components.
- base.match(/\A#{Regexp.escape(extended_root)}\/*(app|lib|components)\/[a-z]/) || base =~ %r{rails-[\d.]+/builtin}
- end
- else
- $LOAD_PATH
- end
+ end
+ def expiry_statement
+ "expired, hash = true, options if !expired && expire_on[:#{key}]"
+ end
+
+ def extraction_code
+ s = extract_value
+ vc = value_check
+ s << "\nreturn [nil,nil] unless #{vc}" if vc
+ s << "\n#{expiry_statement}"
+ end
+
+ def interpolation_chunk
+ "\#{CGI.escape(#{local_name}.to_s)}"
+ end
+
+ def string_structure(prior_segments)
+ if optional? # We have a conditional to do...
+ # If we should not appear in the url, just write the code for the prior
+ # segments. This occurs if our value is the default value, or, if we are
+ # optional, if we have nil as our value.
+ "if #{local_name} == #{default.inspect}\n" +
+ continue_string_structure(prior_segments) +
+ "\nelse\n" + # Otherwise, write the code up to here
+ "#{interpolation_statement(prior_segments)}\nend"
+ else
+ interpolation_statement(prior_segments)
end
+ end
+
+ def value_regexp
+ Regexp.new "\\A#{regexp.source}\\Z" if regexp
+ end
+ def regexp_chunk
+ regexp ? "(#{regexp.source})" : "([^#{Routing::SEPARATORS.join}]+)"
+ end
+
+ def build_pattern(pattern)
+ chunk = regexp_chunk
+ chunk = "(#{chunk})" if Regexp.new(chunk).number_of_captures == 0
+ pattern = "#{chunk}#{pattern}"
+ optional? ? Regexp.optionalize(pattern) : pattern
+ end
+ def match_extraction(next_capture)
+ hangon = (default ? "|| #{default.inspect}" : "if match[#{next_capture}]")
- def attempt_load(mod, const_name, path)
- has_dir = false
- safe_load_paths.each do |load_path|
- full_path = File.join(load_path, path)
- file_path = full_path + '.rb'
- if File.file?(file_path) # Found a .rb file? Load it up
- require_dependency(file_path)
- return :defined if mod.const_defined? const_name
- else
- has_dir ||= File.directory?(full_path)
- end
- end
- return (has_dir ? :dir : nil)
+ # All non code-related keys (such as :id, :slug) have to be unescaped as other CGI params
+ "params[:#{key}] = match[#{next_capture}] #{hangon}"
+ end
+
+ def optionality_implied?
+ [:action, :id].include? key
+ end
+
+ end
+
+ class ControllerSegment < DynamicSegment #:nodoc:
+ def regexp_chunk
+ possible_names = Routing.possible_controllers.collect { |name| Regexp.escape name }
+ "(?i-:(#{(regexp || Regexp.union(*possible_names)).source}))"
+ end
+
+ # Don't CGI.escape the controller name, since it may have slashes in it,
+ # like admin/foo.
+ def interpolation_chunk
+ "\#{#{local_name}.to_s}"
+ end
+
+ # Make sure controller names like Admin/Content are correctly normalized to
+ # admin/content
+ def extract_value
+ "#{local_name} = (hash[:#{key}] #{"|| #{default.inspect}" if default}).downcase"
+ end
+
+ def match_extraction(next_capture)
+ if default
+ "params[:#{key}] = match[#{next_capture}] ? match[#{next_capture}].downcase : '#{default}'"
+ else
+ "params[:#{key}] = match[#{next_capture}].downcase if match[#{next_capture}]"
end
end
end
- class PathComponent < DynamicComponent #:nodoc:
- def optional?() true end
- def default() [] end
- def condition() nil end
+ class PathSegment < DynamicSegment #:nodoc:
+ EscapedSlash = CGI.escape("/")
+ def interpolation_chunk
+ "\#{CGI.escape(#{local_name}.to_s).gsub(#{EscapedSlash.inspect}, '/')}"
+ end
- def default=(value)
- raise RoutingError, "All path components have an implicit default of []" unless value == []
+ def default
+ ''
end
-
- def write_generation(g)
- raise RoutingError, 'Path components must occur last' unless g.after.empty?
- g.if("#{g.hash_value(key, true)} && ! #{g.hash_value(key, true)}.empty?") do
- g << "#{g.hash_value(key, true)} = #{g.hash_value(key, true)}.join('/') unless #{g.hash_value(key, true)}.is_a?(String)"
- g.add_segment("\#{CGI.escape_skipping_slashes(#{g.hash_value(key, true)})}") {|gp| gp.finish }
- end
- g.else { g.finish }
+
+ def default=(path)
+ raise RoutingError, "paths cannot have non-empty default values" unless path.blank?
end
-
- def write_recognition(g)
- raise RoutingError, "Path components must occur last" unless g.after.empty?
-
- start = g.index_name
- start = "(#{start})" unless /^\w+$/ =~ start
-
- value_expr = "#{g.path_name}[#{start}..-1] || []"
- g.result key, "ActionController::Routing::PathComponent::Result.new_escaped(#{value_expr})"
- g.finish(false)
+
+ def match_extraction(next_capture)
+ "params[:#{key}] = PathSegment::Result.new_escaped((match[#{next_capture}]#{" || " + default.inspect if default}).split('/'))#{" if match[" + next_capture + "]" if !default}"
end
-
+
+ def regexp_chunk
+ regexp || "(.*)"
+ end
+
class Result < ::Array #:nodoc:
- def to_s() join '/' end
+ def to_s() join '/' end
def self.new_escaped(strings)
new strings.collect {|str| CGI.unescape str}
- end
- end
+ end
+ end
end
- class Route #:nodoc:
- attr_accessor :components, :known
- attr_reader :path, :options, :keys, :defaults
+ class RouteBuilder #:nodoc:
+ attr_accessor :separators, :optional_separators
- def initialize(path, options = {})
- @path, @options = path, options
+ def initialize
+ self.separators = Routing::SEPARATORS
+ self.optional_separators = %w( / )
+ end
+
+ def separator_pattern(inverted = false)
+ "[#{'^' if inverted}#{Regexp.escape(separators.join)}]"
+ end
+
+ def interval_regexp
+ Regexp.new "(.*?)(#{separators.source}|$)"
+ end
+
+ # Accepts a "route path" (a string defining a route), and returns the array
+ # of segments that corresponds to it. Note that the segment array is only
+ # partially initialized--the defaults and requirements, for instance, need
+ # to be set separately, via the #assign_route_options method, and the
+ # #optional? method for each segment will not be reliable until after
+ # #assign_route_options is called, as well.
+ def segments_for_route_path(path)
+ rest, segments = path, []
- initialize_components path
- defaults, conditions = initialize_hashes options.dup
- @defaults = defaults.dup
- configure_components(defaults, conditions)
- add_default_requirements
- initialize_keys
+ until rest.empty?
+ segment, rest = segment_for rest
+ segments << segment
+ end
+ segments
end
-
- def inspect
- "<#{self.class} #{path.inspect}, #{options.inspect[1..-1]}>"
- end
-
- def write_generation(generator = CodeGeneration::GenerationGenerator.new)
- generator.before, generator.current, generator.after = [], components.first, (components[1..-1] || [])
- if known.empty? then generator.go
- else
- # Alter the conditions to allow :action => 'index' to also catch :action => nil
- altered_known = known.collect do |k, v|
- if k == :action && v== 'index' then [k, [nil, 'index']]
- else [k, v]
+ # A factory method that returns a new segment instance appropriate for the
+ # format of the given string.
+ def segment_for(string)
+ segment = case string
+ when /\A:(\w+)/
+ key = $1.to_sym
+ case key
+ when :controller then ControllerSegment.new(key)
+ else DynamicSegment.new key
+ end
+ when /\A\*(\w+)/ then PathSegment.new($1.to_sym, :optional => true)
+ when /\A\?(.*?)\?/
+ returning segment = StaticSegment.new($1) do
+ segment.is_optional = true
+ end
+ when /\A(#{separator_pattern(:inverted)}+)/ then StaticSegment.new($1)
+ when Regexp.new(separator_pattern) then
+ returning segment = DividerSegment.new($&) do
+ segment.is_optional = (optional_separators.include? $&)
end
- end
- generator.if(generator.check_conditions(altered_known)) {|gp| gp.go }
end
-
- generator
+ [segment, $~.post_match]
end
- def write_recognition(generator = CodeGeneration::RecognitionGenerator.new)
- g = generator.dup
- g.share_locals_with generator
- g.before, g.current, g.after = [], components.first, (components[1..-1] || [])
-
- known.each do |key, value|
- if key == :controller then ControllerComponent.assign_controller(g, value)
- else g.constant_result(key, value)
- end
- end
-
- g.go
-
- generator
- end
+ # Split the given hash of options into requirement and default hashes. The
+ # segments are passed alongside in order to distinguish between default values
+ # and requirements.
+ def divide_route_options(segments, options)
+ options = options.dup
+ requirements = (options.delete(:requirements) || {}).dup
+ defaults = (options.delete(:defaults) || {}).dup
+ conditions = (options.delete(:conditions) || {}).dup
- def initialize_keys
- @keys = (components.collect {|c| c.key} + known.keys).compact
- @keys.freeze
- end
-
- def extra_keys(options)
- options.keys - @keys
- end
-
- def matches_controller?(controller)
- if known[:controller] then known[:controller] == controller
- else
- c = components.find {|c| c.key == :controller}
- return false unless c
- return c.condition.nil? || eval(Routing.test_condition('controller', c.condition))
- end
- end
-
- protected
- def initialize_components(path)
- path = path.split('/') if path.is_a? String
- path.shift if path.first.blank?
- self.components = path.collect {|str| Component.new str}
+ path_keys = segments.collect { |segment| segment.key if segment.respond_to?(:key) }.compact
+ options.each do |key, value|
+ hash = (path_keys.include?(key) && ! value.is_a?(Regexp)) ? defaults : requirements
+ hash[key] = value
end
- def initialize_hashes(options)
- path_keys = components.collect {|c| c.key }.compact
- self.known = {}
- defaults = options.delete(:defaults) || {}
- conditions = options.delete(:require) || {}
- conditions.update(options.delete(:requirements) || {})
+ [defaults, requirements, conditions]
+ end
- options.each do |k, v|
- if path_keys.include?(k) then (v.is_a?(Regexp) ? conditions : defaults)[k] = v
- else known[k] = v
- end
- end
- [defaults, conditions]
+ # Takes a hash of defaults and a hash of requirements, and assigns them to
+ # the segments. Any unused requirements (which do not correspond to a segment)
+ # are returned as a hash.
+ def assign_route_options(segments, defaults, requirements)
+ route_requirements = {} # Requirements that do not belong to a segment
+
+ segment_named = Proc.new do |key|
+ segments.detect { |segment| segment.key == key if segment.respond_to?(:key) }
end
+
+ requirements.each do |key, requirement|
+ segment = segment_named[key]
+ if segment
+ raise TypeError, "#{key}: requirements on a path segment must be regular expressions" unless requirement.is_a?(Regexp)
+ if requirement.source =~ %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
+ raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
+ end
+ segment.regexp = requirement
+ else
+ route_requirements[key] = requirement
+ end
+ end
+
+ defaults.each do |key, default|
+ segment = segment_named[key]
+ raise ArgumentError, "#{key}: No matching segment exists; cannot assign default" unless segment
+ segment.is_optional = true
+ segment.default = default.to_param if default
+ end
+
+ assign_default_route_options(segments)
+ ensure_required_segments(segments)
+ route_requirements
+ end
+
+ # Assign default options, such as 'index' as a default for :action. This
+ # method must be run *after* user supplied requirements and defaults have
+ # been applied to the segments.
+ def assign_default_route_options(segments)
+ segments.each do |segment|
+ next unless segment.is_a? DynamicSegment
+ case segment.key
+ when :action
+ if segment.regexp.nil? || segment.regexp.match('index').to_s == 'index'
+ segment.default ||= 'index'
+ segment.is_optional = true
+ end
+ when :id
+ if segment.default.nil? && segment.regexp.nil? || segment.regexp =~ ''
+ segment.is_optional = true
+ end
+ end
+ end
+ end
+
+ # Makes sure that there are no optional segments that precede a required
+ # segment. If any are found that precede a required segment, they are
+ # made required.
+ def ensure_required_segments(segments)
+ allow_optional = true
+ segments.reverse_each do |segment|
+ allow_optional &&= segment.optional?
+ if !allow_optional && segment.optional?
+ unless segment.optionality_implied?
+ warn "Route segment \"#{segment.to_s}\" cannot be optional because it precedes a required segment. This segment will be required."
+ end
+ segment.is_optional = false
+ elsif allow_optional & segment.respond_to?(:default) && segment.default
+ # if a segment has a default, then it is optional
+ segment.is_optional = true
+ end
+ end
+ end
+
+ # Construct and return a route with the given path and options.
+ def build(path, options)
+ # Wrap the path with slashes
+ path = "/#{path}" unless path[0] == ?/
+ path = "#{path}/" unless path[-1] == ?/
- def configure_components(defaults, conditions)
- components.each do |component|
- if defaults.key?(component.key) then component.default = defaults[component.key]
- elsif component.key == :action then component.default = 'index'
- elsif component.key == :id then component.default = nil
- end
-
- component.condition = conditions[component.key] if conditions.key?(component.key)
- end
+ segments = segments_for_route_path(path)
+ defaults, requirements, conditions = divide_route_options(segments, options)
+ requirements = assign_route_options(segments, defaults, requirements)
+
+ route = Route.new
+ route.segments = segments
+ route.requirements = requirements
+ route.conditions = conditions
+
+ if !route.significant_keys.include?(:action) && !route.requirements[:action]
+ route.requirements[:action] = "index"
+ route.significant_keys << :action
end
-
- def add_default_requirements
- component_keys = components.collect {|c| c.key}
- known[:action] ||= 'index' unless component_keys.include? :action
+
+ if !route.significant_keys.include?(:controller)
+ raise ArgumentError, "Illegal route: the :controller must be specified!"
end
+
+ route
+ end
end
class RouteSet #:nodoc:
- attr_reader :routes, :categories, :controller_to_selector
- def initialize
- @routes = []
- @generation_methods = Hash.new(:generate_default_path)
- end
-
- def generate(options, request_or_recall_hash = {})
- recall = request_or_recall_hash.is_a?(Hash) ? request_or_recall_hash : request_or_recall_hash.symbolized_path_parameters
- use_recall = true
-
- controller = options[:controller]
- options[:action] ||= 'index' if controller
- recall_controller = recall[:controller]
- if (recall_controller && recall_controller.include?(?/)) || (controller && controller.include?(?/))
- recall = {} if controller && controller[0] == ?/
- options[:controller] = Routing.controller_relative_to(controller, recall_controller)
+ # Mapper instances are used to build routes. The object passed to the draw
+ # block in config/routes.rb is a Mapper instance.
+ #
+ # Mapper instances have relatively few instance methods, in order to avoid
+ # clashes with named routes.
+ class Mapper #:nodoc:
+ def initialize(set)
+ @set = set
end
- options = recall.dup if options.empty? # XXX move to url_rewriter?
-
- keys_to_delete = []
- Routing.treat_hash(options, keys_to_delete)
-
- merged = recall.merge(options)
- keys_to_delete.each {|key| merged.delete key}
- expire_on = Routing.expiry_hash(options, recall)
- generate_path(merged, options, expire_on)
+ # Create an unnamed route with the provided +path+ and +options+. See
+ # SomeHelpfulUrl for an introduction to routes.
+ def connect(path, options = {})
+ @set.add_route(path, options)
+ end
+
+ def named_route(name, path, options = {})
+ @set.add_named_route(name, path, options)
+ end
+
+ # Added deprecation notice for anyone who already added a named route called "root".
+ # It'll be used as a shortcut for map.connect '' in Rails 2.0.
+ def root(*args, &proc)
+ super unless args.length >= 1 && proc.nil?
+ @set.add_named_route("root", *args)
+ end
+ deprecate :root => "(as the the label for a named route) will become a shortcut for map.connect '', so find another name"
+
+ def method_missing(route_name, *args, &proc)
+ super unless args.length >= 1 && proc.nil?
+ @set.add_named_route(route_name, *args)
+ end
end
-
- def generate_path(merged, options, expire_on)
- send @generation_methods[merged[:controller]], merged, options, expire_on
- end
- def generate_default_path(*args)
- write_generation
- generate_default_path(*args)
- end
-
- def write_generation
- method_sources = []
- @generation_methods = Hash.new(:generate_default_path)
- categorize_routes.each do |controller, routes|
- next unless routes.length < @routes.length
-
- ivar = controller.gsub('/', '__')
- method_name = "generate_path_for_#{ivar}".to_sym
- instance_variable_set "@#{ivar}", routes
- code = generation_code_for(ivar, method_name).to_s
- method_sources << code
+
+ # A NamedRouteCollection instance is a collection of named routes, and also
+ # maintains an anonymous module that can be used to install helpers for the
+ # named routes.
+ class NamedRouteCollection #:nodoc:
+ include Enumerable
+
+ attr_reader :routes, :helpers
+
+ def initialize
+ clear!
+ end
+
+ def clear!
+ @routes = {}
+ @helpers = []
- filename = "generated_code/routing/generation_for_controller_#{controller}.rb"
- eval(code, nil, filename)
-
- @generation_methods[controller.to_s] = method_name
- @generation_methods[controller.to_sym] = method_name
- end
-
- code = generation_code_for('routes', 'generate_default_path').to_s
- eval(code, nil, 'generated_code/routing/generation.rb')
-
- return (method_sources << code)
- end
-
- def recognize(request)
- string_path = request.path
- string_path.chomp! if string_path[0] == ?/
- path = string_path.split '/'
- path.shift
-
- hash = recognize_path(path)
- return recognition_failed(request) unless hash && hash['controller']
-
- controller = hash['controller']
- hash['controller'] = controller.controller_path
- request.path_parameters = hash
- controller.new
- end
- alias :recognize! :recognize
-
- def recognition_failed(request)
- raise ActionController::RoutingError, "Recognition failed for #{request.path.inspect}"
- end
-
- def write_recognition
- g = generator = CodeGeneration::RecognitionGenerator.new
- g.finish_statement = Proc.new {|hash_expr| "return #{hash_expr}"}
-
- g.def "self.recognize_path(path)" do
- each do |route|
- g << 'index = 0'
- route.write_recognition(g)
+ @module ||= Module.new
+ @module.instance_methods.each do |selector|
+ @module.send :remove_method, selector
end
end
-
- eval g.to_s, nil, 'generated/routing/recognition.rb'
- return g.to_s
- end
-
- def generation_code_for(ivar = 'routes', method_name = nil)
- routes = instance_variable_get('@' + ivar)
- key_ivar = "@keys_for_#{ivar}"
- instance_variable_set(key_ivar, routes.collect {|route| route.keys})
-
- g = generator = CodeGeneration::GenerationGenerator.new
- g.def "self.#{method_name}(merged, options, expire_on)" do
- g << 'unused_count = options.length + 1'
- g << "unused_keys = keys = options.keys"
- g << 'path = nil'
-
- routes.each_with_index do |route, index|
- g << "new_unused_keys = keys - #{key_ivar}[#{index}]"
- g << 'new_path = ('
- g.source.indent do
- if index.zero?
- g << "new_unused_count = new_unused_keys.length"
- g << "hash = merged; not_expired = true"
- route.write_generation(g.dup)
- else
- g.if "(new_unused_count = new_unused_keys.length) < unused_count" do |gp|
- gp << "hash = merged; not_expired = true"
- route.write_generation(gp)
- end
+
+ def add(name, route)
+ routes[name.to_sym] = route
+ define_named_route_methods(name, route)
+ end
+
+ def get(name)
+ routes[name.to_sym]
+ end
+
+ alias []= add
+ alias [] get
+ alias clear clear!
+
+ def each
+ routes.each { |name, route| yield name, route }
+ self
+ end
+
+ def names
+ routes.keys
+ end
+
+ def length
+ routes.length
+ end
+
+ def install(destinations = [ActionController::Base, ActionView::Base])
+ Array(destinations).each { |dest| dest.send :include, @module }
+ end
+
+ private
+ def url_helper_name(name, kind = :url)
+ :"#{name}_#{kind}"
+ end
+
+ def hash_access_name(name, kind = :url)
+ :"hash_for_#{name}_#{kind}"
+ end
+
+ def define_named_route_methods(name, route)
+ {:url => {:only_path => false}, :path => {:only_path => true}}.each do |kind, opts|
+ hash = route.defaults.merge(:use_route => name).merge(opts)
+ define_hash_access route, name, kind, hash
+ define_url_helper route, name, kind, hash
+ end
+ end
+
+ def define_hash_access(route, name, kind, options)
+ selector = hash_access_name(name, kind)
+ @module.send :module_eval, <<-end_eval # We use module_eval to avoid leaks
+ def #{selector}(options = nil)
+ options ? #{options.inspect}.merge(options) : #{options.inspect}
end
- end
- g.source.lines.last << ' )' # Add the closing brace to the end line
- g.if 'new_path' do
- g << 'return new_path, [] if new_unused_count.zero?'
- g << 'path = new_path; unused_keys = new_unused_keys; unused_count = new_unused_count'
- end
+ end_eval
+ @module.send(:protected, selector)
+ helpers << selector
end
-
- g << "raise RoutingError, \"No url can be generated for the hash \#{options.inspect}\" unless path"
- g << "return path, unused_keys"
- end
-
- return g
+
+ def define_url_helper(route, name, kind, options)
+ selector = url_helper_name(name, kind)
+
+ # The segment keys used for positional paramters
+ segment_keys = route.segments.collect do |segment|
+ segment.key if segment.respond_to? :key
+ end.compact
+ hash_access_method = hash_access_name(name, kind)
+
+ @module.send :module_eval, <<-end_eval # We use module_eval to avoid leaks
+ def #{selector}(*args)
+ opts = if args.empty? || Hash === args.first
+ args.first || {}
+ else
+ # allow ordered parameters to be associated with corresponding
+ # dynamic segments, so you can do
+ #
+ # foo_url(bar, baz, bang)
+ #
+ # instead of
+ #
+ # foo_url(:bar => bar, :baz => baz, :bang => bang)
+ args.zip(#{segment_keys.inspect}).inject({}) do |h, (v, k)|
+ h[k] = v
+ h
+ end
+ end
+
+ url_for(#{hash_access_method}(opts))
+ end
+ end_eval
+ @module.send(:protected, selector)
+ helpers << selector
+ end
+
end
-
- def categorize_routes
- @categorized_routes = by_controller = Hash.new(self)
-
- known_controllers.each do |name|
- set = by_controller[name] = []
- each do |route|
- set << route if route.matches_controller? name
- end
- end
-
- @categorized_routes
- end
-
- def known_controllers
- @routes.inject([]) do |known, route|
- if (controller = route.known[:controller])
- if controller.is_a?(Regexp)
- known << controller.source.scan(%r{[\w\d/]+}).select {|word| controller =~ word}
- else known << controller
- end
- end
- known
- end.uniq
+
+ attr_accessor :routes, :named_routes
+
+ def initialize
+ self.routes = []
+ self.named_routes = NamedRouteCollection.new
end
- def reload
- NamedRoutes.clear
-
- if defined?(RAILS_ROOT) then load(File.join(RAILS_ROOT, 'config', 'routes.rb'))
- else connect(':controller/:action/:id', :action => 'index', :id => nil)
- end
-
- NamedRoutes.install
- end
-
- def connect(*args)
- new_route = Route.new(*args)
- @routes << new_route
- return new_route
+ # Subclasses and plugins may override this method to specify a different
+ # RouteBuilder instance, so that other route DSL's can be created.
+ def builder
+ @builder ||= RouteBuilder.new
end
def draw
- old_routes = @routes
- @routes = []
-
- begin yield self
- rescue
- @routes = old_routes
- raise
- end
- write_generation
- write_recognition
+ clear!
+ yield Mapper.new(self)
+ named_routes.install
end
-
- def empty?() @routes.empty? end
- def each(&block) @routes.each(&block) end
-
- # Defines a new named route with the provided name and arguments.
- # This method need only be used when you wish to use a name that a RouteSet instance
- # method exists for, such as categories.
- #
- # For example, map.categories '/categories', :controller => 'categories' will not work
- # due to RouteSet#categories.
- def named_route(name, path, hash = {})
- route = connect(path, hash)
- NamedRoutes.name_route(route, name)
+ def clear!
+ routes.clear
+ named_routes.clear
+ @combined_regexp = nil
+ @routes_by_controller = nil
+ end
+
+ def empty?
+ routes.empty?
+ end
+
+ def load!
+ Routing.use_controllers! nil # Clear the controller cache so we may discover new ones
+ clear!
+ load_routes!
+ named_routes.install
+ end
+
+ alias reload load!
+
+ def load_routes!
+ if defined?(RAILS_ROOT) && defined?(::ActionController::Routing::Routes) && self == ::ActionController::Routing::Routes
+ load File.join("#{RAILS_ROOT}/config/routes.rb")
+ else
+ add_route ":controller/:action/:id"
+ end
+ end
+
+ def add_route(path, options = {})
+ route = builder.build(path, options)
+ routes << route
route
end
-
- def method_missing(name, *args)
- (1..2).include?(args.length) ? named_route(name, *args) : super(name, *args)
- end
-
- def extra_keys(options, recall = {})
- generate(options.dup, recall).last
- end
- end
-
- module NamedRoutes #:nodoc:
- Helpers = []
- class << self
- def clear() Helpers.clear end
- def hash_access_name(name)
- "hash_for_#{name}_url"
+ def add_named_route(name, path, options = {})
+ named_routes[name] = add_route(path, options)
+ end
+
+ def options_as_params(options)
+ # If an explicit :controller was given, always make :action explicit
+ # too, so that action expiry works as expected for things like
+ #
+ # generate({:controller => 'content'}, {:controller => 'content', :action => 'show'})
+ #
+ # (the above is from the unit tests). In the above case, because the
+ # controller was explicitly given, but no action, the action is implied to
+ # be "index", not the recalled action of "show".
+ #
+ # great fun, eh?
+
+ options_as_params = options[:controller] ? { :action => "index" } : {}
+ options.each do |k, value|
+ options_as_params[k] = value.to_param
+ end
+ options_as_params
+ end
+
+ def build_expiry(options, recall)
+ recall.inject({}) do |expiry, (key, recalled_value)|
+ expiry[key] = (options.key?(key) && options[key] != recalled_value)
+ expiry
+ end
+ end
+
+ # Generate the path indicated by the arguments, and return an array of
+ # the keys that were not used to generate it.
+ def extra_keys(options, recall={})
+ generate_extras(options, recall).last
+ end
+
+ def generate_extras(options, recall={})
+ generate(options, recall, :generate_extras)
+ end
+
+ def generate(options, recall = {}, method=:generate)
+ named_route_name = options.delete(:use_route)
+ if named_route_name
+ named_route = named_routes[named_route_name]
+ options = named_route.parameter_shell.merge(options)
end
- def url_helper_name(name)
- "#{name}_url"
+ options = options_as_params(options)
+ expire_on = build_expiry(options, recall)
+
+ # if the controller has changed, make sure it changes relative to the
+ # current controller module, if any. In other words, if we're currently
+ # on admin/get, and the new controller is 'set', the new controller
+ # should really be admin/set.
+ if !named_route && expire_on[:controller] && options[:controller] && options[:controller][0] != ?/
+ old_parts = recall[:controller].split('/')
+ new_parts = options[:controller].split('/')
+ parts = old_parts[0..-(new_parts.length + 1)] + new_parts
+ options[:controller] = parts.join('/')
end
-
- def known_hash_for_route(route)
- hash = route.known.symbolize_keys
- route.defaults.each do |key, value|
- hash[key.to_sym] ||= value if value
+
+ # drop the leading '/' on the controller name
+ options[:controller] = options[:controller][1..-1] if options[:controller] && options[:controller][0] == ?/
+ merged = recall.merge(options)
+
+ if named_route
+ path = named_route.generate(options, merged, expire_on)
+ if path.nil?
+ raise_named_route_error(options, named_route, named_route_name)
+ else
+ return path
end
- hash[:controller] = "/#{hash[:controller]}"
-
- hash
- end
-
- def define_hash_access_method(route, name)
- hash = known_hash_for_route(route)
- define_method(hash_access_name(name)) do |*args|
- args.first ? hash.merge(args.first) : hash
+ else
+ merged[:action] ||= 'index'
+ options[:action] ||= 'index'
+
+ controller = merged[:controller]
+ action = merged[:action]
+
+ raise RoutingError, "Need controller and action!" unless controller && action
+ # don't use the recalled keys when determining which routes to check
+ routes = routes_by_controller[controller][action][options.keys.sort_by { |x| x.object_id }]
+
+ routes.each do |route|
+ results = route.send(method, options, merged, expire_on)
+ return results if results && (!results.is_a?(Array) || results.first)
end
end
-
- def name_route(route, name)
- define_hash_access_method(route, name)
-
- module_eval(%{def #{url_helper_name name}(options = {})
- url_for(#{hash_access_name(name)}.merge(options))
- end}, "generated/routing/named_routes/#{name}.rb")
-
- protected url_helper_name(name), hash_access_name(name)
-
- Helpers << url_helper_name(name).to_sym
- Helpers << hash_access_name(name).to_sym
- Helpers.uniq!
- end
- def install(cls = ActionController::Base)
- cls.send :include, self
- if cls.respond_to? :helper_method
- Helpers.each do |helper_name|
- cls.send :helper_method, helper_name
+ raise RoutingError, "No route matches #{options.inspect}"
+ end
+
+ # try to give a helpful error message when named route generation fails
+ def raise_named_route_error(options, named_route, named_route_name)
+ diff = named_route.requirements.diff(options)
+ unless diff.empty?
+ raise RoutingError, "#{named_route_name}_url failed to generate from #{options.inspect}, expected: #{named_route.requirements.inspect}, diff: #{named_route.requirements.diff(options).inspect}"
+ else
+ required_segments = named_route.segments.select {|seg| (!seg.optional?) && (!seg.is_a?(DividerSegment)) }
+ required_keys_or_values = required_segments.map { |seg| seg.key rescue seg.value } # we want either the key or the value from the segment
+ raise RoutingError, "#{named_route_name}_url failed to generate from #{options.inspect} - you may have ambiguous routes, or you may need to supply additional parameters for this route. content_url has the following required parameters: #{required_keys_or_values.inspect} - are they all satisifed?"
+ end
+ end
+
+ def recognize(request)
+ params = recognize_path(request.path, extract_request_environment(request))
+ request.path_parameters = params.with_indifferent_access
+ "#{params[:controller].camelize}Controller".constantize
+ end
+
+ def recognize_path(path, environment={})
+ path = CGI.unescape(path)
+ routes.each do |route|
+ result = route.recognize(path, environment) and return result
+ end
+ raise RoutingError, "no route found to match #{path.inspect} with #{environment.inspect}"
+ end
+
+ def routes_by_controller
+ @routes_by_controller ||= Hash.new do |controller_hash, controller|
+ controller_hash[controller] = Hash.new do |action_hash, action|
+ action_hash[action] = Hash.new do |key_hash, keys|
+ key_hash[keys] = routes_for_controller_and_action_and_keys(controller, action, keys)
end
end
end
end
+
+ def routes_for(options, merged, expire_on)
+ raise "Need controller and action!" unless controller && action
+ controller = merged[:controller]
+ merged = options if expire_on[:controller]
+ action = merged[:action] || 'index'
+
+ routes_by_controller[controller][action][merged.keys]
+ end
+
+ def routes_for_controller_and_action(controller, action)
+ selected = routes.select do |route|
+ route.matches_controller_and_action? controller, action
+ end
+ (selected.length == routes.length) ? routes : selected
+ end
+
+ def routes_for_controller_and_action_and_keys(controller, action, keys)
+ selected = routes.select do |route|
+ route.matches_controller_and_action? controller, action
+ end
+ selected.sort_by do |route|
+ (keys - route.significant_keys).length
+ end
+ end
+
+ # Subclasses and plugins may override this method to extract further attributes
+ # from the request, for use by route conditions and such.
+ def extract_request_environment(request)
+ { :method => request.method }
+ end
end
Routes = RouteSet.new
end
end
+
diff --git a/vendor/rails/actionpack/lib/action_controller/scaffolding.rb b/vendor/rails/actionpack/lib/action_controller/scaffolding.rb
index 2481107a..d02a31e6 100644
--- a/vendor/rails/actionpack/lib/action_controller/scaffolding.rb
+++ b/vendor/rails/actionpack/lib/action_controller/scaffolding.rb
@@ -1,7 +1,6 @@
module ActionController
module Scaffolding # :nodoc:
- def self.append_features(base)
- super
+ def self.included(base)
base.extend(ClassMethods)
end
@@ -25,25 +24,25 @@ module ActionController
# end
#
# def list
- # @entries = Entry.find_all
+ # @entries = Entry.find(:all)
# render_scaffold "list"
# end
- #
+ #
# def show
# @entry = Entry.find(params[:id])
# render_scaffold
# end
- #
+ #
# def destroy
# Entry.find(params[:id]).destroy
# redirect_to :action => "list"
# end
- #
+ #
# def new
# @entry = Entry.new
# render_scaffold
# end
- #
+ #
# def create
# @entry = Entry.new(params[:entry])
# if @entry.save
@@ -53,16 +52,16 @@ module ActionController
# render_scaffold('new')
# end
# end
- #
+ #
# def edit
# @entry = Entry.find(params[:id])
# render_scaffold
# end
- #
+ #
# def update
# @entry = Entry.find(params[:id])
# @entry.attributes = params[:entry]
- #
+ #
# if @entry.save
# flash[:notice] = "Entry was successfully updated"
# redirect_to :action => "show", :id => @entry
@@ -72,17 +71,17 @@ module ActionController
# end
# end
#
- # The render_scaffold method will first check to see if you've made your own template (like "weblog/show.rhtml" for
- # the show action) and if not, then render the generic template for that action. This gives you the possibility of using the
- # scaffold while you're building your specific application. Start out with a totally generic setup, then replace one template
+ # The render_scaffold method will first check to see if you've made your own template (like "weblog/show.rhtml" for
+ # the show action) and if not, then render the generic template for that action. This gives you the possibility of using the
+ # scaffold while you're building your specific application. Start out with a totally generic setup, then replace one template
# and one action at a time while relying on the rest of the scaffolded templates and actions.
module ClassMethods
# Adds a swath of generic CRUD actions to the controller. The +model_id+ is automatically converted into a class name unless
# one is specifically provide through options[:class_name]. So scaffold :post would use Post as the class
# and @post/@posts for the instance variables.
- #
+ #
# It's possible to use more than one scaffold in a single controller by specifying options[:suffix] = true. This will
- # make scaffold :post, :suffix => true use method names like list_post, show_post, and create_post
+ # make scaffold :post, :suffix => true use method names like list_post, show_post, and create_post
# instead of just list, show, and post. If suffix is used, then no index method is added.
def scaffold(model_id, options = {})
options.assert_valid_keys(:class_name, :suffix)
@@ -99,13 +98,13 @@ module ActionController
end
end_eval
end
-
+
module_eval <<-"end_eval", __FILE__, __LINE__
-
+
verify :method => :post, :only => [ :destroy#{suffix}, :create#{suffix}, :update#{suffix} ],
:redirect_to => { :action => :list#{suffix} }
-
-
+
+
def list#{suffix}
@#{singular_name}_pages, @#{plural_name} = paginate :#{plural_name}, :per_page => 10
render#{suffix}_scaffold "list#{suffix}"
@@ -115,17 +114,17 @@ module ActionController
@#{singular_name} = #{class_name}.find(params[:id])
render#{suffix}_scaffold
end
-
+
def destroy#{suffix}
#{class_name}.find(params[:id]).destroy
redirect_to :action => "list#{suffix}"
end
-
+
def new#{suffix}
@#{singular_name} = #{class_name}.new
render#{suffix}_scaffold
end
-
+
def create#{suffix}
@#{singular_name} = #{class_name}.new(params[:#{singular_name}])
if @#{singular_name}.save
@@ -135,12 +134,12 @@ module ActionController
render#{suffix}_scaffold('new')
end
end
-
+
def edit#{suffix}
@#{singular_name} = #{class_name}.find(params[:id])
render#{suffix}_scaffold
end
-
+
def update#{suffix}
@#{singular_name} = #{class_name}.find(params[:id])
@#{singular_name}.attributes = params[:#{singular_name}]
@@ -152,14 +151,14 @@ module ActionController
render#{suffix}_scaffold('edit')
end
end
-
+
private
def render#{suffix}_scaffold(action=nil)
action ||= caller_method_name(caller)
# logger.info ("testing template:" + "\#{self.class.controller_path}/\#{action}") if logger
-
+
if template_exists?("\#{self.class.controller_path}/\#{action}")
- render_action(action)
+ render :action => action
else
@scaffold_class = #{class_name}
@scaffold_singular_name, @scaffold_plural_name = "#{singular_name}", "#{plural_name}"
@@ -169,9 +168,9 @@ module ActionController
@template.instance_variable_set("@content_for_layout", @template.render_file(scaffold_path(action.sub(/#{suffix}$/, "")), false))
if !active_layout.nil?
- render_file(active_layout, nil, true)
+ render :file => active_layout, :use_full_path => true
else
- render_file(scaffold_path("layout"))
+ render :file => scaffold_path('layout')
end
end
end
@@ -179,12 +178,12 @@ module ActionController
def scaffold_path(template_name)
File.dirname(__FILE__) + "/templates/scaffolds/" + template_name + ".rhtml"
end
-
+
def caller_method_name(caller)
caller.first.scan(/`(.*)'/).first.first # ' ruby-mode
end
end_eval
- end
+ end
end
end
end
diff --git a/vendor/rails/actionpack/lib/action_controller/session/active_record_store.rb b/vendor/rails/actionpack/lib/action_controller/session/active_record_store.rb
index 5f3b960b..cbd5422a 100644
--- a/vendor/rails/actionpack/lib/action_controller/session/active_record_store.rb
+++ b/vendor/rails/actionpack/lib/action_controller/session/active_record_store.rb
@@ -5,6 +5,8 @@ require 'base64'
class CGI
class Session
+ attr_reader :data
+
# Return this session's underlying Session instance. Useful for the DB-backed session stores.
def model
@dbman.model if @dbman
diff --git a/vendor/rails/actionpack/lib/action_controller/session/drb_store.rb b/vendor/rails/actionpack/lib/action_controller/session/drb_store.rb
index 8ea23e8f..4feb2636 100644
--- a/vendor/rails/actionpack/lib/action_controller/session/drb_store.rb
+++ b/vendor/rails/actionpack/lib/action_controller/session/drb_store.rb
@@ -26,6 +26,10 @@ class CGI #:nodoc:all
def delete
@@session_data.delete(@session_id)
end
+
+ def data
+ @@session_data[@session_id]
+ end
end
end
end
diff --git a/vendor/rails/actionpack/lib/action_controller/session/mem_cache_store.rb b/vendor/rails/actionpack/lib/action_controller/session/mem_cache_store.rb
index a7076fcd..e62c0ef9 100644
--- a/vendor/rails/actionpack/lib/action_controller/session/mem_cache_store.rb
+++ b/vendor/rails/actionpack/lib/action_controller/session/mem_cache_store.rb
@@ -93,6 +93,10 @@ begin
end
@session_data = {}
end
+
+ def data
+ @session_data
+ end
end
end
end
diff --git a/vendor/rails/actionpack/lib/action_controller/session_management.rb b/vendor/rails/actionpack/lib/action_controller/session_management.rb
index 408ef279..60b0cd5f 100644
--- a/vendor/rails/actionpack/lib/action_controller/session_management.rb
+++ b/vendor/rails/actionpack/lib/action_controller/session_management.rb
@@ -8,12 +8,9 @@ module ActionController #:nodoc:
module SessionManagement #:nodoc:
def self.included(base)
base.extend(ClassMethods)
-
- base.send :alias_method, :process_without_session_management_support, :process
- base.send :alias_method, :process, :process_with_session_management_support
-
- base.send :alias_method, :process_cleanup_without_session_management_support, :process_cleanup
- base.send :alias_method, :process_cleanup, :process_cleanup_with_session_management_support
+
+ base.send :alias_method_chain, :process, :session_management_support
+ base.send :alias_method_chain, :process_cleanup, :session_management_support
end
module ClassMethods
@@ -123,16 +120,16 @@ module ActionController #:nodoc:
end
def process_cleanup_with_session_management_support
- process_cleanup_without_session_management_support
clear_persistent_model_associations
+ process_cleanup_without_session_management_support
end
# Clear cached associations in session data so they don't overflow
# the database field. Only applies to ActiveRecordStore since there
# is not a standard way to iterate over session data.
def clear_persistent_model_associations #:doc:
- if defined?(@session) && @session.instance_variables.include?('@data')
- session_data = @session.instance_variable_get('@data')
+ if defined?(@_session) && @_session.respond_to?(:data)
+ session_data = @_session.data
if session_data && session_data.respond_to?(:each_value)
session_data.each_value do |obj|
diff --git a/vendor/rails/actionpack/lib/action_controller/streaming.rb b/vendor/rails/actionpack/lib/action_controller/streaming.rb
index 618888d0..484913c7 100644
--- a/vendor/rails/actionpack/lib/action_controller/streaming.rb
+++ b/vendor/rails/actionpack/lib/action_controller/streaming.rb
@@ -69,17 +69,8 @@ module ActionController #:nodoc:
logger.info "Streaming file #{path}" unless logger.nil?
len = options[:buffer_size] || 4096
File.open(path, 'rb') do |file|
- if output.respond_to?(:syswrite)
- begin
- while true
- output.syswrite(file.sysread(len))
- end
- rescue EOFError
- end
- else
- while buf = file.read(len)
- output.write(buf)
- end
+ while buf = file.read(len)
+ output.write(buf)
end
end
}
@@ -97,8 +88,8 @@ module ActionController #:nodoc:
# * :type - specifies an HTTP content type.
# Defaults to 'application/octet-stream'.
# * :disposition - specifies whether the file will be shown inline or downloaded.
- # * :status - specifies the status code to send with the response. Defaults to '200 OK'.
# Valid values are 'inline' and 'attachment' (default).
+ # * :status - specifies the status code to send with the response. Defaults to '200 OK'.
#
# Generic data download:
# send_data buffer
@@ -125,10 +116,10 @@ module ActionController #:nodoc:
end
disposition = options[:disposition].dup || 'attachment'
-
+
disposition <<= %(; filename="#{options[:filename]}") if options[:filename]
- @headers.update(
+ headers.update(
'Content-Length' => options[:length],
'Content-Type' => options[:type].strip, # fixes a problem with extra '\r' with some browsers
'Content-Disposition' => disposition,
@@ -141,7 +132,7 @@ module ActionController #:nodoc:
# after it displays the "open/save" dialog, which means that if you
# hit "open" the file isn't there anymore when the application that
# is called for handling the download is run, so let's workaround that
- @headers['Cache-Control'] = 'private' if @headers['Cache-Control'] == 'no-cache'
+ headers['Cache-Control'] = 'private' if headers['Cache-Control'] == 'no-cache'
end
end
end
diff --git a/vendor/rails/actionpack/lib/action_controller/templates/rescues/_request_and_response.rhtml b/vendor/rails/actionpack/lib/action_controller/templates/rescues/_request_and_response.rhtml
index 81995320..f2f5732e 100644
--- a/vendor/rails/actionpack/lib/action_controller/templates/rescues/_request_and_response.rhtml
+++ b/vendor/rails/actionpack/lib/action_controller/templates/rescues/_request_and_response.rhtml
@@ -8,10 +8,10 @@
<% if false %>
<% begin %>
- <%= form_tag(@request.request_uri, "method" => @request.method) %>
+ <%= form_tag(request.request_uri, "method" => request.method) %>
- <% for key, values in @params %>
+ <% for key, values in params %>
<% next if key == "BP-RETRY" %>
<% for value in Array(values) %>
@@ -26,7 +26,7 @@
<% end %>
<%
- request_parameters_without_action = @request.parameters.clone
+ request_parameters_without_action = request.parameters.clone
request_parameters_without_action.delete("action")
request_parameters_without_action.delete("controller")
@@ -37,8 +37,8 @@
<%=h @exception.class.to_s %>
- <% if @request.parameters['controller'] %>
- in <%=h @request.parameters['controller'].humanize %>Controller<% if @request.parameters['action'] %>#<%=h @request.parameters['action'] %><% end %>
+ <% if request.parameters['controller'] %>
+ in <%=h request.parameters['controller'].humanize %>Controller<% if request.parameters['action'] %>#<%=h request.parameters['action'] %><% end %>
<% end %>
<% end %>
diff --git a/vendor/rails/actionpack/lib/action_controller/test_process.rb b/vendor/rails/actionpack/lib/action_controller/test_process.rb
index 0afe3f82..27daf17c 100644
--- a/vendor/rails/actionpack/lib/action_controller/test_process.rb
+++ b/vendor/rails/actionpack/lib/action_controller/test_process.rb
@@ -1,5 +1,4 @@
require File.dirname(__FILE__) + '/assertions'
-require File.dirname(__FILE__) + '/deprecated_assertions'
module ActionController #:nodoc:
class Base
@@ -18,8 +17,7 @@ module ActionController #:nodoc:
end
end
- alias_method :process_without_test, :process
- alias_method :process, :process_with_test
+ alias_method_chain :process, :test
end
class TestRequest < AbstractRequest #:nodoc:
@@ -39,8 +37,8 @@ module ActionController #:nodoc:
end
def reset_session
- @session = {}
- end
+ @session = TestSession.new
+ end
def raw_post
if raw_post = env['RAW_POST_DATA']
@@ -79,6 +77,10 @@ module ActionController #:nodoc:
@path = uri.split("?").first
end
+ def accept=(mime_types)
+ @env["HTTP_ACCEPT"] = Array(mime_types).collect { |mime_types| mime_types.to_s }.join(",")
+ end
+
def remote_addr=(addr)
@env['REMOTE_ADDR'] = addr
end
@@ -103,7 +105,7 @@ module ActionController #:nodoc:
if value.is_a? Fixnum
value = value.to_s
elsif value.is_a? Array
- value = ActionController::Routing::PathComponent::Result.new(value)
+ value = ActionController::Routing::PathSegment::Result.new(value)
end
if extra_keys.include?(key.to_sym)
@@ -112,6 +114,7 @@ module ActionController #:nodoc:
path_parameters[key.to_s] = value
end
end
+ @parameters = nil # reset TestRequest#parameters to use the new path_parameters
end
def recycle!
@@ -176,7 +179,7 @@ module ActionController #:nodoc:
# returns the redirection location or nil
def redirect_url
- redirect? ? headers['location'] : nil
+ headers['Location']
end
# does the redirect location match this regexp pattern?
@@ -272,27 +275,40 @@ module ActionController #:nodoc:
end
class TestSession #:nodoc:
- def initialize(attributes = {})
+ attr_accessor :session_id
+
+ def initialize(attributes = nil)
+ @session_id = ''
@attributes = attributes
+ @saved_attributes = nil
+ end
+
+ def data
+ @attributes ||= @saved_attributes || {}
end
def [](key)
- @attributes[key]
+ data[key.to_s]
end
def []=(key, value)
- @attributes[key] = value
+ data[key.to_s] = value
end
- def session_id
- ""
+ def update
+ @saved_attributes = @attributes
end
- def update() end
- def close() end
- def delete() @attributes = {} end
+ def delete
+ @attributes = nil
+ end
+
+ def close
+ update
+ delete
+ end
end
-
+
# Essentially generates a modified Tempfile object similar to the object
# you'd get from the standard library CGI module in a multipart
# request. This means you can use an ActionController::TestUploadedFile
@@ -301,6 +317,7 @@ module ActionController #:nodoc:
#
# Usage example, within a functional test:
# post :change_avatar, :avatar => ActionController::TestUploadedFile.new(Test::Unit::TestCase.fixture_path + '/files/spongebob.png', 'image/png')
+ require 'tempfile'
class TestUploadedFile
# The filename, *not* including the path, of the "uploaded" file
attr_reader :original_filename
@@ -309,7 +326,7 @@ module ActionController #:nodoc:
attr_reader :content_type
def initialize(path, content_type = 'text/plain')
- raise "file does not exist" unless File.exist?(path)
+ raise "#{path} file does not exist" unless File.exist?(path)
@content_type = content_type
@original_filename = path.sub(/^.*#{File::SEPARATOR}([^#{File::SEPARATOR}]+)$/) { $1 }
@tempfile = Tempfile.new(@original_filename)
@@ -333,7 +350,7 @@ module ActionController #:nodoc:
%w( get post put delete head ).each do |method|
base.class_eval <<-EOV, __FILE__, __LINE__
def #{method}(action, parameters = nil, session = nil, flash = nil)
- @request.env['REQUEST_METHOD'] = "#{method.upcase}" if @request
+ @request.env['REQUEST_METHOD'] = "#{method.upcase}" if defined?(@request)
process(action, parameters, session, flash)
end
EOV
@@ -344,8 +361,10 @@ module ActionController #:nodoc:
def process(action, parameters = nil, session = nil, flash = nil)
# Sanity check for required instance variables so we can give an
# understandable error message.
- %w(controller request response).each do |iv_name|
- raise "@#{iv_name} is nil: make sure you set it in your test's setup method." if instance_variable_get("@#{iv_name}").nil?
+ %w(@controller @request @response).each do |iv_name|
+ if !instance_variables.include?(iv_name) || instance_variable_get(iv_name).nil?
+ raise "#{iv_name} is nil: make sure you set it in your test's setup method."
+ end
end
@request.recycle!
@@ -374,8 +393,9 @@ module ActionController #:nodoc:
alias xhr :xml_http_request
def follow_redirect
- if @response.redirected_to[:controller]
- raise "Can't follow redirects outside of current controller (#{@response.redirected_to[:controller]})"
+ redirected_controller = @response.redirected_to[:controller]
+ if redirected_controller && redirected_controller != @controller.controller_name
+ raise "Can't follow redirects outside of current controller (from #{@controller.controller_name} to #{redirected_controller})"
end
get(@response.redirected_to.delete(:action), @response.redirected_to.stringify_keys)
@@ -428,7 +448,7 @@ module ActionController #:nodoc:
end
def method_missing(selector, *args)
- return @controller.send(selector, *args) if ActionController::Routing::NamedRoutes::Helpers.include?(selector)
+ return @controller.send(selector, *args) if ActionController::Routing::Routes.named_routes.helpers.include?(selector)
return super
end
@@ -448,13 +468,15 @@ module ActionController #:nodoc:
# The new instance is yielded to the passed block. Typically the block
# will create some routes using map.draw { map.connect ... }:
#
- # with_routing do |set|
- # set.draw { set.connect ':controller/:id/:action' }
- # assert_equal(
- # ['/content/10/show', {}],
- # set.generate(:controller => 'content', :id => 10, :action => 'show')
- # )
- # end
+ # with_routing do |set|
+ # set.draw do |map|
+ # map.connect ':controller/:action/:id'
+ # assert_equal(
+ # ['/content/10/show', {}],
+ # map.generate(:controller => 'content', :id => 10, :action => 'show')
+ # end
+ # end
+ # end
#
def with_routing
real_routes = ActionController::Routing::Routes
diff --git a/vendor/rails/actionpack/lib/action_controller/url_rewriter.rb b/vendor/rails/actionpack/lib/action_controller/url_rewriter.rb
index bc82fda5..0a5aab14 100644
--- a/vendor/rails/actionpack/lib/action_controller/url_rewriter.rb
+++ b/vendor/rails/actionpack/lib/action_controller/url_rewriter.rb
@@ -1,13 +1,71 @@
module ActionController
+
+ # Write URLs from arbitrary places in your codebase, such as your mailers.
+ #
+ # Example:
+ #
+ # class MyMailer
+ # include ActionController::UrlWriter
+ # default_url_options[:host] = 'www.basecamphq.com'
+ #
+ # def signup_url(token)
+ # url_for(:controller => 'signup', action => 'index', :token => token)
+ # end
+ # end
+ #
+ # In addition to providing +url_for+, named routes are also accessible after
+ # including UrlWriter.
+ #
+ module UrlWriter
+
+ # The default options for urls written by this writer. Typically a :host pair
+ # is provided.
+ mattr_accessor :default_url_options
+ self.default_url_options = {}
+
+ def self.included(base) #:nodoc:
+ ActionController::Routing::Routes.named_routes.install base
+ base.mattr_accessor :default_url_options
+ base.default_url_options ||= default_url_options
+ end
+
+ # Generate a url with the provided options. The following special options may
+ # effect the constructed url:
+ #
+ # * :host Specifies the host the link should be targetted at. This option
+ # must be provided either explicitly, or via default_url_options.
+ # * :protocol The protocol to connect to. Defaults to 'http'
+ # * :port Optionally specify the port to connect to.
+ #
+ def url_for(options)
+ options = self.class.default_url_options.merge(options)
+
+ url = ''
+ unless options.delete :only_path
+ url << (options.delete(:protocol) || 'http')
+ url << '://'
+
+ raise "Missing host to link to! Please provide :host parameter or set default_url_options[:host]" unless options[:host]
+ url << options.delete(:host)
+ url << ":#{options.delete(:port)}" if options.key?(:port)
+ else
+ # Delete the unused options to prevent their appearance in the query string
+ [:protocol, :host, :port].each { |k| options.delete k }
+ end
+ url << Routing::Routes.generate(options, {})
+ return url
+ end
+
+ end
+
# Rewrites URLs for Base.redirect_to and Base.url_for in the controller.
-
class UrlRewriter #:nodoc:
RESERVED_OPTIONS = [:anchor, :params, :only_path, :host, :protocol, :trailing_slash, :skip_relative_url_root]
def initialize(request, parameters)
@request, @parameters = request, parameters
end
- def rewrite(options = {})
+ def rewrite(options = {})
rewrite_url(rewrite_path(options), options)
end
@@ -41,34 +99,10 @@ module ActionController
options.update(overwrite)
end
RESERVED_OPTIONS.each {|k| options.delete k}
- path, extra_keys = Routing::Routes.generate(options.dup, @request) # Warning: Routes will mutate and violate the options hash
- path << build_query_string(options, extra_keys) unless extra_keys.empty?
-
- path
- end
-
- # Returns a query string with escaped keys and values from the passed hash. If the passed hash contains an "id" it'll
- # be added as a path element instead of a regular parameter pair.
- def build_query_string(hash, only_keys = nil)
- elements = []
- query_string = ""
-
- only_keys ||= hash.keys
-
- only_keys.each do |key|
- value = hash[key]
- key = CGI.escape key.to_s
- if value.class == Array
- key << '[]'
- else
- value = [ value ]
- end
- value.each { |val| elements << "#{key}=#{Routing.extract_parameter_value(val)}" }
- end
-
- query_string << ("?" + elements.join("&")) unless elements.empty?
- query_string
+ # Generates the query string, too
+ Routing::Routes.generate(options, @request.symbolized_path_parameters)
end
end
+
end
diff --git a/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb b/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb
index 25230f2e..19b349e8 100644
--- a/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb
+++ b/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb
@@ -1,5 +1,6 @@
require File.dirname(__FILE__) + '/tokenizer'
require File.dirname(__FILE__) + '/node'
+require File.dirname(__FILE__) + '/selector'
module HTML #:nodoc:
diff --git a/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb b/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb
index 086f7171..472c5b2b 100644
--- a/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb
+++ b/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb
@@ -92,7 +92,6 @@ module HTML #:nodoc:
# returns non +nil+. Returns the result of the #find call that succeeded.
def find(conditions)
conditions = validate_conditions(conditions)
-
@children.each do |child|
node = child.find(conditions)
return node if node
@@ -152,11 +151,11 @@ module HTML #:nodoc:
if scanner.skip(/!\[CDATA\[/)
scanner.scan_until(/\]\]>/)
- return CDATA.new(parent, line, pos, scanner.pre_match)
+ return CDATA.new(parent, line, pos, scanner.pre_match.gsub(/"
@@ -410,7 +409,6 @@ module HTML #:nodoc:
# :child => /hello world/ }
def match(conditions)
conditions = validate_conditions(conditions)
-
# check content of child nodes
if conditions[:content]
if children.empty?
@@ -455,7 +453,6 @@ module HTML #:nodoc:
# count children
if opts = conditions[:children]
matches = children.select do |c|
- c.match(/./) or
(c.kind_of?(HTML::Tag) and (c.closing == :self or ! c.childless?))
end
diff --git a/vendor/rails/actionpack/lib/action_controller/verification.rb b/vendor/rails/actionpack/lib/action_controller/verification.rb
index d78f5f06..7cdf6584 100644
--- a/vendor/rails/actionpack/lib/action_controller/verification.rb
+++ b/vendor/rails/actionpack/lib/action_controller/verification.rb
@@ -1,7 +1,6 @@
module ActionController #:nodoc:
module Verification #:nodoc:
- def self.append_features(base) #:nodoc:
- super
+ def self.included(base) #:nodoc:
base.extend(ClassMethods)
end
@@ -18,19 +17,26 @@ module ActionController #:nodoc:
# Usage:
#
# class GlobalController < ActionController::Base
- # # prevent the #update_settings action from being invoked unless
- # # the 'admin_privileges' request parameter exists.
+ # # Prevent the #update_settings action from being invoked unless
+ # # the 'admin_privileges' request parameter exists. The
+ # # settings action will be redirected to in current controller
+ # # if verification fails.
# verify :params => "admin_privileges", :only => :update_post,
# :redirect_to => { :action => "settings" }
#
- # # disallow a post from being updated if there was no information
+ # # Disallow a post from being updated if there was no information
# # submitted with the post, and if there is no active post in the
- # # session, and if there is no "note" key in the flash.
+ # # session, and if there is no "note" key in the flash. The route
+ # # named category_url will be redirected to if verification fails.
+ #
# verify :params => "post", :session => "post", "flash" => "note",
# :only => :update_post,
# :add_flash => { "alert" => "Failed to create your message" },
# :redirect_to => :category_url
#
+ # Note that these prerequisites are not business rules. They do not examine
+ # the content of the session or the parameters. That level of validation should
+ # be encapsulated by your domain model or helper methods in the controller.
module ClassMethods
# Verify the given actions so that if certain prerequisites are not met,
# the user is redirected to a different action. The +options+ parameter
@@ -40,7 +46,7 @@ module ActionController #:nodoc:
# be in the params hash in order for the action(s) to be safely
# called.
# * :session: a single key or an array of keys that must
- # be in the @session in order for the action(s) to be safely called.
+ # be in the session in order for the action(s) to be safely called.
# * :flash: a single key or an array of keys that must
# be in the flash in order for the action(s) to be safely called.
# * :method: a single key or an array of keys--any one of which
@@ -51,8 +57,12 @@ module ActionController #:nodoc:
# from an Ajax call or not.
# * :add_flash: a hash of name/value pairs that should be merged
# into the session's flash if the prerequisites cannot be satisfied.
+ # * :add_headers: a hash of name/value pairs that should be
+ # merged into the response's headers hash if the prerequisites cannot
+ # be satisfied.
# * :redirect_to: the redirection parameters to be used when
- # redirecting if the prerequisites cannot be satisfied.
+ # redirecting if the prerequisites cannot be satisfied. You can
+ # redirect either to named route or to the action in some controller.
# * :render: the render parameters to be used when
# the prerequisites cannot be satisfied.
# * :only: only apply this verification to the actions specified
@@ -69,19 +79,20 @@ module ActionController #:nodoc:
def verify_action(options) #:nodoc:
prereqs_invalid =
- [*options[:params] ].find { |v| @params[v].nil? } ||
- [*options[:session]].find { |v| @session[v].nil? } ||
+ [*options[:params] ].find { |v| params[v].nil? } ||
+ [*options[:session]].find { |v| session[v].nil? } ||
[*options[:flash] ].find { |v| flash[v].nil? }
if !prereqs_invalid && options[:method]
prereqs_invalid ||=
- [*options[:method]].all? { |v| @request.method != v.to_sym }
+ [*options[:method]].all? { |v| request.method != v.to_sym }
end
prereqs_invalid ||= (request.xhr? != options[:xhr]) unless options[:xhr].nil?
if prereqs_invalid
flash.update(options[:add_flash]) if options[:add_flash]
+ response.headers.update(options[:add_headers]) if options[:add_headers]
unless performed?
render(options[:render]) if options[:render]
redirect_to(options[:redirect_to]) if options[:redirect_to]
diff --git a/vendor/rails/actionpack/lib/action_pack.rb b/vendor/rails/actionpack/lib/action_pack.rb
index f8a5b5dd..01f8ea89 100644
--- a/vendor/rails/actionpack/lib/action_pack.rb
+++ b/vendor/rails/actionpack/lib/action_pack.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004 David Heinemeier Hansson
+# Copyright (c) 2004-2006 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
diff --git a/vendor/rails/actionpack/lib/action_pack/version.rb b/vendor/rails/actionpack/lib/action_pack/version.rb
index 91e916df..176fda01 100644
--- a/vendor/rails/actionpack/lib/action_pack/version.rb
+++ b/vendor/rails/actionpack/lib/action_pack/version.rb
@@ -1,8 +1,8 @@
module ActionPack #:nodoc:
module VERSION #:nodoc:
MAJOR = 1
- MINOR = 12
- TINY = 5
+ MINOR = 13
+ TINY = 2
STRING = [MAJOR, MINOR, TINY].join('.')
end
diff --git a/vendor/rails/actionpack/lib/action_view.rb b/vendor/rails/actionpack/lib/action_view.rb
index a7648f0e..72ef810b 100644
--- a/vendor/rails/actionpack/lib/action_view.rb
+++ b/vendor/rails/actionpack/lib/action_view.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004 David Heinemeier Hansson
+# Copyright (c) 2004-2006 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
diff --git a/vendor/rails/actionpack/lib/action_view/base.rb b/vendor/rails/actionpack/lib/action_view/base.rb
index 1f156340..e0bd5915 100644
--- a/vendor/rails/actionpack/lib/action_view/base.rb
+++ b/vendor/rails/actionpack/lib/action_view/base.rb
@@ -1,7 +1,6 @@
require 'erb'
module ActionView #:nodoc:
-
class ActionViewError < StandardError #:nodoc:
end
@@ -54,13 +53,22 @@ module ActionView #:nodoc:
#
# You can pass local variables to sub templates by using a hash with the variable names as keys and the objects as values:
#
- # <%= render "shared/header", { "headline" => "Welcome", "person" => person } %>
+ # <%= render "shared/header", { :headline => "Welcome", :person => person } %>
#
# These can now be accessed in shared/header with:
#
# Headline: <%= headline %>
# First name: <%= person.first_name %>
#
+ # If you need to find out whether a certain local variable has been assigned a value in a particular render call,
+ # you need to use the following pattern:
+ #
+ # <% if local_assigns.has_key? :headline %>
+ # Headline: <%= headline %>
+ # <% end %>
+ #
+ # Testing using defined? headline will not work. This is an implementation restriction.
+ #
# == Template caching
#
# By default, Rails will compile each template to a method in order to render it. When you alter a template, Rails will
@@ -148,7 +156,8 @@ module ActionView #:nodoc:
attr_accessor :base_path, :assigns, :template_extension
attr_accessor :controller
- attr_reader :logger, :params, :request, :response, :session, :headers, :flash
+ attr_reader :logger, :response, :headers
+ attr_internal *ActionController::Base::DEPRECATED_INSTANCE_VARIABLES
# Specify trim mode for the ERB compiler. Defaults to '-'.
# See ERB documentation for suitable values.
@@ -199,7 +208,7 @@ module ActionView #:nodoc:
end
def self.load_helpers(helper_dir)#:nodoc:
- Dir.foreach(helper_dir) do |helper_file|
+ Dir.entries(helper_dir).sort.each do |helper_file|
next unless helper_file =~ /^([a-z][a-z_]*_helper).rb$/
require File.join(helper_dir, $1)
helper_module_name = $1.camelize
@@ -301,6 +310,9 @@ module ActionView #:nodoc:
# will only be read if it has to be compiled.
#
def compile_and_render_template(extension, template = nil, file_path = nil, local_assigns = {}) #:nodoc:
+ # convert string keys to symbols if requested
+ local_assigns = local_assigns.symbolize_keys if @@local_assigns_support_string_keys
+
# compile the given template, if necessary
if compile_template?(template, file_path, local_assigns)
template ||= read_template_file(file_path, extension)
@@ -309,9 +321,7 @@ module ActionView #:nodoc:
# Get the method name for this template and run it
method_name = @@method_names[file_path || template]
- evaluate_assigns
-
- local_assigns = local_assigns.symbolize_keys if @@local_assigns_support_string_keys
+ evaluate_assigns
send(method_name, local_assigns) do |*name|
instance_variable_get "@content_for_#{name.first || 'layout'}"
@@ -337,14 +347,14 @@ module ActionView #:nodoc:
def builder_template_exists?(template_path)#:nodoc:
template_exists?(template_path, :rxml)
end
-
+
def javascript_template_exists?(template_path)#:nodoc:
template_exists?(template_path, :rjs)
end
def file_exists?(template_path)#:nodoc:
template_file_name, template_file_extension = path_and_extension(template_path)
-
+
if template_file_extension
template_exists?(template_file_name, template_file_extension)
else
@@ -374,11 +384,11 @@ module ActionView #:nodoc:
template_path_without_extension = template_path.sub(/\.(\w+)$/, '')
[ template_path_without_extension, $1 ]
end
-
+
def cached_template_extension(template_path)
@@cache_template_extensions && @@cached_template_extension[template_path]
- end
-
+ end
+
def find_template_extension_for(template_path)
if match = delegate_template_exists?(template_path)
match.first.to_sym
@@ -386,7 +396,7 @@ module ActionView #:nodoc:
elsif builder_template_exists?(template_path): :rxml
elsif javascript_template_exists?(template_path): :rjs
else
- raise ActionViewError, "No rhtml, rxml, rjs or delegate template found for #{template_path}"
+ raise ActionViewError, "No rhtml, rxml, rjs or delegate template found for #{template_path} in #{@base_path}"
end
end
@@ -416,7 +426,7 @@ module ActionView #:nodoc:
local_assigns.empty? ||
((args = @@template_args[render_symbol]) && local_assigns.all? { |k,_| args.has_key?(k) })
end
-
+
# Check whether compilation is necessary.
# Compile if the inline template or file has not been compiled yet.
# Or if local_assigns has a new key, which isn't supported by the compiled code yet.
@@ -427,8 +437,8 @@ module ActionView #:nodoc:
if @@compile_time[render_symbol] && supports_local_assigns?(render_symbol, local_assigns)
if file_name && !@@cache_template_loading
- @@compile_time[render_symbol] < File.mtime(file_name) || (File.symlink?(file_name) ?
- @@compile_time[render_symbol] < File.lstat(file_name).mtime : false)
+ @@compile_time[render_symbol] < File.mtime(file_name) ||
+ (File.symlink?(file_name) && (@@compile_time[render_symbol] < File.lstat(file_name).mtime))
end
else
true
@@ -440,11 +450,11 @@ module ActionView #:nodoc:
if template_requires_setup?(extension)
body = case extension.to_sym
when :rxml
+ "controller.response.content_type ||= 'application/xml'\n" +
"xml = Builder::XmlMarkup.new(:indent => 2)\n" +
- "@controller.headers['Content-Type'] ||= 'application/xml'\n" +
template
when :rjs
- "@controller.headers['Content-Type'] ||= 'text/javascript'\n" +
+ "controller.response.content_type ||= 'text/javascript'\n" +
"update_page do |page|\n#{template}\nend"
end
else
@@ -457,7 +467,7 @@ module ActionView #:nodoc:
locals_code = ""
locals_keys.each do |key|
- locals_code << "#{key} = local_assigns[:#{key}] if local_assigns.has_key?(:#{key})\n"
+ locals_code << "#{key} = local_assigns[:#{key}]\n"
end
"def #{render_symbol}(local_assigns)\n#{locals_code}#{body}\nend"
@@ -472,34 +482,27 @@ module ActionView #:nodoc:
end
def assign_method_name(extension, template, file_name)
- method_name = '_run_'
- method_name << "#{extension}_" if extension
+ method_key = file_name || template
+ @@method_names[method_key] ||= compiled_method_name(extension, template, file_name)
+ end
+ def compiled_method_name(extension, template, file_name)
+ ['_run', extension, compiled_method_name_file_path_segment(file_name)].compact.join('_').to_sym
+ end
+
+ def compiled_method_name_file_path_segment(file_name)
if file_name
- file_path = File.expand_path(file_name)
- base_path = File.expand_path(@base_path)
-
- i = file_path.index(base_path)
- l = base_path.length
-
- method_name_file_part = i ? file_path[i+l+1,file_path.length-l-1] : file_path.clone
- method_name_file_part.sub!(/\.r(html|xml|js)$/,'')
- method_name_file_part.tr!('/:-', '_')
- method_name_file_part.gsub!(/[^a-zA-Z0-9_]/){|s| s[0].to_s}
-
- method_name += method_name_file_part
+ s = File.expand_path(file_name)
+ s.sub!(/^#{Regexp.escape(File.expand_path(RAILS_ROOT))}/, '') if defined?(RAILS_ROOT)
+ s.gsub!(/([^a-zA-Z0-9_])/) { $1[0].to_s }
+ s
else
- @@inline_template_count += 1
- method_name << @@inline_template_count.to_s
+ (@@inline_template_count += 1).to_s
end
-
- @@method_names[file_name || template] = method_name.intern
end
def compile_template(extension, template, file_name, local_assigns)
- method_key = file_name || template
-
- render_symbol = @@method_names[method_key] || assign_method_name(extension, template, file_name)
+ render_symbol = assign_method_name(extension, template, file_name)
render_source = create_template_source(extension, template, render_symbol, local_assigns.keys)
line_offset = @@template_args[render_symbol].size
@@ -516,18 +519,18 @@ module ActionView #:nodoc:
else
CompiledTemplates.module_eval(render_source, 'compiled-template', -line_offset)
end
- rescue Object => e
+ rescue Exception => e # errors from template code
if logger
logger.debug "ERROR: compiling #{render_symbol} RAISED #{e}"
logger.debug "Function body: #{render_source}"
logger.debug "Backtrace: #{e.backtrace.join("\n")}"
end
- raise TemplateError.new(@base_path, method_key, @assigns, template, e)
+ raise TemplateError.new(@base_path, file_name || template, @assigns, template, e)
end
@@compile_time[render_symbol] = Time.now
- # logger.debug "Compiled template #{method_key}\n ==> #{render_symbol}" if logger
+ # logger.debug "Compiled template #{file_name || template}\n ==> #{render_symbol}" if logger
end
end
end
diff --git a/vendor/rails/actionpack/lib/action_view/compiled_templates.rb b/vendor/rails/actionpack/lib/action_view/compiled_templates.rb
index a00a7578..deb730f4 100644
--- a/vendor/rails/actionpack/lib/action_view/compiled_templates.rb
+++ b/vendor/rails/actionpack/lib/action_view/compiled_templates.rb
@@ -55,7 +55,7 @@ module ActionView
begin
module_eval(method_def, fake_file_name, initial_line_number)
@mtimes[full_key(identifier, arg_names)] = Time.now
- rescue Object => e
+ rescue Exception => e # errors from compiled source
e.blame_file! identifier
raise
end
diff --git a/vendor/rails/actionpack/lib/action_view/helpers/active_record_helper.rb b/vendor/rails/actionpack/lib/action_view/helpers/active_record_helper.rb
index 828aebf7..33eaa138 100644
--- a/vendor/rails/actionpack/lib/action_view/helpers/active_record_helper.rb
+++ b/vendor/rails/actionpack/lib/action_view/helpers/active_record_helper.rb
@@ -85,36 +85,62 @@ module ActionView
# <%= error_message_on "post", "title", "Title simply ", " (or it won't work)", "inputError" %> =>
#
Title simply can't be empty (or it won't work)
def error_message_on(object, method, prepend_text = "", append_text = "", css_class = "formError")
- if errors = instance_variable_get("@#{object}").errors.on(method)
+ if (obj = instance_variable_get("@#{object}")) && (errors = obj.errors.on(method))
content_tag("div", "#{prepend_text}#{errors.is_a?(Array) ? errors.first : errors}#{append_text}", :class => css_class)
+ else
+ ''
end
end
- # Returns a string with a div containing all the error messages for the object located as an instance variable by the name
- # of object_name. This div can be tailored by the following options:
+ # Returns a string with a div containing all of the error messages for the objects located as instance variables by the names
+ # given. If more than one object is specified, the errors for the objects are displayed in the order that the object names are
+ # provided.
+ #
+ # This div can be tailored by the following options:
#
# * header_tag - Used for the header of the error div (default: h2)
# * id - The id of the error div (default: errorExplanation)
# * class - The class of the error div (default: errorExplanation)
+ # * object_name - The object name to use in the header, or
+ # any text that you prefer. If object_name is not set, the name of
+ # the first object will be used.
+ #
+ # Specifying one object:
+ #
+ # error_messages_for 'user'
+ #
+ # Specifying more than one object (and using the name 'user' in the
+ # header as the object_name instead of 'user_common'):
+ #
+ # error_messages_for 'user_common', 'user', :object_name => 'user'
#
# NOTE: This is a pre-packaged presentation of the errors with embedded strings and a certain HTML structure. If what
# you need is significantly different from the default presentation, it makes plenty of sense to access the object.errors
# instance yourself and set it up. View the source of this method to see how easy it is.
- def error_messages_for(object_name, options = {})
- options = options.symbolize_keys
- object = instance_variable_get("@#{object_name}")
- if object && !object.errors.empty?
- content_tag("div",
- content_tag(
- options[:header_tag] || "h2",
- "#{pluralize(object.errors.count, "error")} prohibited this #{object_name.to_s.gsub("_", " ")} from being saved"
- ) +
- content_tag("p", "There were problems with the following fields:") +
- content_tag("ul", object.errors.full_messages.collect { |msg| content_tag("li", msg) }),
- "id" => options[:id] || "errorExplanation", "class" => options[:class] || "errorExplanation"
+ def error_messages_for(*params)
+ options = params.last.is_a?(Hash) ? params.pop.symbolize_keys : {}
+ objects = params.collect {|object_name| instance_variable_get("@#{object_name}") }.compact
+ count = objects.inject(0) {|sum, object| sum + object.errors.count }
+ unless count.zero?
+ html = {}
+ [:id, :class].each do |key|
+ if options.include?(key)
+ value = options[key]
+ html[key] = value unless value.blank?
+ else
+ html[key] = 'errorExplanation'
+ end
+ end
+ header_message = "#{pluralize(count, 'error')} prohibited this #{(options[:object_name] || params.first).to_s.gsub('_', ' ')} from being saved"
+ error_messages = objects.map {|object| object.errors.full_messages.map {|msg| content_tag(:li, msg) } }
+ content_tag(:div,
+ content_tag(options[:header_tag] || :h2, header_message) <<
+ content_tag(:p, 'There were problems with the following fields:') <<
+ content_tag(:ul, error_messages),
+ html
)
else
- ""
+ ''
end
end
@@ -137,12 +163,14 @@ module ActionView
to_input_field_tag(field_type, options)
when :text
to_text_area_tag(options)
- when :integer, :float
+ when :integer, :float, :decimal
to_input_field_tag("text", options)
when :date
to_date_select_tag(options)
when :datetime, :timestamp
to_datetime_select_tag(options)
+ when :time
+ to_time_select_tag(options)
when :boolean
to_boolean_select_tag(options)
end
@@ -184,6 +212,15 @@ module ActionView
end
end
+ alias_method :to_time_select_tag_without_error_wrapping, :to_time_select_tag
+ def to_time_select_tag(options = {})
+ if object.respond_to?("errors") && object.errors.respond_to?("on")
+ error_wrapping(to_time_select_tag_without_error_wrapping(options), object.errors.on(@method_name))
+ else
+ to_time_select_tag_without_error_wrapping(options)
+ end
+ end
+
def error_wrapping(html_tag, has_error)
has_error ? Base.field_error_proc.call(html_tag, self) : html_tag
end
diff --git a/vendor/rails/actionpack/lib/action_view/helpers/asset_tag_helper.rb b/vendor/rails/actionpack/lib/action_view/helpers/asset_tag_helper.rb
index 2d9d7556..29d77f47 100644
--- a/vendor/rails/actionpack/lib/action_view/helpers/asset_tag_helper.rb
+++ b/vendor/rails/actionpack/lib/action_view/helpers/asset_tag_helper.rb
@@ -3,20 +3,36 @@ require File.dirname(__FILE__) + '/url_helper'
require File.dirname(__FILE__) + '/tag_helper'
module ActionView
- module Helpers
- # Provides methods for linking a HTML page together with other assets, such as javascripts, stylesheets, and feeds.
+ module Helpers #:nodoc:
+ # Provides methods for linking an HTML page together with other assets such
+ # as images, javascripts, stylesheets, and feeds. You can direct Rails to
+ # link to assets from a dedicated assets server by setting ActionController::Base.asset_host
+ # in your environment.rb. These methods do not verify the assets exist before
+ # linking to them.
+ #
+ # ActionController::Base.asset_host = "http://assets.example.com"
+ # image_tag("rails.png")
+ # =>
+ # stylesheet_include_tag("application")
+ # =>
module AssetTagHelper
- # Returns a link tag that browsers and news readers can use to auto-detect a RSS or ATOM feed for this page. The +type+ can
- # either be :rss (default) or :atom and the +options+ follow the url_for style of declaring a link target.
+ # Returns a link tag that browsers and news readers can use to auto-detect
+ # an RSS or ATOM feed. The +type+ can either be :rss (default) or
+ # :atom. Control the link options in url_for format using the
+ # +url_options+. You can modify the LINK tag itself in +tag_options+.
#
- # Examples:
- # auto_discovery_link_tag # =>
+ # Tag Options:
+ # * :rel - Specify the relation of this link, defaults to "alternate"
+ # * :type - Override the auto-generated mime type
+ # * :title - Specify the title of the link, defaults to the +type+
+ #
+ # auto_discovery_link_tag # =>
#
- # auto_discovery_link_tag(:atom) # =>
+ # auto_discovery_link_tag(:atom) # =>
#
- # auto_discovery_link_tag(:rss, {:action => "feed"}) # =>
+ # auto_discovery_link_tag(:rss, {:action => "feed"}) # =>
#
- # auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "My RSS"}) # =>
+ # auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "My RSS"}) # =>
#
def auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {})
tag(
@@ -28,9 +44,14 @@ module ActionView
)
end
- # Returns path to a javascript asset. Example:
+ # Computes the path to a javascript asset in the public javascripts directory.
+ # If the +source+ filename has no extension, .js will be appended.
+ # Full paths from the document root will be passed through.
+ # Used internally by javascript_include_tag to build the script path.
#
# javascript_path "xmlhr" # => /javascripts/xmlhr.js
+ # javascript_path "dir/xmlhr.js" # => /javascripts/dir/xmlhr.js
+ # javascript_path "/dir/xmlhr" # => /dir/xmlhr.js
def javascript_path(source)
compute_public_path(source, 'javascripts', 'js')
end
@@ -38,7 +59,15 @@ module ActionView
JAVASCRIPT_DEFAULT_SOURCES = ['prototype', 'effects', 'dragdrop', 'controls'] unless const_defined?(:JAVASCRIPT_DEFAULT_SOURCES)
@@javascript_default_sources = JAVASCRIPT_DEFAULT_SOURCES.dup
- # Returns a script include tag per source given as argument. Examples:
+ # Returns an html script tag for each of the +sources+ provided. You
+ # can pass in the filename (.js extension is optional) of javascript files
+ # that exist in your public/javascripts directory for inclusion into the
+ # current page or you can pass the full path relative to your document
+ # root. To include the Prototype and Scriptaculous javascript libraries in
+ # your application, pass :defaults as the source. When using
+ # :defaults, if an application.js file exists in your public
+ # javascripts directory, it will be included as well. You can modify the
+ # html attributes of the script tag by passing a hash as the last argument.
#
# javascript_include_tag "xmlhr" # =>
#
@@ -52,11 +81,6 @@ module ActionView
#
# ...
# *see below
- #
- # If there's an application.js file in your public/javascripts directory,
- # javascript_include_tag :defaults will automatically include it. This file
- # facilitates the inclusion of small snippets of JavaScript code, along the lines of
- # controllers/application.rb and helpers/application_helper.rb.
def javascript_include_tag(*sources)
options = sources.last.is_a?(Hash) ? sources.pop.stringify_keys : { }
@@ -69,18 +93,16 @@ module ActionView
sources << "application" if defined?(RAILS_ROOT) && File.exists?("#{RAILS_ROOT}/public/javascripts/application.js")
end
- sources.collect { |source|
+ sources.collect do |source|
source = javascript_path(source)
content_tag("script", "", { "type" => "text/javascript", "src" => source }.merge(options))
- }.join("\n")
+ end.join("\n")
end
# Register one or more additional JavaScript files to be included when
- #
- # javascript_include_tag :defaults
- #
- # is called. This method is intended to be called only from plugin initialization
- # to register extra .js files the plugin installed in public/javascripts.
+ # javascript_include_tag :defaults is called. This method is
+ # only intended to be called from plugin initialization to register additional
+ # .js files that the plugin installed in public/javascripts.
def self.register_javascript_include_default(*sources)
@@javascript_default_sources.concat(sources)
end
@@ -89,14 +111,21 @@ module ActionView
@@javascript_default_sources = JAVASCRIPT_DEFAULT_SOURCES.dup
end
- # Returns path to a stylesheet asset. Example:
+ # Computes the path to a stylesheet asset in the public stylesheets directory.
+ # If the +source+ filename has no extension, .css will be appended.
+ # Full paths from the document root will be passed through.
+ # Used internally by stylesheet_link_tag to build the stylesheet path.
#
# stylesheet_path "style" # => /stylesheets/style.css
+ # stylesheet_path "dir/style.css" # => /stylesheets/dir/style.css
+ # stylesheet_path "/dir/style.css" # => /dir/style.css
def stylesheet_path(source)
compute_public_path(source, 'stylesheets', 'css')
end
- # Returns a css link tag per source given as argument. Examples:
+ # Returns a stylesheet link tag for the sources specified as arguments. If
+ # you don't specify an extension, .css will be appended automatically.
+ # You can modify the link attributes by passing a hash as the last argument.
#
# stylesheet_link_tag "style" # =>
#
@@ -109,31 +138,50 @@ module ActionView
#
def stylesheet_link_tag(*sources)
options = sources.last.is_a?(Hash) ? sources.pop.stringify_keys : { }
- sources.collect { |source|
+ sources.collect do |source|
source = stylesheet_path(source)
tag("link", { "rel" => "Stylesheet", "type" => "text/css", "media" => "screen", "href" => source }.merge(options))
- }.join("\n")
+ end.join("\n")
end
- # Returns path to an image asset. Example:
+ # Computes the path to an image asset in the public images directory.
+ # Full paths from the document root will be passed through.
+ # Used internally by image_tag to build the image path. Passing
+ # a filename without an extension is deprecated.
#
- # The +src+ can be supplied as a...
- # * full path, like "/my_images/image.gif"
- # * file name, like "rss.gif", that gets expanded to "/images/rss.gif"
- # * file name without extension, like "logo", that gets expanded to "/images/logo.png"
+ # image_path("edit.png") # => /images/edit.png
+ # image_path("icons/edit.png") # => /images/icons/edit.png
+ # image_path("/icons/edit.png") # => /icons/edit.png
def image_path(source)
+ unless (source.split("/").last || source).include?(".") || source.blank?
+ ActiveSupport::Deprecation.warn(
+ "You've called image_path with a source that doesn't include an extension. " +
+ "In Rails 2.0, that will not result in .png automatically being appended. " +
+ "So you should call image_path('#{source}.png') instead", caller
+ )
+ end
+
compute_public_path(source, 'images', 'png')
end
- # Returns an image tag converting the +options+ into html options on the tag, but with these special cases:
+ # Returns an html image tag for the +source+. The +source+ can be a full
+ # path or a file that exists in your public images directory. Note that
+ # specifying a filename without the extension is now deprecated in Rails.
+ # You can add html attributes using the +options+. The +options+ supports
+ # two additional keys for convienence and conformance:
#
- # * :alt - If no alt text is given, the file name part of the +src+ is used (capitalized and without the extension)
- # * :size - Supplied as "XxY", so "30x45" becomes width="30" and height="45"
+ # * :alt - If no alt text is given, the file name part of the
+ # +source+ is used (capitalized and without the extension)
+ # * :size - Supplied as "{Width}x{Height}", so "30x45" becomes
+ # width="30" and height="45". :size will be ignored if the
+ # value is not in the correct format.
#
- # The +src+ can be supplied as a...
- # * full path, like "/my_images/image.gif"
- # * file name, like "rss.gif", that gets expanded to "/images/rss.gif"
- # * file name without extension, like "logo", that gets expanded to "/images/logo.png"
+ # image_tag("icon.png") # =>
+ #
+ # image_tag("icon.png", :size => "16x10", :alt => "Edit Entry") # =>
+ #
+ # image_tag("/icons/icon.gif", :size => "16x16") # =>
+ #
def image_tag(source, options = {})
options.symbolize_keys!
@@ -141,8 +189,8 @@ module ActionView
options[:alt] ||= File.basename(options[:src], '.*').split('.').first.capitalize
if options[:size]
- options[:width], options[:height] = options[:size].split("x")
- options.delete :size
+ options[:width], options[:height] = options[:size].split("x") if options[:size] =~ %r{^\d+x\d+$}
+ options.delete(:size)
end
tag("img", options)
@@ -150,11 +198,14 @@ module ActionView
private
def compute_public_path(source, dir, ext)
- source = "/#{dir}/#{source}" unless source.first == "/" || source.include?(":")
- source << ".#{ext}" unless source.split("/").last.include?(".")
- source << '?' + rails_asset_id(source) if defined?(RAILS_ROOT) && %r{^[-a-z]+://} !~ source
- source = "#{@controller.request.relative_url_root}#{source}" unless %r{^[-a-z]+://} =~ source
- source = ActionController::Base.asset_host + source unless source.include?(":")
+ source = source.dup
+ source << ".#{ext}" if File.extname(source).blank?
+ unless source =~ %r{^[-a-z]+://}
+ source = "/#{dir}/#{source}" unless source[0] == ?/
+ asset_id = rails_asset_id(source)
+ source << '?' + asset_id if defined?(RAILS_ROOT) && !asset_id.blank?
+ source = "#{ActionController::Base.asset_host}#{@controller.request.relative_url_root}#{source}"
+ end
source
end
diff --git a/vendor/rails/actionpack/lib/action_view/helpers/capture_helper.rb b/vendor/rails/actionpack/lib/action_view/helpers/capture_helper.rb
index 28b3e299..497ce093 100644
--- a/vendor/rails/actionpack/lib/action_view/helpers/capture_helper.rb
+++ b/vendor/rails/actionpack/lib/action_view/helpers/capture_helper.rb
@@ -89,7 +89,7 @@ module ActionView
# named @@content_for_#{name_of_the_content_block}@. So <%= content_for('footer') %>
# would be avaiable as <%= @content_for_footer %>. The preferred notation now is
# <%= yield :footer %>.
- def content_for(name, &block)
+ def content_for(name, content = nil, &block)
eval "@content_for_#{name} = (@content_for_#{name} || '') + capture(&block)"
end
diff --git a/vendor/rails/actionpack/lib/action_view/helpers/date_helper.rb b/vendor/rails/actionpack/lib/action_view/helpers/date_helper.rb
index 00400956..19dc90ca 100755
--- a/vendor/rails/actionpack/lib/action_view/helpers/date_helper.rb
+++ b/vendor/rails/actionpack/lib/action_view/helpers/date_helper.rb
@@ -13,14 +13,38 @@ module ActionView
module DateHelper
DEFAULT_PREFIX = 'date' unless const_defined?('DEFAULT_PREFIX')
- # Reports the approximate distance in time between two Time objects or integers.
- # For example, if the distance is 47 minutes, it'll return
- # "about 1 hour". See the source for the complete wording list.
+ # Reports the approximate distance in time between two Time or Date objects or integers as seconds.
+ # Set include_seconds to true if you want more detailed approximations when distance < 1 min, 29 secs
+ # Distances are reported base on the following table:
#
- # Integers are interpreted as seconds. So,
- # distance_of_time_in_words(50) returns "less than a minute".
+ # 0 <-> 29 secs # => less than a minute
+ # 30 secs <-> 1 min, 29 secs # => 1 minute
+ # 1 min, 30 secs <-> 44 mins, 29 secs # => [2..44] minutes
+ # 44 mins, 30 secs <-> 89 mins, 29 secs # => about 1 hour
+ # 89 mins, 29 secs <-> 23 hrs, 59 mins, 29 secs # => about [2..24] hours
+ # 23 hrs, 59 mins, 29 secs <-> 47 hrs, 59 mins, 29 secs # => 1 day
+ # 47 hrs, 59 mins, 29 secs <-> 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days
+ # 29 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs # => about 1 month
+ # 59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 31 secs # => [2..12] months
+ # 1 yr minus 30 secs <-> 2 yrs minus 31 secs # => about 1 year
+ # 2 yrs minus 30 secs <-> max time or date # => over [2..X] years
#
- # Set include_seconds to true if you want more detailed approximations if distance < 1 minute
+ # With include_seconds = true and the difference < 1 minute 29 seconds
+ # 0-4 secs # => less than 5 seconds
+ # 5-9 secs # => less than 10 seconds
+ # 10-19 secs # => less than 20 seconds
+ # 20-39 secs # => half a minute
+ # 40-59 secs # => less than a minute
+ # 60-89 secs # => 1 minute
+ #
+ # Examples:
+ #
+ # from_time = Time.now
+ # distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour
+ # distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute
+ # distance_of_time_in_words(from_time, from_time + 15.seconds, true) # => less than 20 seconds
+ #
+ # Note: Rails calculates one year as 365.25 days.
def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
@@ -29,29 +53,33 @@ module ActionView
case distance_in_minutes
when 0..1
- return (distance_in_minutes==0) ? 'less than a minute' : '1 minute' unless include_seconds
+ return (distance_in_minutes == 0) ? 'less than a minute' : '1 minute' unless include_seconds
case distance_in_seconds
- when 0..5 then 'less than 5 seconds'
- when 6..10 then 'less than 10 seconds'
- when 11..20 then 'less than 20 seconds'
- when 21..40 then 'half a minute'
- when 41..59 then 'less than a minute'
+ when 0..4 then 'less than 5 seconds'
+ when 5..9 then 'less than 10 seconds'
+ when 10..19 then 'less than 20 seconds'
+ when 20..39 then 'half a minute'
+ when 40..59 then 'less than a minute'
else '1 minute'
end
-
- when 2..45 then "#{distance_in_minutes} minutes"
- when 46..90 then 'about 1 hour'
- when 90..1440 then "about #{(distance_in_minutes.to_f / 60.0).round} hours"
- when 1441..2880 then '1 day'
- else "#{(distance_in_minutes / 1440).round} days"
+
+ when 2..44 then "#{distance_in_minutes} minutes"
+ when 45..89 then 'about 1 hour'
+ when 90..1439 then "about #{(distance_in_minutes.to_f / 60.0).round} hours"
+ when 1440..2879 then '1 day'
+ when 2880..43199 then "#{(distance_in_minutes / 1440).round} days"
+ when 43200..86399 then 'about 1 month'
+ when 86400..525959 then "#{(distance_in_minutes / 43200).round} months"
+ when 525960..1051919 then 'about 1 year'
+ else "over #{(distance_in_minutes / 525960).round} years"
end
end
-
+
# Like distance_of_time_in_words, but where to_time is fixed to Time.now.
def time_ago_in_words(from_time, include_seconds = false)
distance_of_time_in_words(from_time, Time.now, include_seconds)
end
-
+
alias_method :distance_of_time_in_words_to_now, :time_ago_in_words
# Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute (identified by
@@ -80,6 +108,19 @@ module ActionView
InstanceTag.new(object_name, method, self, nil, options.delete(:object)).to_date_select_tag(options)
end
+ # Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a specified
+ # time-based attribute (identified by +method+) on an object assigned to the template (identified by +object+).
+ # You can include the seconds with :include_seconds.
+ # Examples:
+ #
+ # time_select("post", "sunrise")
+ # time_select("post", "start_time", :include_seconds => true)
+ #
+ # The selects are prepared for multi-parameter assignment to an Active Record object.
+ def time_select(object_name, method, options = {})
+ InstanceTag.new(object_name, method, self, nil, options.delete(:object)).to_time_select_tag(options)
+ end
+
# Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a specified datetime-based
# attribute (identified by +method+) on an object assigned to the template (identified by +object+). Examples:
#
@@ -91,36 +132,55 @@ module ActionView
InstanceTag.new(object_name, method, self, nil, options.delete(:object)).to_datetime_select_tag(options)
end
- # Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+.
- def select_date(date = Date.today, options = {})
- select_year(date, options) + select_month(date, options) + select_day(date, options)
- end
-
# Returns a set of html select-tags (one for year, month, day, hour, and minute) pre-selected with the +datetime+.
- def select_datetime(datetime = Time.now, options = {})
- select_year(datetime, options) + select_month(datetime, options) + select_day(datetime, options) +
- select_hour(datetime, options) + select_minute(datetime, options)
+ # It's also possible to explicitly set the order of the tags using the :order option with an array of
+ # symbols :year, :month and :day in the desired order. If you do not supply a Symbol, it
+ # will be appened onto the :order passed in. You can also add :date_separator and :time_separator
+ # keys to the +options+ to control visual display of the elements.
+ def select_datetime(datetime = Time.now, options = {})
+ separator = options[:datetime_separator] || ''
+ select_date(datetime, options) + separator + select_time(datetime, options)
+ end
+
+ # Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+.
+ # It's possible to explicitly set the order of the tags using the :order option with an array of
+ # symbols :year, :month and :day in the desired order. If you do not supply a Symbol, it
+ # will be appened onto the :order passed in.
+ def select_date(date = Date.today, options = {})
+ options[:order] ||= []
+ [:year, :month, :day].each { |o| options[:order].push(o) unless options[:order].include?(o) }
+
+ select_date = ''
+ options[:order].each do |o|
+ select_date << self.send("select_#{o}", date, options)
+ end
+ select_date
end
# Returns a set of html select-tags (one for hour and minute)
+ # You can set :add_separator key to format the output.
def select_time(datetime = Time.now, options = {})
- h = select_hour(datetime, options) + select_minute(datetime, options) + (options[:include_seconds] ? select_second(datetime, options) : '')
+ separator = options[:time_separator] || ''
+ select_hour(datetime, options) + separator + select_minute(datetime, options) + (options[:include_seconds] ? separator + select_second(datetime, options) : '')
end
# Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.
# The second can also be substituted for a second number.
# Override the field name using the :field_name option, 'second' by default.
def select_second(datetime, options = {})
- second_options = []
-
- 0.upto(59) do |second|
- second_options << ((datetime && (datetime.kind_of?(Fixnum) ? datetime : datetime.sec) == second) ?
- %(\n) :
- %(\n)
- )
+ val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.sec) : ''
+ if options[:use_hidden]
+ options[:include_seconds] ? hidden_html(options[:field_name] || 'second', val, options) : ''
+ else
+ second_options = []
+ 0.upto(59) do |second|
+ second_options << ((val == second) ?
+ %(\n) :
+ %(\n)
+ )
+ end
+ select_html(options[:field_name] || 'second', second_options, options)
end
-
- select_html(options[:field_name] || 'second', second_options, options[:prefix], options[:include_blank], options[:discard_type], options[:disabled])
end
# Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
@@ -128,84 +188,100 @@ module ActionView
# The minute can also be substituted for a minute number.
# Override the field name using the :field_name option, 'minute' by default.
def select_minute(datetime, options = {})
- minute_options = []
-
- 0.step(59, options[:minute_step] || 1) do |minute|
- minute_options << ((datetime && (datetime.kind_of?(Fixnum) ? datetime : datetime.min) == minute) ?
- %(\n) :
- %(\n)
- )
- end
-
- select_html(options[:field_name] || 'minute', minute_options, options[:prefix], options[:include_blank], options[:discard_type], options[:disabled])
+ val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.min) : ''
+ if options[:use_hidden]
+ hidden_html(options[:field_name] || 'minute', val, options)
+ else
+ minute_options = []
+ 0.step(59, options[:minute_step] || 1) do |minute|
+ minute_options << ((val == minute) ?
+ %(\n) :
+ %(\n)
+ )
+ end
+ select_html(options[:field_name] || 'minute', minute_options, options)
+ end
end
# Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
# The hour can also be substituted for a hour number.
# Override the field name using the :field_name option, 'hour' by default.
def select_hour(datetime, options = {})
- hour_options = []
-
- 0.upto(23) do |hour|
- hour_options << ((datetime && (datetime.kind_of?(Fixnum) ? datetime : datetime.hour) == hour) ?
- %(\n) :
- %(\n)
- )
+ val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.hour) : ''
+ if options[:use_hidden]
+ hidden_html(options[:field_name] || 'hour', val, options)
+ else
+ hour_options = []
+ 0.upto(23) do |hour|
+ hour_options << ((val == hour) ?
+ %(\n) :
+ %(\n)
+ )
+ end
+ select_html(options[:field_name] || 'hour', hour_options, options)
end
-
- select_html(options[:field_name] || 'hour', hour_options, options[:prefix], options[:include_blank], options[:discard_type], options[:disabled])
end
# Returns a select tag with options for each of the days 1 through 31 with the current day selected.
# The date can also be substituted for a hour number.
# Override the field name using the :field_name option, 'day' by default.
def select_day(date, options = {})
- day_options = []
-
- 1.upto(31) do |day|
- day_options << ((date && (date.kind_of?(Fixnum) ? date : date.day) == day) ?
- %(\n) :
- %(\n)
- )
+ val = date ? (date.kind_of?(Fixnum) ? date : date.day) : ''
+ if options[:use_hidden]
+ hidden_html(options[:field_name] || 'day', val, options)
+ else
+ day_options = []
+ 1.upto(31) do |day|
+ day_options << ((val == day) ?
+ %(\n) :
+ %(\n)
+ )
+ end
+ select_html(options[:field_name] || 'day', day_options, options)
end
-
- select_html(options[:field_name] || 'day', day_options, options[:prefix], options[:include_blank], options[:discard_type], options[:disabled])
end
# Returns a select tag with options for each of the months January through December with the current month selected.
# The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are used as values
# (what's submitted to the server). It's also possible to use month numbers for the presentation instead of names --
# set the :use_month_numbers key in +options+ to true for this to happen. If you want both numbers and names,
- # set the :add_month_numbers key in +options+ to true. Examples:
+ # set the :add_month_numbers key in +options+ to true. If you would prefer to show month names as abbreviations,
+ # set the :use_short_month key in +options+ to true. If you want to use your own month names, set the
+ # :use_month_names key in +options+ to an array of 12 month names.
+ #
+ # Examples:
#
# select_month(Date.today) # Will use keys like "January", "March"
# select_month(Date.today, :use_month_numbers => true) # Will use keys like "1", "3"
# select_month(Date.today, :add_month_numbers => true) # Will use keys like "1 - January", "3 - March"
+ # select_month(Date.today, :use_short_month => true) # Will use keys like "Jan", "Mar"
+ # select_month(Date.today, :use_month_names => %w(Januar Februar Marts ...)) # Will use keys like "Januar", "Marts"
#
# Override the field name using the :field_name option, 'month' by default.
- #
- # If you would prefer to show month names as abbreviations, set the
- # :use_short_month key in +options+ to true.
def select_month(date, options = {})
- month_options = []
- month_names = options[:use_short_month] ? Date::ABBR_MONTHNAMES : Date::MONTHNAMES
+ val = date ? (date.kind_of?(Fixnum) ? date : date.month) : ''
+ if options[:use_hidden]
+ hidden_html(options[:field_name] || 'month', val, options)
+ else
+ month_options = []
+ month_names = options[:use_month_names] || (options[:use_short_month] ? Date::ABBR_MONTHNAMES : Date::MONTHNAMES)
+ month_names.unshift(nil) if month_names.size < 13
+ 1.upto(12) do |month_number|
+ month_name = if options[:use_month_numbers]
+ month_number
+ elsif options[:add_month_numbers]
+ month_number.to_s + ' - ' + month_names[month_number]
+ else
+ month_names[month_number]
+ end
- 1.upto(12) do |month_number|
- month_name = if options[:use_month_numbers]
- month_number
- elsif options[:add_month_numbers]
- month_number.to_s + ' - ' + month_names[month_number]
- else
- month_names[month_number]
+ month_options << ((val == month_number) ?
+ %(\n) :
+ %(\n)
+ )
end
-
- month_options << ((date && (date.kind_of?(Fixnum) ? date : date.month) == month_number) ?
- %(\n) :
- %(\n)
- )
+ select_html(options[:field_name] || 'month', month_options, options)
end
-
- select_html(options[:field_name] || 'month', month_options, options[:prefix], options[:include_blank], options[:discard_type], options[:disabled])
end
# Returns a select tag with options for each of the five years on each side of the current, which is selected. The five year radius
@@ -215,37 +291,51 @@ module ActionView
#
# select_year(Date.today, :start_year => 1992, :end_year => 2007) # ascending year values
# select_year(Date.today, :start_year => 2005, :end_year => 1900) # descending year values
+ # select_year(2006, :start_year => 2000, :end_year => 2010)
#
# Override the field name using the :field_name option, 'year' by default.
def select_year(date, options = {})
- year_options = []
- y = date ? (date.kind_of?(Fixnum) ? (y = (date == 0) ? Date.today.year : date) : date.year) : Date.today.year
+ val = date ? (date.kind_of?(Fixnum) ? date : date.year) : ''
+ if options[:use_hidden]
+ hidden_html(options[:field_name] || 'year', val, options)
+ else
+ year_options = []
+ y = date ? (date.kind_of?(Fixnum) ? (y = (date == 0) ? Date.today.year : date) : date.year) : Date.today.year
- start_year, end_year = (options[:start_year] || y-5), (options[:end_year] || y+5)
- step_val = start_year < end_year ? 1 : -1
-
- start_year.step(end_year, step_val) do |year|
- year_options << ((date && (date.kind_of?(Fixnum) ? date : date.year) == year) ?
- %(\n) :
- %(\n)
- )
+ start_year, end_year = (options[:start_year] || y-5), (options[:end_year] || y+5)
+ step_val = start_year < end_year ? 1 : -1
+ start_year.step(end_year, step_val) do |year|
+ year_options << ((val == year) ?
+ %(\n) :
+ %(\n)
+ )
+ end
+ select_html(options[:field_name] || 'year', year_options, options)
end
-
- select_html(options[:field_name] || 'year', year_options, options[:prefix], options[:include_blank], options[:discard_type], options[:disabled])
end
private
- def select_html(type, options, prefix = nil, include_blank = false, discard_type = false, disabled = false)
- select_html = %(\n"
end
+ def hidden_html(type, value, options)
+ name_and_id_from_options(options, type)
+ hidden_html = %(\n)
+ end
+
+ def name_and_id_from_options(options, type)
+ options[:name] = (options[:prefix] || DEFAULT_PREFIX) + (options[:discard_type] ? '' : "[#{type}]")
+ options[:id] = options[:name].gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '')
+ end
+
def leading_zero_on_single_digits(number)
number > 9 ? number : "0#{number}"
end
@@ -255,43 +345,71 @@ module ActionView
include DateHelper
def to_date_select_tag(options = {})
- defaults = { :discard_type => true }
- options = defaults.merge(options)
- options_with_prefix = Proc.new { |position| options.merge(:prefix => "#{@object_name}[#{@method_name}(#{position}i)]") }
- date = options[:include_blank] ? (value || 0) : (value || Date.today)
+ date_or_time_select options.merge(:discard_hour => true)
+ end
- date_select = ''
- options[:order] = [:month, :year, :day] if options[:month_before_year] # For backwards compatibility
- options[:order] ||= [:year, :month, :day]
-
- position = {:year => 1, :month => 2, :day => 3}
-
- discard = {}
- discard[:year] = true if options[:discard_year]
- discard[:month] = true if options[:discard_month]
- discard[:day] = true if options[:discard_day] or options[:discard_month]
-
- options[:order].each do |param|
- date_select << self.send("select_#{param}", date, options_with_prefix.call(position[param])) unless discard[param]
- end
-
- date_select
+ def to_time_select_tag(options = {})
+ date_or_time_select options.merge(:discard_year => true, :discard_month => true)
end
def to_datetime_select_tag(options = {})
- defaults = { :discard_type => true }
- options = defaults.merge(options)
- options_with_prefix = Proc.new { |position| options.merge(:prefix => "#{@object_name}[#{@method_name}(#{position}i)]") }
- datetime = options[:include_blank] ? (value || nil) : (value || Time.now)
-
- datetime_select = select_year(datetime, options_with_prefix.call(1))
- datetime_select << select_month(datetime, options_with_prefix.call(2)) unless options[:discard_month]
- datetime_select << select_day(datetime, options_with_prefix.call(3)) unless options[:discard_day] || options[:discard_month]
- datetime_select << ' — ' + select_hour(datetime, options_with_prefix.call(4)) unless options[:discard_hour]
- datetime_select << ' : ' + select_minute(datetime, options_with_prefix.call(5)) unless options[:discard_minute] || options[:discard_hour]
-
- datetime_select
+ date_or_time_select options
end
+
+ private
+ def date_or_time_select(options)
+ defaults = { :discard_type => true }
+ options = defaults.merge(options)
+ datetime = value(object)
+ datetime ||= Time.now unless options[:include_blank]
+
+ position = { :year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6 }
+
+ order = (options[:order] ||= [:year, :month, :day])
+
+ # Discard explicit and implicit by not being included in the :order
+ discard = {}
+ discard[:year] = true if options[:discard_year] or !order.include?(:year)
+ discard[:month] = true if options[:discard_month] or !order.include?(:month)
+ discard[:day] = true if options[:discard_day] or discard[:month] or !order.include?(:day)
+ discard[:hour] = true if options[:discard_hour]
+ discard[:minute] = true if options[:discard_minute] or discard[:hour]
+ discard[:second] = true unless options[:include_seconds] && !discard[:minute]
+
+ # Maintain valid dates by including hidden fields for discarded elements
+ [:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
+ # Ensure proper ordering of :hour, :minute and :second
+ [:hour, :minute, :second].each { |o| order.delete(o); order.push(o) }
+
+ date_or_time_select = ''
+ order.reverse.each do |param|
+ # Send hidden fields for discarded elements once output has started
+ # This ensures AR can reconstruct valid dates using ParseDate
+ next if discard[param] && date_or_time_select.empty?
+
+ date_or_time_select.insert(0, self.send("select_#{param}", datetime, options_with_prefix(position[param], options.merge(:use_hidden => discard[param]))))
+ date_or_time_select.insert(0,
+ case param
+ when :hour then (discard[:year] && discard[:day] ? "" : " — ")
+ when :minute then " : "
+ when :second then options[:include_seconds] ? " : " : ""
+ else ""
+ end)
+
+ end
+
+ date_or_time_select
+ end
+
+ def options_with_prefix(position, options)
+ prefix = "#{@object_name}"
+ if options[:index]
+ prefix << "[#{options[:index]}]"
+ elsif @auto_index
+ prefix << "[#{@auto_index}]"
+ end
+ options.merge(:prefix => "#{prefix}[#{@method_name}(#{position}i)]")
+ end
end
class FormBuilder
@@ -299,6 +417,10 @@ module ActionView
@template.date_select(@object_name, method, options.merge(:object => @object))
end
+ def time_select(method, options = {})
+ @template.time_select(@object_name, method, options.merge(:object => @object))
+ end
+
def datetime_select(method, options = {})
@template.datetime_select(@object_name, method, options.merge(:object => @object))
end
diff --git a/vendor/rails/actionpack/lib/action_view/helpers/debug_helper.rb b/vendor/rails/actionpack/lib/action_view/helpers/debug_helper.rb
index 8baea6f4..9e92813a 100644
--- a/vendor/rails/actionpack/lib/action_view/helpers/debug_helper.rb
+++ b/vendor/rails/actionpack/lib/action_view/helpers/debug_helper.rb
@@ -7,7 +7,7 @@ module ActionView
begin
Marshal::dump(object)
"
#{h(object.to_yaml).gsub(" ", " ")}
"
- rescue Object => e
+ rescue Exception => e # errors from Marshal or YAML
# Object couldn't be dumped, perhaps because of singleton methods -- this is the fallback
"#{h(object.inspect)}"
end
diff --git a/vendor/rails/actionpack/lib/action_view/helpers/form_helper.rb b/vendor/rails/actionpack/lib/action_view/helpers/form_helper.rb
index 7c8748d6..772753b7 100644
--- a/vendor/rails/actionpack/lib/action_view/helpers/form_helper.rb
+++ b/vendor/rails/actionpack/lib/action_view/helpers/form_helper.rb
@@ -142,11 +142,13 @@ module ActionView
#
# Note: This also works for the methods in FormOptionHelper and DateHelper that are designed to work with an object as base.
# Like collection_select and datetime_select.
- def fields_for(object_name, *args, &proc)
+ def fields_for(object_name, *args, &block)
raise ArgumentError, "Missing block" unless block_given?
options = args.last.is_a?(Hash) ? args.pop : {}
object = args.first
- yield((options[:builder] || FormBuilder).new(object_name, object, self, options, proc))
+
+ builder = options[:builder] || ActionView::Base.default_form_builder
+ yield builder.new(object_name, object, self, options, block)
end
# Returns an input tag of the "text" type tailored for accessing a specified attribute (identified by +method+) on an object
@@ -238,7 +240,11 @@ module ActionView
@template_object, @local_binding = template_object, local_binding
@object = object
if @object_name.sub!(/\[\]$/,"")
- @auto_index = @template_object.instance_variable_get("@#{Regexp.last_match.pre_match}").id_before_type_cast
+ if object ||= @template_object.instance_variable_get("@#{Regexp.last_match.pre_match}") and object.respond_to?(:id_before_type_cast)
+ @auto_index = object.id_before_type_cast
+ else
+ raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to id_before_type_cast: #{object.inspect}"
+ end
end
end
@@ -250,7 +256,7 @@ module ActionView
options.delete("size")
end
options["type"] = field_type
- options["value"] ||= value_before_type_cast unless field_type == "file"
+ options["value"] ||= value_before_type_cast(object) unless field_type == "file"
add_default_name_and_id(options)
tag("input", options)
end
@@ -259,9 +265,15 @@ module ActionView
options = DEFAULT_RADIO_OPTIONS.merge(options.stringify_keys)
options["type"] = "radio"
options["value"] = tag_value
- options["checked"] = "checked" if value.to_s == tag_value.to_s
+ if options.has_key?("checked")
+ cv = options.delete "checked"
+ checked = cv == true || cv == "checked"
+ else
+ checked = self.class.radio_button_checked?(value(object), tag_value)
+ end
+ options["checked"] = "checked" if checked
pretty_tag_value = tag_value.to_s.gsub(/\s/, "_").gsub(/\W/, "").downcase
- options["id"] = @auto_index ?
+ options["id"] ||= defined?(@auto_index) ?
"#{@object_name}_#{@auto_index}_#{@method_name}_#{pretty_tag_value}" :
"#{@object_name}_#{@method_name}_#{pretty_tag_value}"
add_default_name_and_id(options)
@@ -271,14 +283,82 @@ module ActionView
def to_text_area_tag(options = {})
options = DEFAULT_TEXT_AREA_OPTIONS.merge(options.stringify_keys)
add_default_name_and_id(options)
- content_tag("textarea", html_escape(options.delete('value') || value_before_type_cast), options)
+
+ if size = options.delete("size")
+ options["cols"], options["rows"] = size.split("x")
+ end
+
+ content_tag("textarea", html_escape(options.delete('value') || value_before_type_cast(object)), options)
end
def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0")
options = options.stringify_keys
options["type"] = "checkbox"
options["value"] = checked_value
- checked = case value
+ if options.has_key?("checked")
+ cv = options.delete "checked"
+ checked = cv == true || cv == "checked"
+ else
+ checked = self.class.check_box_checked?(value(object), checked_value)
+ end
+ options["checked"] = "checked" if checked
+ add_default_name_and_id(options)
+ tag("input", options) << tag("input", "name" => options["name"], "type" => "hidden", "value" => unchecked_value)
+ end
+
+ def to_date_tag()
+ defaults = DEFAULT_DATE_OPTIONS.dup
+ date = value(object) || Date.today
+ options = Proc.new { |position| defaults.merge(:prefix => "#{@object_name}[#{@method_name}(#{position}i)]") }
+ html_day_select(date, options.call(3)) +
+ html_month_select(date, options.call(2)) +
+ html_year_select(date, options.call(1))
+ end
+
+ def to_boolean_select_tag(options = {})
+ options = options.stringify_keys
+ add_default_name_and_id(options)
+ value = value(object)
+ tag_text = ""
+ end
+
+ def to_content_tag(tag_name, options = {})
+ content_tag(tag_name, value(object), options)
+ end
+
+ def object
+ @object || @template_object.instance_variable_get("@#{@object_name}")
+ end
+
+ def value(object)
+ self.class.value(object, @method_name)
+ end
+
+ def value_before_type_cast(object)
+ self.class.value_before_type_cast(object, @method_name)
+ end
+
+ class << self
+ def value(object, method_name)
+ object.send method_name unless object.nil?
+ end
+
+ def value_before_type_cast(object, method_name)
+ unless object.nil?
+ object.respond_to?(method_name + "_before_type_cast") ?
+ object.send(method_name + "_before_type_cast") :
+ object.send(method_name)
+ end
+ end
+
+ def check_box_checked?(value, checked_value)
+ case value
when TrueClass, FalseClass
value
when NilClass
@@ -290,55 +370,10 @@ module ActionView
else
value.to_i != 0
end
- if checked || options["checked"] == "checked"
- options["checked"] = "checked"
- else
- options.delete("checked")
end
- add_default_name_and_id(options)
- tag("input", options) << tag("input", "name" => options["name"], "type" => "hidden", "value" => unchecked_value)
- end
-
- def to_date_tag()
- defaults = DEFAULT_DATE_OPTIONS.dup
- date = value || Date.today
- options = Proc.new { |position| defaults.merge(:prefix => "#{@object_name}[#{@method_name}(#{position}i)]") }
- html_day_select(date, options.call(3)) +
- html_month_select(date, options.call(2)) +
- html_year_select(date, options.call(1))
- end
-
- def to_boolean_select_tag(options = {})
- options = options.stringify_keys
- add_default_name_and_id(options)
- tag_text = ""
- end
-
- def to_content_tag(tag_name, options = {})
- content_tag(tag_name, value, options)
- end
-
- def object
- @object || @template_object.instance_variable_get("@#{@object_name}")
- end
-
- def value
- unless object.nil?
- object.send(@method_name)
- end
- end
-
- def value_before_type_cast
- unless object.nil?
- object.respond_to?(@method_name + "_before_type_cast") ?
- object.send(@method_name + "_before_type_cast") :
- object.send(@method_name)
+
+ def radio_button_checked?(value, checked_value)
+ value.to_s == checked_value.to_s
end
end
@@ -348,11 +383,11 @@ module ActionView
options["name"] ||= tag_name_with_index(options["index"])
options["id"] ||= tag_id_with_index(options["index"])
options.delete("index")
- elsif @auto_index
+ elsif defined?(@auto_index)
options["name"] ||= tag_name_with_index(@auto_index)
options["id"] ||= tag_id_with_index(@auto_index)
else
- options["name"] ||= tag_name
+ options["name"] ||= tag_name + (options.has_key?('multiple') ? '[]' : '')
options["id"] ||= tag_id
end
end
@@ -379,7 +414,7 @@ module ActionView
class_inheritable_accessor :field_helpers
self.field_helpers = (FormHelper.instance_methods - ['form_for'])
- attr_accessor :object_name, :object
+ attr_accessor :object_name, :object, :options
def initialize(object_name, object, template, options, proc)
@object_name, @object, @template, @options, @proc = object_name, object, template, options, proc
@@ -403,4 +438,9 @@ module ActionView
end
end
end
+
+ class Base
+ cattr_accessor :default_form_builder
+ self.default_form_builder = ::ActionView::Helpers::FormBuilder
+ end
end
diff --git a/vendor/rails/actionpack/lib/action_view/helpers/form_options_helper.rb b/vendor/rails/actionpack/lib/action_view/helpers/form_options_helper.rb
index 53b39305..6b3da64f 100644
--- a/vendor/rails/actionpack/lib/action_view/helpers/form_options_helper.rb
+++ b/vendor/rails/actionpack/lib/action_view/helpers/form_options_helper.rb
@@ -26,7 +26,7 @@ module ActionView
#
# Another common case is a select tag for an belongs_to-associated object. For example,
#
- # select("post", "person_id", Person.find_all.collect {|p| [ p.name, p.id ] })
+ # select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] })
#
# could become:
#
@@ -43,7 +43,7 @@ module ActionView
# See options_for_select for the required format of the choices parameter.
#
# Example with @post.person_id => 1:
- # select("post", "person_id", Person.find_all.collect {|p| [ p.name, p.id ] }, { :include_blank => true })
+ # select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }, { :include_blank => true })
#
# could become:
#
@@ -113,7 +113,6 @@ module ActionView
options_for_select = container.inject([]) do |options, element|
if !element.is_a?(String) and element.respond_to?(:first) and element.respond_to?(:last)
- is_selected = ( (selected.respond_to?(:include?) ? selected.include?(element.last) : element.last == selected) )
is_selected = ( (selected.respond_to?(:include?) && !selected.is_a?(String) ? selected.include?(element.last) : element.last == selected) )
if is_selected
options << ""
@@ -121,7 +120,6 @@ module ActionView
options << ""
end
else
- is_selected = ( (selected.respond_to?(:include?) ? selected.include?(element) : element == selected) )
is_selected = ( (selected.respond_to?(:include?) && !selected.is_a?(String) ? selected.include?(element) : element == selected) )
options << ((is_selected) ? "" : "")
end
@@ -299,13 +297,15 @@ module ActionView
def to_select_tag(choices, options, html_options)
html_options = html_options.stringify_keys
add_default_name_and_id(html_options)
+ value = value(object)
selected_value = options.has_key?(:selected) ? options[:selected] : value
- content_tag("select", add_options(options_for_select(choices, selected_value), options, value), html_options)
+ content_tag("select", add_options(options_for_select(choices, selected_value), options, selected_value), html_options)
end
def to_collection_select_tag(collection, value_method, text_method, options, html_options)
html_options = html_options.stringify_keys
add_default_name_and_id(html_options)
+ value = value(object)
content_tag(
"select", add_options(options_from_collection_for_select(collection, value_method, text_method, value), options, value), html_options
)
@@ -314,12 +314,14 @@ module ActionView
def to_country_select_tag(priority_countries, options, html_options)
html_options = html_options.stringify_keys
add_default_name_and_id(html_options)
+ value = value(object)
content_tag("select", add_options(country_options_for_select(value, priority_countries), options, value), html_options)
end
def to_time_zone_select_tag(priority_zones, options, html_options)
html_options = html_options.stringify_keys
add_default_name_and_id(html_options)
+ value = value(object)
content_tag("select",
add_options(
time_zone_options_for_select(value, priority_zones, options[:model] || TimeZone),
diff --git a/vendor/rails/actionpack/lib/action_view/helpers/form_tag_helper.rb b/vendor/rails/actionpack/lib/action_view/helpers/form_tag_helper.rb
index c7a5d1bb..e2e796e7 100644
--- a/vendor/rails/actionpack/lib/action_view/helpers/form_tag_helper.rb
+++ b/vendor/rails/actionpack/lib/action_view/helpers/form_tag_helper.rb
@@ -12,14 +12,49 @@ module ActionView
# Starts a form tag that points the action to an url configured with url_for_options just like
# ActionController::Base#url_for. The method for the form defaults to POST.
#
+ # Examples:
+ # * form_tag('/posts') =>
+ # * form_tag('/posts/1', :method => :put) =>
+ # * form_tag('/upload', :multipart => true) =>
+ #
+ # ERb example:
+ # <% form_tag '/posts' do -%>
+ #
<%= submit_tag 'Save' %>
+ # <% end -%>
+ #
+ # Will output:
+ #
+ #
# Options:
# * :multipart - If set to true, the enctype is set to "multipart/form-data".
- # * :method - The method to use when submitting the form, usually either "get" or "post".
- def form_tag(url_for_options = {}, options = {}, *parameters_for_url, &proc)
- html_options = { "method" => "post" }.merge(options.stringify_keys)
+ # * :method - The method to use when submitting the form, usually either "get" or "post".
+ # If "put", "delete", or another verb is used, a hidden input with name _method
+ # is added to simulate the verb over post.
+ def form_tag(url_for_options = {}, options = {}, *parameters_for_url, &block)
+ html_options = options.stringify_keys
html_options["enctype"] = "multipart/form-data" if html_options.delete("multipart")
- html_options["action"] = url_for(url_for_options, *parameters_for_url)
- tag :form, html_options, true
+ html_options["action"] = url_for(url_for_options, *parameters_for_url)
+
+ method_tag = ""
+
+ case method = html_options.delete("method").to_s
+ when /^get$/i # must be case-insentive, but can't use downcase as might be nil
+ html_options["method"] = "get"
+ when /^post$/i, "", nil
+ html_options["method"] = "post"
+ else
+ html_options["method"] = "post"
+ method_tag = content_tag(:div, tag(:input, :type => "hidden", :name => "_method", :value => method), :style => 'margin:0;padding:0')
+ end
+
+ if block_given?
+ content = capture(&block)
+ concat(tag(:form, html_options, true) + method_tag, block.binding)
+ concat(content, block.binding)
+ concat("", block.binding)
+ else
+ tag(:form, html_options, true) + method_tag
+ end
end
alias_method :start_form_tag, :form_tag
@@ -28,6 +63,8 @@ module ActionView
def end_form_tag
""
end
+
+ deprecate :end_form_tag, :start_form_tag => :form_tag
# Creates a dropdown selection box, or if the :multiple option is set to true, a multiple
# choice selection box.
@@ -110,7 +147,8 @@ module ActionView
# Creates a radio button.
def radio_button_tag(name, value, checked = false, options = {})
- html_options = { "type" => "radio", "name" => name, "id" => name, "value" => value }.update(options.stringify_keys)
+ pretty_tag_value = value.to_s.gsub(/\s/, "_").gsub(/(?!-)\W/, "").downcase
+ html_options = { "type" => "radio", "name" => name, "id" => "#{name}_#{pretty_tag_value}", "value" => value }.update(options.stringify_keys)
html_options["checked"] = "checked" if checked
tag :input, html_options
end
diff --git a/vendor/rails/actionpack/lib/action_view/helpers/java_script_macros_helper.rb b/vendor/rails/actionpack/lib/action_view/helpers/java_script_macros_helper.rb
index 2cb64c95..463fe0e1 100644
--- a/vendor/rails/actionpack/lib/action_view/helpers/java_script_macros_helper.rb
+++ b/vendor/rails/actionpack/lib/action_view/helpers/java_script_macros_helper.rb
@@ -7,6 +7,8 @@ module ActionView
# editing relies on ActionController::Base.in_place_edit_for and the autocompletion relies on
# ActionController::Base.auto_complete_for.
module JavaScriptMacrosHelper
+ # DEPRECATION WARNING: This method will become a separate plugin when Rails 2.0 ships.
+ #
# Makes an HTML element specified by the DOM ID +field_id+ become an in-place
# editor of a property.
#
@@ -27,20 +29,21 @@ module ActionView
# :url:: Specifies the url where the updated value should
# be sent after the user presses "ok".
#
- #
# Addtional +options+ are:
# :rows:: Number of rows (more than 1 will use a TEXTAREA)
# :cols:: Number of characters the text input should span (works for both INPUT and TEXTAREA)
# :size:: Synonym for :cols when using a single line text input.
# :cancel_text:: The text on the cancel link. (default: "cancel")
# :save_text:: The text on the save link. (default: "ok")
- # :loading_text:: The text to display when submitting to the server (default: "Saving...")
+ # :loading_text:: The text to display while the data is being loaded from the server (default: "Loading...")
+ # :saving_text:: The text to display when submitting to the server (default: "Saving...")
# :external_control:: The id of an external control used to enter edit mode.
# :load_text_url:: URL where initial value of editor (content) is retrieved.
# :options:: Pass through options to the AJAX call (see prototype's Ajax.Updater)
# :with:: JavaScript snippet that should return what is to be sent
# in the AJAX call, +form+ is an implicit parameter
# :script:: Instructs the in-place editor to evaluate the remote JavaScript response (default: false)
+ # :click_to_edit_text::The text shown during mouseover the editable text (default: "Click to edit")
def in_place_editor(field_id, options = {})
function = "new Ajax.InPlaceEditor("
function << "'#{field_id}', "
@@ -50,6 +53,7 @@ module ActionView
js_options['cancelText'] = %('#{options[:cancel_text]}') if options[:cancel_text]
js_options['okText'] = %('#{options[:save_text]}') if options[:save_text]
js_options['loadingText'] = %('#{options[:loading_text]}') if options[:loading_text]
+ js_options['savingText'] = %('#{options[:saving_text]}') if options[:saving_text]
js_options['rows'] = options[:rows] if options[:rows]
js_options['cols'] = options[:cols] if options[:cols]
js_options['size'] = options[:size] if options[:size]
@@ -58,6 +62,7 @@ module ActionView
js_options['ajaxOptions'] = options[:options] if options[:options]
js_options['evalScripts'] = options[:script] if options[:script]
js_options['callback'] = "function(form) { return #{options[:with]} }" if options[:with]
+ js_options['clickToEditText'] = %('#{options[:click_to_edit_text]}') if options[:click_to_edit_text]
function << (', ' + options_for_javascript(js_options)) unless js_options.empty?
function << ')'
@@ -65,6 +70,8 @@ module ActionView
javascript_tag(function)
end
+ # DEPRECATION WARNING: This method will become a separate plugin when Rails 2.0 ships.
+ #
# Renders the value of the specified object and method with in-place editing capabilities.
#
# See the RDoc on ActionController::InPlaceEditing to learn more about this.
@@ -76,14 +83,16 @@ module ActionView
in_place_editor(tag_options[:id], in_place_editor_options)
end
+ # DEPRECATION WARNING: This method will become a separate plugin when Rails 2.0 ships.
+ #
# Adds AJAX autocomplete functionality to the text input field with the
# DOM ID specified by +field_id+.
#
- # This function expects that the called action returns a HTML
list,
+ # This function expects that the called action returns an HTML
list,
# or nothing if no entries should be displayed for autocompletion.
#
# You'll probably want to turn the browser's built-in autocompletion off,
- # so be sure to include a autocomplete="off" attribute with your text
+ # so be sure to include an autocomplete="off" attribute with your text
# input field.
#
# The autocompleter object is assigned to a Javascript variable named field_id_auto_completer.
@@ -91,45 +100,45 @@ module ActionView
# other means than user input (for that specific case, call the activate method on that object).
#
# Required +options+ are:
- # :url:: URL to call for autocompletion results
- # in url_for format.
+ # :url:: URL to call for autocompletion results
+ # in url_for format.
#
# Addtional +options+ are:
- # :update:: Specifies the DOM ID of the element whose
- # innerHTML should be updated with the autocomplete
- # entries returned by the AJAX request.
- # Defaults to field_id + '_auto_complete'
- # :with:: A JavaScript expression specifying the
- # parameters for the XMLHttpRequest. This defaults
- # to 'fieldname=value'.
- # :frequency:: Determines the time to wait after the last keystroke
- # for the AJAX request to be initiated.
- # :indicator:: Specifies the DOM ID of an element which will be
- # displayed while autocomplete is running.
- # :tokens:: A string or an array of strings containing
- # separator tokens for tokenized incremental
- # autocompletion. Example: :tokens => ',' would
- # allow multiple autocompletion entries, separated
- # by commas.
- # :min_chars:: The minimum number of characters that should be
- # in the input field before an Ajax call is made
- # to the server.
- # :on_hide:: A Javascript expression that is called when the
- # autocompletion div is hidden. The expression
- # should take two variables: element and update.
- # Element is a DOM element for the field, update
- # is a DOM element for the div from which the
- # innerHTML is replaced.
- # :on_show:: Like on_hide, only now the expression is called
- # then the div is shown.
- # :after_update_element:: A Javascript expression that is called when the
- # user has selected one of the proposed values.
- # The expression should take two variables: element and value.
- # Element is a DOM element for the field, value
- # is the value selected by the user.
- # :select:: Pick the class of the element from which the value for
- # insertion should be extracted. If this is not specified,
- # the entire element is used.
+ # :update:: Specifies the DOM ID of the element whose
+ # innerHTML should be updated with the autocomplete
+ # entries returned by the AJAX request.
+ # Defaults to field_id + '_auto_complete'
+ # :with:: A JavaScript expression specifying the
+ # parameters for the XMLHttpRequest. This defaults
+ # to 'fieldname=value'.
+ # :frequency:: Determines the time to wait after the last keystroke
+ # for the AJAX request to be initiated.
+ # :indicator:: Specifies the DOM ID of an element which will be
+ # displayed while autocomplete is running.
+ # :tokens:: A string or an array of strings containing
+ # separator tokens for tokenized incremental
+ # autocompletion. Example: :tokens => ',' would
+ # allow multiple autocompletion entries, separated
+ # by commas.
+ # :min_chars:: The minimum number of characters that should be
+ # in the input field before an Ajax call is made
+ # to the server.
+ # :on_hide:: A Javascript expression that is called when the
+ # autocompletion div is hidden. The expression
+ # should take two variables: element and update.
+ # Element is a DOM element for the field, update
+ # is a DOM element for the div from which the
+ # innerHTML is replaced.
+ # :on_show:: Like on_hide, only now the expression is called
+ # then the div is shown.
+ # :after_update_element:: A Javascript expression that is called when the
+ # user has selected one of the proposed values.
+ # The expression should take two variables: element and value.
+ # Element is a DOM element for the field, value
+ # is the value selected by the user.
+ # :select:: Pick the class of the element from which the value for
+ # insertion should be extracted. If this is not specified,
+ # the entire element is used.
def auto_complete_field(field_id, options = {})
function = "var #{field_id}_auto_completer = new Ajax.Autocompleter("
function << "'#{field_id}', "
@@ -141,6 +150,7 @@ module ActionView
js_options[:callback] = "function(element, value) { return #{options[:with]} }" if options[:with]
js_options[:indicator] = "'#{options[:indicator]}'" if options[:indicator]
js_options[:select] = "'#{options[:select]}'" if options[:select]
+ js_options[:paramName] = "'#{options[:param_name]}'" if options[:param_name]
js_options[:frequency] = "#{options[:frequency]}" if options[:frequency]
{ :after_update_element => :afterUpdateElement,
@@ -153,6 +163,8 @@ module ActionView
javascript_tag(function)
end
+ # DEPRECATION WARNING: This method will become a separate plugin when Rails 2.0 ships.
+ #
# Use this method in your view to generate a return for the AJAX autocomplete requests.
#
# Example action:
@@ -161,7 +173,7 @@ module ActionView
# @items = Item.find(:all,
# :conditions => [ 'LOWER(description) LIKE ?',
# '%' + request.raw_post.downcase + '%' ])
- # render :inline => '<%= auto_complete_result(@items, 'description') %>'
+ # render :inline => "<%= auto_complete_result(@items, 'description') %>"
# end
#
# The auto_complete_result can of course also be called from a view belonging to the
@@ -172,12 +184,14 @@ module ActionView
content_tag("ul", items.uniq)
end
+ # DEPRECATION WARNING: This method will become a separate plugin when Rails 2.0 ships.
+ #
# Wrapper for text_field with added AJAX autocompletion functionality.
#
# In your controller, you'll need to define an action called
- # auto_complete_for_object_method to respond the AJAX calls,
+ # auto_complete_for to respond the AJAX calls,
#
- # See the RDoc on ActionController::AutoComplete to learn more about this.
+ # See the RDoc on ActionController::Macros::AutoComplete to learn more about this.
def text_field_with_auto_complete(object, method, tag_options = {}, completion_options = {})
(completion_options[:skip_style] ? "" : auto_complete_stylesheet) +
text_field(object, method, tag_options) +
@@ -187,7 +201,7 @@ module ActionView
private
def auto_complete_stylesheet
- content_tag("style", <<-EOT
+ content_tag('style', <<-EOT, :type => 'text/css')
div.auto_complete {
width: 350px;
background: #fff;
@@ -212,7 +226,6 @@ module ActionView
padding:0;
}
EOT
- )
end
end
diff --git a/vendor/rails/actionpack/lib/action_view/helpers/javascript_helper.rb b/vendor/rails/actionpack/lib/action_view/helpers/javascript_helper.rb
index 93a6e700..7bce6b91 100644
--- a/vendor/rails/actionpack/lib/action_view/helpers/javascript_helper.rb
+++ b/vendor/rails/actionpack/lib/action_view/helpers/javascript_helper.rb
@@ -1,4 +1,5 @@
require File.dirname(__FILE__) + '/tag_helper'
+require File.dirname(__FILE__) + '/prototype_helper'
module ActionView
module Helpers
@@ -40,15 +41,50 @@ module ActionView
unless const_defined? :JAVASCRIPT_PATH
JAVASCRIPT_PATH = File.join(File.dirname(__FILE__), 'javascripts')
end
+
+ include PrototypeHelper
- # Returns a link that'll trigger a JavaScript +function+ using the
+ # Returns a link that will trigger a JavaScript +function+ using the
# onclick handler and return false after the fact.
#
+ # The +function+ argument can be omitted in favor of an +update_page+
+ # block, which evaluates to a string when the template is rendered
+ # (instead of making an Ajax request first).
+ #
# Examples:
# link_to_function "Greeting", "alert('Hello world!')"
- # link_to_function(image_tag("delete"), "if confirm('Really?'){ do_delete(); }")
- def link_to_function(name, function, html_options = {})
+ # Produces:
+ # Greeting
+ #
+ # link_to_function(image_tag("delete"), "if (confirm('Really?')) do_delete()")
+ # Produces:
+ #
+ #
+ #
+ #
+ # link_to_function("Show me more", nil, :id => "more_link") do |page|
+ # page[:details].visual_effect :toggle_blind
+ # page[:more_link].replace_html "Show me less"
+ # end
+ # Produces:
+ # Show me more
+ #
+ def link_to_function(name, *args, &block)
+ html_options = args.last.is_a?(Hash) ? args.pop : {}
+ function = args[0] || ''
+
html_options.symbolize_keys!
+ function = update_page(&block) if block_given?
content_tag(
"a", name,
html_options.merge({
@@ -58,14 +94,28 @@ module ActionView
)
end
- # Returns a link that'll trigger a JavaScript +function+ using the
+ # Returns a button that'll trigger a JavaScript +function+ using the
# onclick handler.
#
+ # The +function+ argument can be omitted in favor of an +update_page+
+ # block, which evaluates to a string when the template is rendered
+ # (instead of making an Ajax request first).
+ #
# Examples:
# button_to_function "Greeting", "alert('Hello world!')"
- # button_to_function "Delete", "if confirm('Really?'){ do_delete(); }")
- def button_to_function(name, function, html_options = {})
+ # button_to_function "Delete", "if (confirm('Really?')) do_delete()"
+ # button_to_function "Details" do |page|
+ # page[:details].visual_effect :toggle_slide
+ # end
+ # button_to_function "Details", :class => "details_button" do |page|
+ # page[:details].visual_effect :toggle_slide
+ # end
+ def button_to_function(name, *args, &block)
+ html_options = args.last.is_a?(Hash) ? args.pop : {}
+ function = args[0] || ''
+
html_options.symbolize_keys!
+ function = update_page(&block) if block_given?
tag(:input, html_options.merge({
:type => "button", :value => name,
:onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};"
@@ -99,13 +149,24 @@ module ActionView
# Escape carrier returns and single and double quotes for JavaScript segments.
def escape_javascript(javascript)
- (javascript || '').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" }
+ (javascript || '').gsub('\\','\0\0').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" }
end
# Returns a JavaScript tag with the +content+ inside. Example:
- # javascript_tag "alert('All is good')" # =>
- def javascript_tag(content)
- content_tag("script", javascript_cdata_section(content), :type => "text/javascript")
+ # javascript_tag "alert('All is good')"
+ #
+ # Returns:
+ #
+ #
+ #
+ # +html_options+ may be a hash of attributes for the
+ def javascript_tag(content, html_options = {})
+ content_tag("script", javascript_cdata_section(content), html_options.merge(:type => "text/javascript"))
end
def javascript_cdata_section(content) #:nodoc:
diff --git a/vendor/rails/actionpack/lib/action_view/helpers/javascripts/controls.js b/vendor/rails/actionpack/lib/action_view/helpers/javascripts/controls.js
index de0261ed..8c273f87 100644
--- a/vendor/rails/actionpack/lib/action_view/helpers/javascripts/controls.js
+++ b/vendor/rails/actionpack/lib/action_view/helpers/javascripts/controls.js
@@ -1,12 +1,13 @@
-// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
-// (c) 2005 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
-// (c) 2005 Jon Tirsen (http://www.tirsen.com)
+// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// (c) 2005, 2006 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
+// (c) 2005, 2006 Jon Tirsen (http://www.tirsen.com)
// Contributors:
// Richard Livsey
// Rahul Bhargava
// Rob Wills
//
-// See scriptaculous.js for full license.
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
// Autocompleter.Base handles all the autocompletion functionality
// that's independent of the data source for autocompletion. This
@@ -33,6 +34,9 @@
// useful when one of the tokens is \n (a newline), as it
// allows smart autocompletion after linebreaks.
+if(typeof Effect == 'undefined')
+ throw("controls.js requires including script.aculo.us' effects.js library");
+
var Autocompleter = {}
Autocompleter.Base = function() {};
Autocompleter.Base.prototype = {
@@ -45,7 +49,7 @@ Autocompleter.Base.prototype = {
this.index = 0;
this.entryCount = 0;
- if (this.setOptions)
+ if(this.setOptions)
this.setOptions(options);
else
this.options = options || {};
@@ -55,17 +59,20 @@ Autocompleter.Base.prototype = {
this.options.frequency = this.options.frequency || 0.4;
this.options.minChars = this.options.minChars || 1;
this.options.onShow = this.options.onShow ||
- function(element, update){
- if(!update.style.position || update.style.position=='absolute') {
- update.style.position = 'absolute';
- Position.clone(element, update, {setHeight: false, offsetTop: element.offsetHeight});
- }
- Effect.Appear(update,{duration:0.15});
- };
+ function(element, update){
+ if(!update.style.position || update.style.position=='absolute') {
+ update.style.position = 'absolute';
+ Position.clone(element, update, {
+ setHeight: false,
+ offsetTop: element.offsetHeight
+ });
+ }
+ Effect.Appear(update,{duration:0.15});
+ };
this.options.onHide = this.options.onHide ||
- function(element, update){ new Effect.Fade(update,{duration:0.15}) };
+ function(element, update){ new Effect.Fade(update,{duration:0.15}) };
- if (typeof(this.options.tokens) == 'string')
+ if(typeof(this.options.tokens) == 'string')
this.options.tokens = new Array(this.options.tokens);
this.observer = null;
@@ -94,7 +101,7 @@ Autocompleter.Base.prototype = {
},
fixIEOverlapping: function() {
- Position.clone(this.update, this.iefix);
+ Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
this.iefix.style.zIndex = 1;
this.update.style.zIndex = 2;
Element.show(this.iefix);
@@ -202,11 +209,13 @@ Autocompleter.Base.prototype = {
markPrevious: function() {
if(this.index > 0) this.index--
else this.index = this.entryCount-1;
+ this.getEntry(this.index).scrollIntoView(true);
},
markNext: function() {
if(this.index < this.entryCount-1) this.index++
else this.index = 0;
+ this.getEntry(this.index).scrollIntoView(false);
},
getEntry: function(index) {
@@ -254,11 +263,11 @@ Autocompleter.Base.prototype = {
if(!this.changed && this.hasFocus) {
this.update.innerHTML = choices;
Element.cleanWhitespace(this.update);
- Element.cleanWhitespace(this.update.firstChild);
+ Element.cleanWhitespace(this.update.down());
- if(this.update.firstChild && this.update.firstChild.childNodes) {
+ if(this.update.firstChild && this.update.down().childNodes) {
this.entryCount =
- this.update.firstChild.childNodes.length;
+ this.update.down().childNodes.length;
for (var i = 0; i < this.entryCount; i++) {
var entry = this.getEntry(i);
entry.autocompleteIndex = i;
@@ -269,9 +278,14 @@ Autocompleter.Base.prototype = {
}
this.stopIndicator();
-
this.index = 0;
- this.render();
+
+ if(this.entryCount==1 && this.options.autoSelect) {
+ this.selectEntry();
+ this.hide();
+ } else {
+ this.render();
+ }
}
},
@@ -459,6 +473,7 @@ Ajax.InPlaceEditor.prototype = {
this.element = $(element);
this.options = Object.extend({
+ paramName: "value",
okButton: true,
okText: "ok",
cancelLink: true,
@@ -531,7 +546,7 @@ Ajax.InPlaceEditor.prototype = {
Element.hide(this.element);
this.createForm();
this.element.parentNode.insertBefore(this.form, this.element);
- Field.scrollFreeActivate(this.editField);
+ if (!this.options.loadTextURL) Field.scrollFreeActivate(this.editField);
// stop the event to avoid a page refresh in Safari
if (evt) {
Event.stop(evt);
@@ -590,7 +605,7 @@ Ajax.InPlaceEditor.prototype = {
var textField = document.createElement("input");
textField.obj = this;
textField.type = "text";
- textField.name = "value";
+ textField.name = this.options.paramName;
textField.value = text;
textField.style.backgroundColor = this.options.highlightcolor;
textField.className = 'editor_field';
@@ -603,7 +618,7 @@ Ajax.InPlaceEditor.prototype = {
this.options.textarea = true;
var textArea = document.createElement("textarea");
textArea.obj = this;
- textArea.name = "value";
+ textArea.name = this.options.paramName;
textArea.value = this.convertHTMLLineBreaks(text);
textArea.rows = this.options.rows;
textArea.cols = this.options.cols || 40;
@@ -636,6 +651,7 @@ Ajax.InPlaceEditor.prototype = {
Element.removeClassName(this.form, this.options.loadingClassName);
this.editField.disabled = false;
this.editField.value = transport.responseText.stripTags();
+ Field.scrollFreeActivate(this.editField);
},
onclickCancel: function() {
this.onComplete();
@@ -772,6 +788,8 @@ Object.extend(Ajax.InPlaceCollectionEditor.prototype, {
collection.each(function(e,i) {
optionTag = document.createElement("option");
optionTag.value = (e instanceof Array) ? e[0] : e;
+ if((typeof this.options.value == 'undefined') &&
+ ((e instanceof Array) ? this.element.innerHTML == e[1] : e == optionTag.value)) optionTag.selected = true;
if(this.options.value==optionTag.value) optionTag.selected = true;
optionTag.appendChild(document.createTextNode((e instanceof Array) ? e[1] : e));
selectTag.appendChild(optionTag);
diff --git a/vendor/rails/actionpack/lib/action_view/helpers/javascripts/dragdrop.js b/vendor/rails/actionpack/lib/action_view/helpers/javascripts/dragdrop.js
index a01b7be2..c71ddb82 100644
--- a/vendor/rails/actionpack/lib/action_view/helpers/javascripts/dragdrop.js
+++ b/vendor/rails/actionpack/lib/action_view/helpers/javascripts/dragdrop.js
@@ -1,9 +1,11 @@
-// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
-// (c) 2005 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
+// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// (c) 2005, 2006 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
//
-// See scriptaculous.js for full license.
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
-/*--------------------------------------------------------------------------*/
+if(typeof Effect == 'undefined')
+ throw("dragdrop.js requires including script.aculo.us' effects.js library");
var Droppables = {
drops: [],
@@ -145,8 +147,16 @@ var Draggables = {
},
activate: function(draggable) {
- window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
- this.activeDraggable = draggable;
+ if(draggable.options.delay) {
+ this._timeout = setTimeout(function() {
+ Draggables._timeout = null;
+ window.focus();
+ Draggables.activeDraggable = draggable;
+ }.bind(this), draggable.options.delay);
+ } else {
+ window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
+ this.activeDraggable = draggable;
+ }
},
deactivate: function() {
@@ -160,10 +170,15 @@ var Draggables = {
// the same coordinates, prevent needless redrawing (moz bug?)
if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
this._lastPointer = pointer;
+
this.activeDraggable.updateDrag(event, pointer);
},
endDrag: function(event) {
+ if(this._timeout) {
+ clearTimeout(this._timeout);
+ this._timeout = null;
+ }
if(!this.activeDraggable) return;
this._lastPointer = null;
this.activeDraggable.endDrag(event);
@@ -190,6 +205,7 @@ var Draggables = {
this.observers.each( function(o) {
if(o[eventName]) o[eventName](eventName, draggable, event);
});
+ if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
},
_cacheObserverCallbacks: function() {
@@ -204,39 +220,59 @@ var Draggables = {
/*--------------------------------------------------------------------------*/
var Draggable = Class.create();
+Draggable._dragging = {};
+
Draggable.prototype = {
initialize: function(element) {
- var options = Object.extend({
+ var defaults = {
handle: false,
- starteffect: function(element) {
- new Effect.Opacity(element, {duration:0.2, from:1.0, to:0.7});
- },
reverteffect: function(element, top_offset, left_offset) {
var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
- element._revert = new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur});
+ new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
+ queue: {scope:'_draggable', position:'end'}
+ });
},
- endeffect: function(element) {
- new Effect.Opacity(element, {duration:0.2, from:0.7, to:1.0});
+ endeffect: function(element) {
+ var toOpacity = typeof element._opacity == 'number' ? element._opacity : 1.0;
+ new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
+ queue: {scope:'_draggable', position:'end'},
+ afterFinish: function(){
+ Draggable._dragging[element] = false
+ }
+ });
},
zindex: 1000,
revert: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
- snap: false // false, or xy or [x,y] or function(x,y){ return [x,y] }
- }, arguments[1] || {});
+ snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
+ delay: 0
+ };
+
+ if(!arguments[1] || typeof arguments[1].endeffect == 'undefined')
+ Object.extend(defaults, {
+ starteffect: function(element) {
+ element._opacity = Element.getOpacity(element);
+ Draggable._dragging[element] = true;
+ new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
+ }
+ });
+
+ var options = Object.extend(defaults, arguments[1] || {});
this.element = $(element);
- if(options.handle && (typeof options.handle == 'string')) {
- var h = Element.childrenWithClassName(this.element, options.handle, true);
- if(h.length>0) this.handle = h[0];
- }
+ if(options.handle && (typeof options.handle == 'string'))
+ this.handle = this.element.down('.'+options.handle, 0);
+
if(!this.handle) this.handle = $(options.handle);
if(!this.handle) this.handle = this.element;
- if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML)
+ if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
options.scroll = $(options.scroll);
+ this._isScrollChild = Element.childOf(this.element, options.scroll);
+ }
Element.makePositioned(this.element); // fix IE
@@ -262,6 +298,8 @@ Draggable.prototype = {
},
initDrag: function(event) {
+ if(typeof Draggable._dragging[this.element] != 'undefined' &&
+ Draggable._dragging[this.element]) return;
if(Event.isLeftClick(event)) {
// abort on form elements, fixes a Firefox issue
var src = Event.element(event);
@@ -272,11 +310,6 @@ Draggable.prototype = {
src.tagName=='BUTTON' ||
src.tagName=='TEXTAREA')) return;
- if(this.element._revert) {
- this.element._revert.cancel();
- this.element._revert = null;
- }
-
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var pos = Position.cumulativeOffset(this.element);
this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
@@ -312,6 +345,7 @@ Draggable.prototype = {
}
Draggables.notify('onStart', this, event);
+
if(this.options.starteffect) this.options.starteffect(this.element);
},
@@ -320,6 +354,7 @@ Draggable.prototype = {
Position.prepare();
Droppables.show(pointer, this.element);
Draggables.notify('onDrag', this, event);
+
this.draw(pointer);
if(this.options.change) this.options.change(this);
@@ -331,8 +366,8 @@ Draggable.prototype = {
with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
} else {
p = Position.page(this.options.scroll);
- p[0] += this.options.scroll.scrollLeft;
- p[1] += this.options.scroll.scrollTop;
+ p[0] += this.options.scroll.scrollLeft + Position.deltaX;
+ p[1] += this.options.scroll.scrollTop + Position.deltaY;
p.push(p[0]+this.options.scroll.offsetWidth);
p.push(p[1]+this.options.scroll.offsetHeight);
}
@@ -378,7 +413,7 @@ Draggable.prototype = {
if(this.options.endeffect)
this.options.endeffect(this.element);
-
+
Draggables.deactivate(this);
Droppables.reset();
},
@@ -398,10 +433,15 @@ Draggable.prototype = {
draw: function(point) {
var pos = Position.cumulativeOffset(this.element);
+ if(this.options.ghosting) {
+ var r = Position.realOffset(this.element);
+ pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
+ }
+
var d = this.currentDelta();
pos[0] -= d[0]; pos[1] -= d[1];
- if(this.options.scroll && (this.options.scroll != window)) {
+ if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
}
@@ -412,7 +452,7 @@ Draggable.prototype = {
if(this.options.snap) {
if(typeof this.options.snap == 'function') {
- p = this.options.snap(p[0],p[1]);
+ p = this.options.snap(p[0],p[1],this);
} else {
if(this.options.snap instanceof Array) {
p = p.map( function(v, i) {
@@ -428,6 +468,7 @@ Draggable.prototype = {
style.left = p[0] + "px";
if((!this.options.constraint) || (this.options.constraint=='vertical'))
style.top = p[1] + "px";
+
if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
},
@@ -440,6 +481,7 @@ Draggable.prototype = {
},
startScrolling: function(speed) {
+ if(!(speed[0] || speed[1])) return;
this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
this.lastScrolled = new Date();
this.scrollInterval = setInterval(this.scroll.bind(this), 10);
@@ -464,14 +506,16 @@ Draggable.prototype = {
Position.prepare();
Droppables.show(Draggables._lastPointer, this.element);
Draggables.notify('onDrag', this);
- Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
- Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
- Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
- if (Draggables._lastScrollPointer[0] < 0)
- Draggables._lastScrollPointer[0] = 0;
- if (Draggables._lastScrollPointer[1] < 0)
- Draggables._lastScrollPointer[1] = 0;
- this.draw(Draggables._lastScrollPointer);
+ if (this._isScrollChild) {
+ Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
+ Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
+ Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
+ if (Draggables._lastScrollPointer[0] < 0)
+ Draggables._lastScrollPointer[0] = 0;
+ if (Draggables._lastScrollPointer[1] < 0)
+ Draggables._lastScrollPointer[1] = 0;
+ this.draw(Draggables._lastScrollPointer);
+ }
if(this.options.change) this.options.change(this);
},
@@ -523,6 +567,8 @@ SortableObserver.prototype = {
}
var Sortable = {
+ SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
+
sortables: {},
_findRootElement: function(element) {
@@ -563,12 +609,13 @@ var Sortable = {
containment: element, // also takes array of elements (or id's); or false
handle: false, // or a CSS class
only: false,
+ delay: 0,
hoverclass: null,
ghosting: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
- format: /^[^_]*_(.*)$/,
+ format: this.SERIALIZE_RULE,
onChange: Prototype.emptyFunction,
onUpdate: Prototype.emptyFunction
}, arguments[1] || {});
@@ -582,6 +629,7 @@ var Sortable = {
scroll: options.scroll,
scrollSpeed: options.scrollSpeed,
scrollSensitivity: options.scrollSensitivity,
+ delay: options.delay,
ghosting: options.ghosting,
constraint: options.constraint,
handle: options.handle };
@@ -610,7 +658,6 @@ var Sortable = {
tree: options.tree,
hoverclass: options.hoverclass,
onHover: Sortable.onHover
- //greedy: !options.dropOnEmpty
}
var options_for_tree = {
@@ -635,7 +682,7 @@ var Sortable = {
(this.findElements(element, options) || []).each( function(e) {
// handles are per-draggable
var handle = options.handle ?
- Element.childrenWithClassName(e, options.handle)[0] : e;
+ $(e).down('.'+options.handle,0) : e;
options.draggables.push(
new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
Droppables.add(e, options_for_droppable);
@@ -706,7 +753,7 @@ var Sortable = {
if(!Element.isParent(dropon, element)) {
var index;
- var children = Sortable.findElements(dropon, {tag: droponOptions.tag});
+ var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
var child = null;
if(children) {
@@ -733,7 +780,7 @@ var Sortable = {
},
unmark: function() {
- if(Sortable._marker) Element.hide(Sortable._marker);
+ if(Sortable._marker) Sortable._marker.hide();
},
mark: function(dropon, position) {
@@ -742,23 +789,21 @@ var Sortable = {
if(sortable && !sortable.ghosting) return;
if(!Sortable._marker) {
- Sortable._marker = $('dropmarker') || document.createElement('DIV');
- Element.hide(Sortable._marker);
- Element.addClassName(Sortable._marker, 'dropmarker');
- Sortable._marker.style.position = 'absolute';
+ Sortable._marker =
+ ($('dropmarker') || Element.extend(document.createElement('DIV'))).
+ hide().addClassName('dropmarker').setStyle({position:'absolute'});
document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
}
var offsets = Position.cumulativeOffset(dropon);
- Sortable._marker.style.left = offsets[0] + 'px';
- Sortable._marker.style.top = offsets[1] + 'px';
+ Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
if(position=='after')
if(sortable.overlap == 'horizontal')
- Sortable._marker.style.left = (offsets[0]+dropon.clientWidth) + 'px';
+ Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
else
- Sortable._marker.style.top = (offsets[1]+dropon.clientHeight) + 'px';
+ Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
- Element.show(Sortable._marker);
+ Sortable._marker.show();
},
_tree: function(element, options, parent) {
@@ -773,9 +818,9 @@ var Sortable = {
id: encodeURIComponent(match ? match[1] : null),
element: element,
parent: parent,
- children: new Array,
+ children: [],
position: parent.children.length,
- container: Sortable._findChildrenElement(children[i], options.treeTag.toUpperCase())
+ container: $(children[i]).down(options.treeTag)
}
/* Get the element containing the children and recurse over it */
@@ -788,17 +833,6 @@ var Sortable = {
return parent;
},
- /* Finds the first element of the given tag type within a parent element.
- Used for finding the first LI[ST] within a L[IST]I[TEM].*/
- _findChildrenElement: function (element, containerTag) {
- if (element && element.hasChildNodes)
- for (var i = 0; i < element.childNodes.length; ++i)
- if (element.childNodes[i].tagName == containerTag)
- return element.childNodes[i];
-
- return null;
- },
-
tree: function(element) {
element = $(element);
var sortableOptions = this.options(element);
@@ -813,12 +847,12 @@ var Sortable = {
var root = {
id: null,
parent: null,
- children: new Array,
+ children: [],
container: element,
position: 0
}
- return Sortable._tree (element, options, root);
+ return Sortable._tree(element, options, root);
},
/* Construct a [i] index for a particular node */
@@ -867,7 +901,7 @@ var Sortable = {
if (options.tree) {
return Sortable.tree(element, arguments[1]).children.map( function (item) {
- return [name + Sortable._constructIndex(item) + "=" +
+ return [name + Sortable._constructIndex(item) + "[id]=" +
encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
}).flatten().join('&');
} else {
@@ -878,12 +912,10 @@ var Sortable = {
}
}
-/* Returns true if child is contained within element */
+// Returns true if child is contained within element
Element.isParent = function(child, element) {
if (!child.parentNode || child == element) return false;
-
if (child.parentNode == element) return true;
-
return Element.isParent(child.parentNode, element);
}
@@ -906,8 +938,5 @@ Element.findChildren = function(element, only, recursive, tagName) {
}
Element.offsetSize = function (element, type) {
- if (type == 'vertical' || type == 'height')
- return element.offsetHeight;
- else
- return element.offsetWidth;
-}
\ No newline at end of file
+ return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
+}
diff --git a/vendor/rails/actionpack/lib/action_view/helpers/javascripts/effects.js b/vendor/rails/actionpack/lib/action_view/helpers/javascripts/effects.js
index 92740050..3b02eda2 100644
--- a/vendor/rails/actionpack/lib/action_view/helpers/javascripts/effects.js
+++ b/vendor/rails/actionpack/lib/action_view/helpers/javascripts/effects.js
@@ -1,15 +1,16 @@
-// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
// Justin Palmer (http://encytemedia.com/)
// Mark Pilgrim (http://diveintomark.org/)
// Martin Bialasinki
//
-// See scriptaculous.js for full license.
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
// converts rgb() and #xxx to #xxxxxx format,
// returns self (or first argument) if not convertable
String.prototype.parseColor = function() {
- var color = '#';
+ var color = '#';
if(this.slice(0,4) == 'rgb(') {
var cols = this.slice(4,this.length-1).split(',');
var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
@@ -41,15 +42,17 @@ Element.collectTextNodesIgnoreClass = function(element, className) {
Element.setContentZoom = function(element, percent) {
element = $(element);
- Element.setStyle(element, {fontSize: (percent/100) + 'em'});
+ element.setStyle({fontSize: (percent/100) + 'em'});
if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
+ return element;
}
-Element.getOpacity = function(element){
+Element.getOpacity = function(element){
+ element = $(element);
var opacity;
- if (opacity = Element.getStyle(element, 'opacity'))
+ if (opacity = element.getStyle('opacity'))
return parseFloat(opacity);
- if (opacity = (Element.getStyle(element, 'filter') || '').match(/alpha\(opacity=(.*)\)/))
+ if (opacity = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
if(opacity[1]) return parseFloat(opacity[1]) / 100;
return 1.0;
}
@@ -57,34 +60,26 @@ Element.getOpacity = function(element){
Element.setOpacity = function(element, value){
element= $(element);
if (value == 1){
- Element.setStyle(element, { opacity:
+ element.setStyle({ opacity:
(/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ?
- 0.999999 : null });
- if(/MSIE/.test(navigator.userAgent))
- Element.setStyle(element, {filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'')});
+ 0.999999 : 1.0 });
+ if(/MSIE/.test(navigator.userAgent) && !window.opera)
+ element.setStyle({filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'')});
} else {
if(value < 0.00001) value = 0;
- Element.setStyle(element, {opacity: value});
- if(/MSIE/.test(navigator.userAgent))
- Element.setStyle(element,
- { filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'') +
- 'alpha(opacity='+value*100+')' });
+ element.setStyle({opacity: value});
+ if(/MSIE/.test(navigator.userAgent) && !window.opera)
+ element.setStyle(
+ { filter: element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') +
+ 'alpha(opacity='+value*100+')' });
}
+ return element;
}
Element.getInlineOpacity = function(element){
return $(element).style.opacity || '';
}
-Element.childrenWithClassName = function(element, className, findFirst) {
- var classNameRegExp = new RegExp("(^|\\s)" + className + "(\\s|$)");
- var results = $A($(element).getElementsByTagName('*'))[findFirst ? 'detect' : 'select']( function(c) {
- return (c.className && c.className.match(classNameRegExp));
- });
- if(!results) results = [];
- return results;
-}
-
Element.forceRerendering = function(element) {
try {
element = $(element);
@@ -104,9 +99,17 @@ Array.prototype.call = function() {
/*--------------------------------------------------------------------------*/
var Effect = {
+ _elementDoesNotExistError: {
+ name: 'ElementDoesNotExistError',
+ message: 'The specified DOM element does not exist, but is required for this effect to operate'
+ },
tagifyText: function(element) {
+ if(typeof Builder == 'undefined')
+ throw("Effect.tagifyText requires including script.aculo.us' builder.js library");
+
var tagifyStyle = 'position:relative';
- if(/MSIE/.test(navigator.userAgent)) tagifyStyle += ';zoom:1';
+ if(/MSIE/.test(navigator.userAgent) && !window.opera) tagifyStyle += ';zoom:1';
+
element = $(element);
$A(element.childNodes).each( function(child) {
if(child.nodeType==3) {
@@ -159,33 +162,35 @@ var Effect2 = Effect; // deprecated
/* ------------- transitions ------------- */
-Effect.Transitions = {}
-
-Effect.Transitions.linear = function(pos) {
- return pos;
-}
-Effect.Transitions.sinoidal = function(pos) {
- return (-Math.cos(pos*Math.PI)/2) + 0.5;
-}
-Effect.Transitions.reverse = function(pos) {
- return 1-pos;
-}
-Effect.Transitions.flicker = function(pos) {
- return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
-}
-Effect.Transitions.wobble = function(pos) {
- return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
-}
-Effect.Transitions.pulse = function(pos) {
- return (Math.floor(pos*10) % 2 == 0 ?
- (pos*10-Math.floor(pos*10)) : 1-(pos*10-Math.floor(pos*10)));
-}
-Effect.Transitions.none = function(pos) {
- return 0;
-}
-Effect.Transitions.full = function(pos) {
- return 1;
-}
+Effect.Transitions = {
+ linear: Prototype.K,
+ sinoidal: function(pos) {
+ return (-Math.cos(pos*Math.PI)/2) + 0.5;
+ },
+ reverse: function(pos) {
+ return 1-pos;
+ },
+ flicker: function(pos) {
+ return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
+ },
+ wobble: function(pos) {
+ return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
+ },
+ pulse: function(pos, pulses) {
+ pulses = pulses || 5;
+ return (
+ Math.round((pos % (1/pulses)) * pulses) == 0 ?
+ ((pos * pulses * 2) - Math.floor(pos * pulses * 2)) :
+ 1 - ((pos * pulses * 2) - Math.floor(pos * pulses * 2))
+ );
+ },
+ none: function(pos) {
+ return 0;
+ },
+ full: function(pos) {
+ return 1;
+ }
+};
/* ------------- core effects ------------- */
@@ -212,6 +217,9 @@ Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), {
e.finishOn += effect.finishOn;
});
break;
+ case 'with-last':
+ timestamp = this.effects.pluck('startOn').max() || timestamp;
+ break;
case 'end':
// start effect after last queued effect has finished
timestamp = this.effects.pluck('finishOn').max() || timestamp;
@@ -348,12 +356,24 @@ Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), {
}
});
+Effect.Event = Class.create();
+Object.extend(Object.extend(Effect.Event.prototype, Effect.Base.prototype), {
+ initialize: function() {
+ var options = Object.extend({
+ duration: 0
+ }, arguments[0] || {});
+ this.start(options);
+ },
+ update: Prototype.emptyFunction
+});
+
Effect.Opacity = Class.create();
Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), {
initialize: function(element) {
this.element = $(element);
+ if(!this.element) throw(Effect._elementDoesNotExistError);
// make this work on IE on elements without 'layout'
- if(/MSIE/.test(navigator.userAgent) && (!this.element.hasLayout))
+ if(/MSIE/.test(navigator.userAgent) && !window.opera && (!this.element.currentStyle.hasLayout))
this.element.setStyle({zoom: 1});
var options = Object.extend({
from: this.element.getOpacity() || 0.0,
@@ -370,6 +390,7 @@ Effect.Move = Class.create();
Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), {
initialize: function(element) {
this.element = $(element);
+ if(!this.element) throw(Effect._elementDoesNotExistError);
var options = Object.extend({
x: 0,
y: 0,
@@ -393,8 +414,8 @@ Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), {
},
update: function(position) {
this.element.setStyle({
- left: this.options.x * position + this.originalLeft + 'px',
- top: this.options.y * position + this.originalTop + 'px'
+ left: Math.round(this.options.x * position + this.originalLeft) + 'px',
+ top: Math.round(this.options.y * position + this.originalTop) + 'px'
});
}
});
@@ -408,7 +429,8 @@ Effect.MoveBy = function(element, toTop, toLeft) {
Effect.Scale = Class.create();
Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
initialize: function(element, percent) {
- this.element = $(element)
+ this.element = $(element);
+ if(!this.element) throw(Effect._elementDoesNotExistError);
var options = Object.extend({
scaleX: true,
scaleY: true,
@@ -433,7 +455,7 @@ Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
this.originalLeft = this.element.offsetLeft;
var fontSize = this.element.getStyle('font-size') || '100%';
- ['em','px','%'].each( function(fontSizeType) {
+ ['em','px','%','pt'].each( function(fontSizeType) {
if(fontSize.indexOf(fontSizeType)>0) {
this.fontSize = parseFloat(fontSize);
this.fontSizeType = fontSizeType;
@@ -458,12 +480,12 @@ Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
},
finish: function(position) {
- if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
+ if(this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
},
setDimensions: function(height, width) {
var d = {};
- if(this.options.scaleX) d.width = width + 'px';
- if(this.options.scaleY) d.height = height + 'px';
+ if(this.options.scaleX) d.width = Math.round(width) + 'px';
+ if(this.options.scaleY) d.height = Math.round(height) + 'px';
if(this.options.scaleFromCenter) {
var topd = (height - this.dims[0])/2;
var leftd = (width - this.dims[1])/2;
@@ -483,6 +505,7 @@ Effect.Highlight = Class.create();
Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), {
initialize: function(element) {
this.element = $(element);
+ if(!this.element) throw(Effect._elementDoesNotExistError);
var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {});
this.start(options);
},
@@ -547,8 +570,7 @@ Effect.Fade = function(element) {
to: 0.0,
afterFinishInternal: function(effect) {
if(effect.options.to!=0) return;
- effect.element.hide();
- effect.element.setStyle({opacity: oldOpacity});
+ effect.element.hide().setStyle({opacity: oldOpacity});
}}, arguments[1] || {});
return new Effect.Opacity(element,options);
}
@@ -563,25 +585,31 @@ Effect.Appear = function(element) {
effect.element.forceRerendering();
},
beforeSetup: function(effect) {
- effect.element.setOpacity(effect.options.from);
- effect.element.show();
+ effect.element.setOpacity(effect.options.from).show();
}}, arguments[1] || {});
return new Effect.Opacity(element,options);
}
Effect.Puff = function(element) {
element = $(element);
- var oldStyle = { opacity: element.getInlineOpacity(), position: element.getStyle('position') };
+ var oldStyle = {
+ opacity: element.getInlineOpacity(),
+ position: element.getStyle('position'),
+ top: element.style.top,
+ left: element.style.left,
+ width: element.style.width,
+ height: element.style.height
+ };
return new Effect.Parallel(
[ new Effect.Scale(element, 200,
{ sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
Object.extend({ duration: 1.0,
beforeSetupInternal: function(effect) {
- effect.effects[0].element.setStyle({position: 'absolute'}); },
+ Position.absolutize(effect.effects[0].element)
+ },
afterFinishInternal: function(effect) {
- effect.effects[0].element.hide();
- effect.effects[0].element.setStyle(oldStyle); }
+ effect.effects[0].element.hide().setStyle(oldStyle); }
}, arguments[1] || {})
);
}
@@ -589,13 +617,12 @@ Effect.Puff = function(element) {
Effect.BlindUp = function(element) {
element = $(element);
element.makeClipping();
- return new Effect.Scale(element, 0,
+ return new Effect.Scale(element, 0,
Object.extend({ scaleContent: false,
scaleX: false,
restoreAfterFinish: true,
afterFinishInternal: function(effect) {
- effect.element.hide();
- effect.element.undoClipping();
+ effect.element.hide().undoClipping();
}
}, arguments[1] || {})
);
@@ -604,28 +631,25 @@ Effect.BlindUp = function(element) {
Effect.BlindDown = function(element) {
element = $(element);
var elementDimensions = element.getDimensions();
- return new Effect.Scale(element, 100,
- Object.extend({ scaleContent: false,
- scaleX: false,
- scaleFrom: 0,
- scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
- restoreAfterFinish: true,
- afterSetup: function(effect) {
- effect.element.makeClipping();
- effect.element.setStyle({height: '0px'});
- effect.element.show();
- },
- afterFinishInternal: function(effect) {
- effect.element.undoClipping();
- }
- }, arguments[1] || {})
- );
+ return new Effect.Scale(element, 100, Object.extend({
+ scaleContent: false,
+ scaleX: false,
+ scaleFrom: 0,
+ scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
+ restoreAfterFinish: true,
+ afterSetup: function(effect) {
+ effect.element.makeClipping().setStyle({height: '0px'}).show();
+ },
+ afterFinishInternal: function(effect) {
+ effect.element.undoClipping();
+ }
+ }, arguments[1] || {}));
}
Effect.SwitchOff = function(element) {
element = $(element);
var oldOpacity = element.getInlineOpacity();
- return new Effect.Appear(element, {
+ return new Effect.Appear(element, Object.extend({
duration: 0.4,
from: 0,
transition: Effect.Transitions.flicker,
@@ -634,18 +658,14 @@ Effect.SwitchOff = function(element) {
duration: 0.3, scaleFromCenter: true,
scaleX: false, scaleContent: false, restoreAfterFinish: true,
beforeSetup: function(effect) {
- effect.element.makePositioned();
- effect.element.makeClipping();
+ effect.element.makePositioned().makeClipping();
},
afterFinishInternal: function(effect) {
- effect.element.hide();
- effect.element.undoClipping();
- effect.element.undoPositioned();
- effect.element.setStyle({opacity: oldOpacity});
+ effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
}
})
}
- });
+ }, arguments[1] || {}));
}
Effect.DropOut = function(element) {
@@ -663,9 +683,7 @@ Effect.DropOut = function(element) {
effect.effects[0].element.makePositioned();
},
afterFinishInternal: function(effect) {
- effect.effects[0].element.hide();
- effect.effects[0].element.undoPositioned();
- effect.effects[0].element.setStyle(oldStyle);
+ effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
}
}, arguments[1] || {}));
}
@@ -687,54 +705,42 @@ Effect.Shake = function(element) {
{ x: 40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
- effect.element.undoPositioned();
- effect.element.setStyle(oldStyle);
+ effect.element.undoPositioned().setStyle(oldStyle);
}}) }}) }}) }}) }}) }});
}
Effect.SlideDown = function(element) {
- element = $(element);
- element.cleanWhitespace();
+ element = $(element).cleanWhitespace();
// SlideDown need to have the content of the element wrapped in a container element with fixed height!
- var oldInnerBottom = $(element.firstChild).getStyle('bottom');
+ var oldInnerBottom = element.down().getStyle('bottom');
var elementDimensions = element.getDimensions();
return new Effect.Scale(element, 100, Object.extend({
scaleContent: false,
scaleX: false,
- scaleFrom: 0,
+ scaleFrom: window.opera ? 0 : 1,
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
restoreAfterFinish: true,
afterSetup: function(effect) {
effect.element.makePositioned();
- effect.element.firstChild.makePositioned();
+ effect.element.down().makePositioned();
if(window.opera) effect.element.setStyle({top: ''});
- effect.element.makeClipping();
- effect.element.setStyle({height: '0px'});
- effect.element.show(); },
+ effect.element.makeClipping().setStyle({height: '0px'}).show();
+ },
afterUpdateInternal: function(effect) {
- effect.element.firstChild.setStyle({bottom:
+ effect.element.down().setStyle({bottom:
(effect.dims[0] - effect.element.clientHeight) + 'px' });
},
afterFinishInternal: function(effect) {
- effect.element.undoClipping();
- // IE will crash if child is undoPositioned first
- if(/MSIE/.test(navigator.userAgent)){
- effect.element.undoPositioned();
- effect.element.firstChild.undoPositioned();
- }else{
- effect.element.firstChild.undoPositioned();
- effect.element.undoPositioned();
- }
- effect.element.firstChild.setStyle({bottom: oldInnerBottom}); }
+ effect.element.undoClipping().undoPositioned();
+ effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
}, arguments[1] || {})
);
}
-
+
Effect.SlideUp = function(element) {
- element = $(element);
- element.cleanWhitespace();
- var oldInnerBottom = $(element.firstChild).getStyle('bottom');
- return new Effect.Scale(element, 0,
+ element = $(element).cleanWhitespace();
+ var oldInnerBottom = element.down().getStyle('bottom');
+ return new Effect.Scale(element, window.opera ? 0 : 1,
Object.extend({ scaleContent: false,
scaleX: false,
scaleMode: 'box',
@@ -742,32 +748,32 @@ Effect.SlideUp = function(element) {
restoreAfterFinish: true,
beforeStartInternal: function(effect) {
effect.element.makePositioned();
- effect.element.firstChild.makePositioned();
+ effect.element.down().makePositioned();
if(window.opera) effect.element.setStyle({top: ''});
- effect.element.makeClipping();
- effect.element.show(); },
+ effect.element.makeClipping().show();
+ },
afterUpdateInternal: function(effect) {
- effect.element.firstChild.setStyle({bottom:
- (effect.dims[0] - effect.element.clientHeight) + 'px' }); },
+ effect.element.down().setStyle({bottom:
+ (effect.dims[0] - effect.element.clientHeight) + 'px' });
+ },
afterFinishInternal: function(effect) {
- effect.element.hide();
- effect.element.undoClipping();
- effect.element.firstChild.undoPositioned();
- effect.element.undoPositioned();
- effect.element.setStyle({bottom: oldInnerBottom}); }
+ effect.element.hide().undoClipping().undoPositioned().setStyle({bottom: oldInnerBottom});
+ effect.element.down().undoPositioned();
+ }
}, arguments[1] || {})
);
}
// Bug in opera makes the TD containing this element expand for a instance after finish
Effect.Squish = function(element) {
- return new Effect.Scale(element, window.opera ? 1 : 0,
- { restoreAfterFinish: true,
- beforeSetup: function(effect) {
- effect.element.makeClipping(effect.element); },
- afterFinishInternal: function(effect) {
- effect.element.hide(effect.element);
- effect.element.undoClipping(effect.element); }
+ return new Effect.Scale(element, window.opera ? 1 : 0, {
+ restoreAfterFinish: true,
+ beforeSetup: function(effect) {
+ effect.element.makeClipping();
+ },
+ afterFinishInternal: function(effect) {
+ effect.element.hide().undoClipping();
+ }
});
}
@@ -823,9 +829,7 @@ Effect.Grow = function(element) {
y: initialMoveY,
duration: 0.01,
beforeSetup: function(effect) {
- effect.element.hide();
- effect.element.makeClipping();
- effect.element.makePositioned();
+ effect.element.hide().makeClipping().makePositioned();
},
afterFinishInternal: function(effect) {
new Effect.Parallel(
@@ -836,13 +840,10 @@ Effect.Grow = function(element) {
sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
], Object.extend({
beforeSetup: function(effect) {
- effect.effects[0].element.setStyle({height: '0px'});
- effect.effects[0].element.show();
+ effect.effects[0].element.setStyle({height: '0px'}).show();
},
afterFinishInternal: function(effect) {
- effect.effects[0].element.undoClipping();
- effect.effects[0].element.undoPositioned();
- effect.effects[0].element.setStyle(oldStyle);
+ effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
}
}, options)
)
@@ -896,13 +897,10 @@ Effect.Shrink = function(element) {
new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
], Object.extend({
beforeStartInternal: function(effect) {
- effect.effects[0].element.makePositioned();
- effect.effects[0].element.makeClipping(); },
+ effect.effects[0].element.makePositioned().makeClipping();
+ },
afterFinishInternal: function(effect) {
- effect.effects[0].element.hide();
- effect.effects[0].element.undoClipping();
- effect.effects[0].element.undoPositioned();
- effect.effects[0].element.setStyle(oldStyle); }
+ effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
}, options)
);
}
@@ -912,10 +910,10 @@ Effect.Pulsate = function(element) {
var options = arguments[1] || {};
var oldOpacity = element.getInlineOpacity();
var transition = options.transition || Effect.Transitions.sinoidal;
- var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos)) };
+ var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
reverser.bind(transition);
return new Effect.Opacity(element,
- Object.extend(Object.extend({ duration: 3.0, from: 0,
+ Object.extend(Object.extend({ duration: 2.0, from: 0,
afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
}, options), {transition: reverser}));
}
@@ -927,7 +925,7 @@ Effect.Fold = function(element) {
left: element.style.left,
width: element.style.width,
height: element.style.height };
- Element.makeClipping(element);
+ element.makeClipping();
return new Effect.Scale(element, 5, Object.extend({
scaleContent: false,
scaleX: false,
@@ -936,15 +934,147 @@ Effect.Fold = function(element) {
scaleContent: false,
scaleY: false,
afterFinishInternal: function(effect) {
- effect.element.hide();
- effect.element.undoClipping();
- effect.element.setStyle(oldStyle);
+ effect.element.hide().undoClipping().setStyle(oldStyle);
} });
}}, arguments[1] || {}));
};
+Effect.Morph = Class.create();
+Object.extend(Object.extend(Effect.Morph.prototype, Effect.Base.prototype), {
+ initialize: function(element) {
+ this.element = $(element);
+ if(!this.element) throw(Effect._elementDoesNotExistError);
+ var options = Object.extend({
+ style: ''
+ }, arguments[1] || {});
+ this.start(options);
+ },
+ setup: function(){
+ function parseColor(color){
+ if(!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
+ color = color.parseColor();
+ return $R(0,2).map(function(i){
+ return parseInt( color.slice(i*2+1,i*2+3), 16 )
+ });
+ }
+ this.transforms = this.options.style.parseStyle().map(function(property){
+ var originalValue = this.element.getStyle(property[0]);
+ return $H({
+ style: property[0],
+ originalValue: property[1].unit=='color' ?
+ parseColor(originalValue) : parseFloat(originalValue || 0),
+ targetValue: property[1].unit=='color' ?
+ parseColor(property[1].value) : property[1].value,
+ unit: property[1].unit
+ });
+ }.bind(this)).reject(function(transform){
+ return (
+ (transform.originalValue == transform.targetValue) ||
+ (
+ transform.unit != 'color' &&
+ (isNaN(transform.originalValue) || isNaN(transform.targetValue))
+ )
+ )
+ });
+ },
+ update: function(position) {
+ var style = $H(), value = null;
+ this.transforms.each(function(transform){
+ value = transform.unit=='color' ?
+ $R(0,2).inject('#',function(m,v,i){
+ return m+(Math.round(transform.originalValue[i]+
+ (transform.targetValue[i] - transform.originalValue[i])*position)).toColorPart() }) :
+ transform.originalValue + Math.round(
+ ((transform.targetValue - transform.originalValue) * position) * 1000)/1000 + transform.unit;
+ style[transform.style] = value;
+ });
+ this.element.setStyle(style);
+ }
+});
+
+Effect.Transform = Class.create();
+Object.extend(Effect.Transform.prototype, {
+ initialize: function(tracks){
+ this.tracks = [];
+ this.options = arguments[1] || {};
+ this.addTracks(tracks);
+ },
+ addTracks: function(tracks){
+ tracks.each(function(track){
+ var data = $H(track).values().first();
+ this.tracks.push($H({
+ ids: $H(track).keys().first(),
+ effect: Effect.Morph,
+ options: { style: data }
+ }));
+ }.bind(this));
+ return this;
+ },
+ play: function(){
+ return new Effect.Parallel(
+ this.tracks.map(function(track){
+ var elements = [$(track.ids) || $$(track.ids)].flatten();
+ return elements.map(function(e){ return new track.effect(e, Object.extend({ sync:true }, track.options)) });
+ }).flatten(),
+ this.options
+ );
+ }
+});
+
+Element.CSS_PROPERTIES = ['azimuth', 'backgroundAttachment', 'backgroundColor', 'backgroundImage',
+ 'backgroundPosition', 'backgroundRepeat', 'borderBottomColor', 'borderBottomStyle',
+ 'borderBottomWidth', 'borderCollapse', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth',
+ 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderSpacing', 'borderTopColor',
+ 'borderTopStyle', 'borderTopWidth', 'bottom', 'captionSide', 'clear', 'clip', 'color', 'content',
+ 'counterIncrement', 'counterReset', 'cssFloat', 'cueAfter', 'cueBefore', 'cursor', 'direction',
+ 'display', 'elevation', 'emptyCells', 'fontFamily', 'fontSize', 'fontSizeAdjust', 'fontStretch',
+ 'fontStyle', 'fontVariant', 'fontWeight', 'height', 'left', 'letterSpacing', 'lineHeight',
+ 'listStyleImage', 'listStylePosition', 'listStyleType', 'marginBottom', 'marginLeft', 'marginRight',
+ 'marginTop', 'markerOffset', 'marks', 'maxHeight', 'maxWidth', 'minHeight', 'minWidth', 'opacity',
+ 'orphans', 'outlineColor', 'outlineOffset', 'outlineStyle', 'outlineWidth', 'overflowX', 'overflowY',
+ 'paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop', 'page', 'pageBreakAfter', 'pageBreakBefore',
+ 'pageBreakInside', 'pauseAfter', 'pauseBefore', 'pitch', 'pitchRange', 'position', 'quotes',
+ 'richness', 'right', 'size', 'speakHeader', 'speakNumeral', 'speakPunctuation', 'speechRate', 'stress',
+ 'tableLayout', 'textAlign', 'textDecoration', 'textIndent', 'textShadow', 'textTransform', 'top',
+ 'unicodeBidi', 'verticalAlign', 'visibility', 'voiceFamily', 'volume', 'whiteSpace', 'widows',
+ 'width', 'wordSpacing', 'zIndex'];
+
+Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
+
+String.prototype.parseStyle = function(){
+ var element = Element.extend(document.createElement('div'));
+ element.innerHTML = '';
+ var style = element.down().style, styleRules = $H();
+
+ Element.CSS_PROPERTIES.each(function(property){
+ if(style[property]) styleRules[property] = style[property];
+ });
+
+ var result = $H();
+
+ styleRules.each(function(pair){
+ var property = pair[0], value = pair[1], unit = null;
+
+ if(value.parseColor('#zzzzzz') != '#zzzzzz') {
+ value = value.parseColor();
+ unit = 'color';
+ } else if(Element.CSS_LENGTH.test(value))
+ var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/),
+ value = parseFloat(components[1]), unit = (components.length == 3) ? components[2] : null;
+
+ result[property.underscore().dasherize()] = $H({ value:value, unit:unit });
+ }.bind(this));
+
+ return result;
+};
+
+Element.morph = function(element, style) {
+ new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || {}));
+ return element;
+};
+
['setOpacity','getOpacity','getInlineOpacity','forceRerendering','setContentZoom',
- 'collectTextNodes','collectTextNodesIgnoreClass','childrenWithClassName'].each(
+ 'collectTextNodes','collectTextNodesIgnoreClass','morph'].each(
function(f) { Element.Methods[f] = Element[f]; }
);
diff --git a/vendor/rails/actionpack/lib/action_view/helpers/javascripts/prototype.js b/vendor/rails/actionpack/lib/action_view/helpers/javascripts/prototype.js
index 0caf9cd7..50582217 100644
--- a/vendor/rails/actionpack/lib/action_view/helpers/javascripts/prototype.js
+++ b/vendor/rails/actionpack/lib/action_view/helpers/javascripts/prototype.js
@@ -1,5 +1,5 @@
-/* Prototype JavaScript framework, version 1.5.0_rc0
- * (c) 2005 Sam Stephenson
+/* Prototype JavaScript framework, version 1.5.0
+ * (c) 2005-2007 Sam Stephenson
*
* Prototype is freely distributable under the terms of an MIT-style license.
* For details, see the Prototype web site: http://prototype.conio.net/
@@ -7,11 +7,14 @@
/*--------------------------------------------------------------------------*/
var Prototype = {
- Version: '1.5.0_rc0',
- ScriptFragment: '(?:)((\n|\r|.)*?)(?:<\/script>)',
+ Version: '1.5.0',
+ BrowserFeatures: {
+ XPath: !!document.evaluate
+ },
+ ScriptFragment: '(?:)((\n|\r|.)*?)(?:<\/script>)',
emptyFunction: function() {},
- K: function(x) {return x}
+ K: function(x) { return x }
}
var Class = {
@@ -31,16 +34,36 @@ Object.extend = function(destination, source) {
return destination;
}
-Object.inspect = function(object) {
- try {
- if (object == undefined) return 'undefined';
- if (object == null) return 'null';
- return object.inspect ? object.inspect() : object.toString();
- } catch (e) {
- if (e instanceof RangeError) return '...';
- throw e;
+Object.extend(Object, {
+ inspect: function(object) {
+ try {
+ if (object === undefined) return 'undefined';
+ if (object === null) return 'null';
+ return object.inspect ? object.inspect() : object.toString();
+ } catch (e) {
+ if (e instanceof RangeError) return '...';
+ throw e;
+ }
+ },
+
+ keys: function(object) {
+ var keys = [];
+ for (var property in object)
+ keys.push(property);
+ return keys;
+ },
+
+ values: function(object) {
+ var values = [];
+ for (var property in object)
+ values.push(object[property]);
+ return values;
+ },
+
+ clone: function(object) {
+ return Object.extend({}, object);
}
-}
+});
Function.prototype.bind = function() {
var __method = this, args = $A(arguments), object = args.shift();
@@ -50,9 +73,9 @@ Function.prototype.bind = function() {
}
Function.prototype.bindAsEventListener = function(object) {
- var __method = this;
+ var __method = this, args = $A(arguments), object = args.shift();
return function(event) {
- return __method.call(object, event || window.event);
+ return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
}
}
@@ -77,7 +100,7 @@ var Try = {
these: function() {
var returnValue;
- for (var i = 0; i < arguments.length; i++) {
+ for (var i = 0, length = arguments.length; i < length; i++) {
var lambda = arguments[i];
try {
returnValue = lambda();
@@ -102,20 +125,30 @@ PeriodicalExecuter.prototype = {
},
registerCallback: function() {
- setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
+ this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
+ },
+
+ stop: function() {
+ if (!this.timer) return;
+ clearInterval(this.timer);
+ this.timer = null;
},
onTimerEvent: function() {
if (!this.currentlyExecuting) {
try {
this.currentlyExecuting = true;
- this.callback();
+ this.callback(this);
} finally {
this.currentlyExecuting = false;
}
}
}
}
+String.interpret = function(value){
+ return value == null ? '' : String(value);
+}
+
Object.extend(String.prototype, {
gsub: function(pattern, replacement) {
var result = '', source = this, match;
@@ -124,7 +157,7 @@ Object.extend(String.prototype, {
while (source.length > 0) {
if (match = source.match(pattern)) {
result += source.slice(0, match.index);
- result += (replacement(match) || '').toString();
+ result += String.interpret(replacement(match));
source = source.slice(match.index + match[0].length);
} else {
result += source, source = '';
@@ -189,15 +222,28 @@ Object.extend(String.prototype, {
unescapeHTML: function() {
var div = document.createElement('div');
div.innerHTML = this.stripTags();
- return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
+ return div.childNodes[0] ? (div.childNodes.length > 1 ?
+ $A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) :
+ div.childNodes[0].nodeValue) : '';
},
- toQueryParams: function() {
- var pairs = this.match(/^\??(.*)$/)[1].split('&');
- return pairs.inject({}, function(params, pairString) {
- var pair = pairString.split('=');
- params[pair[0]] = pair[1];
- return params;
+ toQueryParams: function(separator) {
+ var match = this.strip().match(/([^?#]*)(#.*)?$/);
+ if (!match) return {};
+
+ return match[1].split(separator || '&').inject({}, function(hash, pair) {
+ if ((pair = pair.split('='))[0]) {
+ var name = decodeURIComponent(pair[0]);
+ var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;
+
+ if (hash[name] !== undefined) {
+ if (hash[name].constructor != Array)
+ hash[name] = [hash[name]];
+ if (value) hash[name].push(value);
+ }
+ else hash[name] = value;
+ }
+ return hash;
});
},
@@ -205,24 +251,43 @@ Object.extend(String.prototype, {
return this.split('');
},
- camelize: function() {
- var oStringList = this.split('-');
- if (oStringList.length == 1) return oStringList[0];
-
- var camelizedString = this.indexOf('-') == 0
- ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
- : oStringList[0];
-
- for (var i = 1, len = oStringList.length; i < len; i++) {
- var s = oStringList[i];
- camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
- }
-
- return camelizedString;
+ succ: function() {
+ return this.slice(0, this.length - 1) +
+ String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
},
- inspect: function() {
- return "'" + this.replace(/\\/g, '\\\\').replace(/'/g, '\\\'') + "'";
+ camelize: function() {
+ var parts = this.split('-'), len = parts.length;
+ if (len == 1) return parts[0];
+
+ var camelized = this.charAt(0) == '-'
+ ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
+ : parts[0];
+
+ for (var i = 1; i < len; i++)
+ camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
+
+ return camelized;
+ },
+
+ capitalize: function(){
+ return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
+ },
+
+ underscore: function() {
+ return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
+ },
+
+ dasherize: function() {
+ return this.gsub(/_/,'-');
+ },
+
+ inspect: function(useDoubleQuotes) {
+ var escapedString = this.replace(/\\/g, '\\\\');
+ if (useDoubleQuotes)
+ return '"' + escapedString.replace(/"/g, '\\"') + '"';
+ else
+ return "'" + escapedString.replace(/'/g, '\\\'') + "'";
}
});
@@ -246,7 +311,7 @@ Template.prototype = {
return this.template.gsub(this.pattern, function(match) {
var before = match[1];
if (before == '\\') return match[2];
- return before + (object[match[3]] || '').toString();
+ return before + String.interpret(object[match[3]]);
});
}
}
@@ -268,6 +333,14 @@ var Enumerable = {
} catch (e) {
if (e != $break) throw e;
}
+ return this;
+ },
+
+ eachSlice: function(number, iterator) {
+ var index = -number, slices = [], array = this.toArray();
+ while ((index += number) < array.length)
+ slices.push(array.slice(index, index+number));
+ return slices.map(iterator);
},
all: function(iterator) {
@@ -280,7 +353,7 @@ var Enumerable = {
},
any: function(iterator) {
- var result = true;
+ var result = false;
this.each(function(value, index) {
if (result = !!(iterator || Prototype.K)(value, index))
throw $break;
@@ -291,12 +364,12 @@ var Enumerable = {
collect: function(iterator) {
var results = [];
this.each(function(value, index) {
- results.push(iterator(value, index));
+ results.push((iterator || Prototype.K)(value, index));
});
return results;
},
- detect: function (iterator) {
+ detect: function(iterator) {
var result;
this.each(function(value, index) {
if (iterator(value, index)) {
@@ -337,6 +410,14 @@ var Enumerable = {
return found;
},
+ inGroupsOf: function(number, fillWith) {
+ fillWith = fillWith === undefined ? null : fillWith;
+ return this.eachSlice(number, function(slice) {
+ while(slice.length < number) slice.push(fillWith);
+ return slice;
+ });
+ },
+
inject: function(memo, iterator) {
this.each(function(value, index) {
memo = iterator(memo, value, index);
@@ -346,7 +427,7 @@ var Enumerable = {
invoke: function(method) {
var args = $A(arguments).slice(1);
- return this.collect(function(value) {
+ return this.map(function(value) {
return value[method].apply(value, args);
});
},
@@ -398,7 +479,7 @@ var Enumerable = {
},
sortBy: function(iterator) {
- return this.collect(function(value, index) {
+ return this.map(function(value, index) {
return {value: value, criteria: iterator(value, index)};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
@@ -407,7 +488,7 @@ var Enumerable = {
},
toArray: function() {
- return this.collect(Prototype.K);
+ return this.map();
},
zip: function() {
@@ -421,6 +502,10 @@ var Enumerable = {
});
},
+ size: function() {
+ return this.toArray().length;
+ },
+
inspect: function() {
return '#';
}
@@ -439,7 +524,7 @@ var $A = Array.from = function(iterable) {
return iterable.toArray();
} else {
var results = [];
- for (var i = 0; i < iterable.length; i++)
+ for (var i = 0, length = iterable.length; i < length; i++)
results.push(iterable[i]);
return results;
}
@@ -452,7 +537,7 @@ if (!Array.prototype._reverse)
Object.extend(Array.prototype, {
_each: function(iterator) {
- for (var i = 0; i < this.length; i++)
+ for (var i = 0, length = this.length; i < length; i++)
iterator(this[i]);
},
@@ -471,7 +556,7 @@ Object.extend(Array.prototype, {
compact: function() {
return this.select(function(value) {
- return value != undefined || value != null;
+ return value != null;
});
},
@@ -490,7 +575,7 @@ Object.extend(Array.prototype, {
},
indexOf: function(object) {
- for (var i = 0; i < this.length; i++)
+ for (var i = 0, length = this.length; i < length; i++)
if (this[i] == object) return i;
return -1;
},
@@ -499,15 +584,88 @@ Object.extend(Array.prototype, {
return (inline !== false ? this : this.toArray())._reverse();
},
+ reduce: function() {
+ return this.length > 1 ? this : this[0];
+ },
+
+ uniq: function() {
+ return this.inject([], function(array, value) {
+ return array.include(value) ? array : array.concat([value]);
+ });
+ },
+
+ clone: function() {
+ return [].concat(this);
+ },
+
+ size: function() {
+ return this.length;
+ },
+
inspect: function() {
return '[' + this.map(Object.inspect).join(', ') + ']';
}
});
-var Hash = {
+
+Array.prototype.toArray = Array.prototype.clone;
+
+function $w(string){
+ string = string.strip();
+ return string ? string.split(/\s+/) : [];
+}
+
+if(window.opera){
+ Array.prototype.concat = function(){
+ var array = [];
+ for(var i = 0, length = this.length; i < length; i++) array.push(this[i]);
+ for(var i = 0, length = arguments.length; i < length; i++) {
+ if(arguments[i].constructor == Array) {
+ for(var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
+ array.push(arguments[i][j]);
+ } else {
+ array.push(arguments[i]);
+ }
+ }
+ return array;
+ }
+}
+var Hash = function(obj) {
+ Object.extend(this, obj || {});
+};
+
+Object.extend(Hash, {
+ toQueryString: function(obj) {
+ var parts = [];
+
+ this.prototype._each.call(obj, function(pair) {
+ if (!pair.key) return;
+
+ if (pair.value && pair.value.constructor == Array) {
+ var values = pair.value.compact();
+ if (values.length < 2) pair.value = values.reduce();
+ else {
+ key = encodeURIComponent(pair.key);
+ values.each(function(value) {
+ value = value != undefined ? encodeURIComponent(value) : '';
+ parts.push(key + '=' + encodeURIComponent(value));
+ });
+ return;
+ }
+ }
+ if (pair.value == undefined) pair[1] = '';
+ parts.push(pair.map(encodeURIComponent).join('='));
+ });
+
+ return parts.join('&');
+ }
+});
+
+Object.extend(Hash.prototype, Enumerable);
+Object.extend(Hash.prototype, {
_each: function(iterator) {
for (var key in this) {
var value = this[key];
- if (typeof value == 'function') continue;
+ if (value && value == Hash.prototype[key]) continue;
var pair = [key, value];
pair.key = key;
@@ -525,16 +683,30 @@ var Hash = {
},
merge: function(hash) {
- return $H(hash).inject($H(this), function(mergedHash, pair) {
+ return $H(hash).inject(this, function(mergedHash, pair) {
mergedHash[pair.key] = pair.value;
return mergedHash;
});
},
+ remove: function() {
+ var result;
+ for(var i = 0, length = arguments.length; i < length; i++) {
+ var value = this[arguments[i]];
+ if (value !== undefined){
+ if (result === undefined) result = value;
+ else {
+ if (result.constructor != Array) result = [result];
+ result.push(value)
+ }
+ }
+ delete this[arguments[i]];
+ }
+ return result;
+ },
+
toQueryString: function() {
- return this.map(function(pair) {
- return pair.map(encodeURIComponent).join('=');
- }).join('&');
+ return Hash.toQueryString(this);
},
inspect: function() {
@@ -542,14 +714,12 @@ var Hash = {
return pair.map(Object.inspect).join(': ');
}).join(', ') + '}>';
}
-}
+});
function $H(object) {
- var hash = Object.extend({}, object || {});
- Object.extend(hash, Enumerable);
- Object.extend(hash, Hash);
- return hash;
-}
+ if (object && object.constructor == Hash) return object;
+ return new Hash(object);
+};
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
@@ -561,10 +731,10 @@ Object.extend(ObjectRange.prototype, {
_each: function(iterator) {
var value = this.start;
- do {
+ while (this.include(value)) {
iterator(value);
value = value.succ();
- } while (this.include(value));
+ }
},
include: function(value) {
@@ -599,18 +769,18 @@ Ajax.Responders = {
this.responders._each(iterator);
},
- register: function(responderToAdd) {
- if (!this.include(responderToAdd))
- this.responders.push(responderToAdd);
+ register: function(responder) {
+ if (!this.include(responder))
+ this.responders.push(responder);
},
- unregister: function(responderToRemove) {
- this.responders = this.responders.without(responderToRemove);
+ unregister: function(responder) {
+ this.responders = this.responders.without(responder);
},
dispatch: function(callback, request, transport, json) {
this.each(function(responder) {
- if (responder[callback] && typeof responder[callback] == 'function') {
+ if (typeof responder[callback] == 'function') {
try {
responder[callback].apply(responder, [request, transport, json]);
} catch (e) {}
@@ -625,7 +795,6 @@ Ajax.Responders.register({
onCreate: function() {
Ajax.activeRequestCount++;
},
-
onComplete: function() {
Ajax.activeRequestCount--;
}
@@ -638,19 +807,14 @@ Ajax.Base.prototype = {
method: 'post',
asynchronous: true,
contentType: 'application/x-www-form-urlencoded',
+ encoding: 'UTF-8',
parameters: ''
}
Object.extend(this.options, options || {});
- },
- responseIsSuccess: function() {
- return this.transport.status == undefined
- || this.transport.status == 0
- || (this.transport.status >= 200 && this.transport.status < 300);
- },
-
- responseIsFailure: function() {
- return !this.responseIsSuccess();
+ this.options.method = this.options.method.toLowerCase();
+ if (typeof this.options.parameters == 'string')
+ this.options.parameters = this.options.parameters.toQueryParams();
}
}
@@ -659,6 +823,8 @@ Ajax.Request.Events =
['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
+ _complete: false,
+
initialize: function(url, options) {
this.transport = Ajax.getTransport();
this.setOptions(options);
@@ -666,74 +832,138 @@ Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
},
request: function(url) {
- var parameters = this.options.parameters || '';
- if (parameters.length > 0) parameters += '&_=';
+ this.url = url;
+ this.method = this.options.method;
+ var params = this.options.parameters;
+
+ if (!['get', 'post'].include(this.method)) {
+ // simulate other verbs over post
+ params['_method'] = this.method;
+ this.method = 'post';
+ }
+
+ params = Hash.toQueryString(params);
+ if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_='
+
+ // when GET, append parameters to URL
+ if (this.method == 'get' && params)
+ this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params;
try {
- this.url = url;
- if (this.options.method == 'get' && parameters.length > 0)
- this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;
-
Ajax.Responders.dispatch('onCreate', this, this.transport);
- this.transport.open(this.options.method, this.url,
+ this.transport.open(this.method.toUpperCase(), this.url,
this.options.asynchronous);
- if (this.options.asynchronous) {
- this.transport.onreadystatechange = this.onStateChange.bind(this);
- setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10);
- }
+ if (this.options.asynchronous)
+ setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);
+ this.transport.onreadystatechange = this.onStateChange.bind(this);
this.setRequestHeaders();
- var body = this.options.postBody ? this.options.postBody : parameters;
- this.transport.send(this.options.method == 'post' ? body : null);
+ var body = this.method == 'post' ? (this.options.postBody || params) : null;
- } catch (e) {
+ this.transport.send(body);
+
+ /* Force Firefox to handle ready state 4 for synchronous requests */
+ if (!this.options.asynchronous && this.transport.overrideMimeType)
+ this.onStateChange();
+
+ }
+ catch (e) {
this.dispatchException(e);
}
},
- setRequestHeaders: function() {
- var requestHeaders =
- ['X-Requested-With', 'XMLHttpRequest',
- 'X-Prototype-Version', Prototype.Version,
- 'Accept', 'text/javascript, text/html, application/xml, text/xml, */*'];
-
- if (this.options.method == 'post') {
- requestHeaders.push('Content-type', this.options.contentType);
-
- /* Force "Connection: close" for Mozilla browsers to work around
- * a bug where XMLHttpReqeuest sends an incorrect Content-length
- * header. See Mozilla Bugzilla #246651.
- */
- if (this.transport.overrideMimeType)
- requestHeaders.push('Connection', 'close');
- }
-
- if (this.options.requestHeaders)
- requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);
-
- for (var i = 0; i < requestHeaders.length; i += 2)
- this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
- },
-
onStateChange: function() {
var readyState = this.transport.readyState;
- if (readyState != 1)
+ if (readyState > 1 && !((readyState == 4) && this._complete))
this.respondToReadyState(this.transport.readyState);
},
- header: function(name) {
+ setRequestHeaders: function() {
+ var headers = {
+ 'X-Requested-With': 'XMLHttpRequest',
+ 'X-Prototype-Version': Prototype.Version,
+ 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
+ };
+
+ if (this.method == 'post') {
+ headers['Content-type'] = this.options.contentType +
+ (this.options.encoding ? '; charset=' + this.options.encoding : '');
+
+ /* Force "Connection: close" for older Mozilla browsers to work
+ * around a bug where XMLHttpRequest sends an incorrect
+ * Content-length header. See Mozilla Bugzilla #246651.
+ */
+ if (this.transport.overrideMimeType &&
+ (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
+ headers['Connection'] = 'close';
+ }
+
+ // user-defined headers
+ if (typeof this.options.requestHeaders == 'object') {
+ var extras = this.options.requestHeaders;
+
+ if (typeof extras.push == 'function')
+ for (var i = 0, length = extras.length; i < length; i += 2)
+ headers[extras[i]] = extras[i+1];
+ else
+ $H(extras).each(function(pair) { headers[pair.key] = pair.value });
+ }
+
+ for (var name in headers)
+ this.transport.setRequestHeader(name, headers[name]);
+ },
+
+ success: function() {
+ return !this.transport.status
+ || (this.transport.status >= 200 && this.transport.status < 300);
+ },
+
+ respondToReadyState: function(readyState) {
+ var state = Ajax.Request.Events[readyState];
+ var transport = this.transport, json = this.evalJSON();
+
+ if (state == 'Complete') {
+ try {
+ this._complete = true;
+ (this.options['on' + this.transport.status]
+ || this.options['on' + (this.success() ? 'Success' : 'Failure')]
+ || Prototype.emptyFunction)(transport, json);
+ } catch (e) {
+ this.dispatchException(e);
+ }
+
+ if ((this.getHeader('Content-type') || 'text/javascript').strip().
+ match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
+ this.evalResponse();
+ }
+
+ try {
+ (this.options['on' + state] || Prototype.emptyFunction)(transport, json);
+ Ajax.Responders.dispatch('on' + state, this, transport, json);
+ } catch (e) {
+ this.dispatchException(e);
+ }
+
+ if (state == 'Complete') {
+ // avoid memory leak in MSIE: clean up
+ this.transport.onreadystatechange = Prototype.emptyFunction;
+ }
+ },
+
+ getHeader: function(name) {
try {
return this.transport.getResponseHeader(name);
- } catch (e) {}
+ } catch (e) { return null }
},
evalJSON: function() {
try {
- return eval('(' + this.header('X-JSON') + ')');
- } catch (e) {}
+ var json = this.getHeader('X-JSON');
+ return json ? eval('(' + json + ')') : null;
+ } catch (e) { return null }
},
evalResponse: function() {
@@ -744,35 +974,6 @@ Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
}
},
- respondToReadyState: function(readyState) {
- var event = Ajax.Request.Events[readyState];
- var transport = this.transport, json = this.evalJSON();
-
- if (event == 'Complete') {
- try {
- (this.options['on' + this.transport.status]
- || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
- || Prototype.emptyFunction)(transport, json);
- } catch (e) {
- this.dispatchException(e);
- }
-
- if ((this.header('Content-type') || '').match(/^text\/javascript/i))
- this.evalResponse();
- }
-
- try {
- (this.options['on' + event] || Prototype.emptyFunction)(transport, json);
- Ajax.Responders.dispatch('on' + event, this, transport, json);
- } catch (e) {
- this.dispatchException(e);
- }
-
- /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
- if (event == 'Complete')
- this.transport.onreadystatechange = Prototype.emptyFunction;
- },
-
dispatchException: function(exception) {
(this.options.onException || Prototype.emptyFunction)(this, exception);
Ajax.Responders.dispatch('onException', this, exception);
@@ -783,41 +984,37 @@ Ajax.Updater = Class.create();
Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
initialize: function(container, url, options) {
- this.containers = {
- success: container.success ? $(container.success) : $(container),
- failure: container.failure ? $(container.failure) :
- (container.success ? null : $(container))
+ this.container = {
+ success: (container.success || container),
+ failure: (container.failure || (container.success ? null : container))
}
this.transport = Ajax.getTransport();
this.setOptions(options);
var onComplete = this.options.onComplete || Prototype.emptyFunction;
- this.options.onComplete = (function(transport, object) {
+ this.options.onComplete = (function(transport, param) {
this.updateContent();
- onComplete(transport, object);
+ onComplete(transport, param);
}).bind(this);
this.request(url);
},
updateContent: function() {
- var receiver = this.responseIsSuccess() ?
- this.containers.success : this.containers.failure;
+ var receiver = this.container[this.success() ? 'success' : 'failure'];
var response = this.transport.responseText;
- if (!this.options.evalScripts)
- response = response.stripScripts();
+ if (!this.options.evalScripts) response = response.stripScripts();
- if (receiver) {
- if (this.options.insertion) {
+ if (receiver = $(receiver)) {
+ if (this.options.insertion)
new this.options.insertion(receiver, response);
- } else {
- Element.update(receiver, response);
- }
+ else
+ receiver.update(response);
}
- if (this.responseIsSuccess()) {
+ if (this.success()) {
if (this.onComplete)
setTimeout(this.onComplete.bind(this), 10);
}
@@ -846,7 +1043,7 @@ Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
},
stop: function() {
- this.updater.onComplete = undefined;
+ this.updater.options.onComplete = undefined;
clearTimeout(this.timer);
(this.onComplete || Prototype.emptyFunction).apply(this, arguments);
},
@@ -866,25 +1063,43 @@ Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
this.updater = new Ajax.Updater(this.container, this.url, this.options);
}
});
-function $() {
- var results = [], element;
- for (var i = 0; i < arguments.length; i++) {
- element = arguments[i];
- if (typeof element == 'string')
- element = document.getElementById(element);
- results.push(Element.extend(element));
+function $(element) {
+ if (arguments.length > 1) {
+ for (var i = 0, elements = [], length = arguments.length; i < length; i++)
+ elements.push($(arguments[i]));
+ return elements;
}
- return results.length < 2 ? results[0] : results;
+ if (typeof element == 'string')
+ element = document.getElementById(element);
+ return Element.extend(element);
+}
+
+if (Prototype.BrowserFeatures.XPath) {
+ document._getElementsByXPath = function(expression, parentElement) {
+ var results = [];
+ var query = document.evaluate(expression, $(parentElement) || document,
+ null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
+ for (var i = 0, length = query.snapshotLength; i < length; i++)
+ results.push(query.snapshotItem(i));
+ return results;
+ };
}
document.getElementsByClassName = function(className, parentElement) {
- var children = ($(parentElement) || document.body).getElementsByTagName('*');
- return $A(children).inject([], function(elements, child) {
- if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
- elements.push(Element.extend(child));
+ if (Prototype.BrowserFeatures.XPath) {
+ var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
+ return document._getElementsByXPath(q, parentElement);
+ } else {
+ var children = ($(parentElement) || document.body).getElementsByTagName('*');
+ var elements = [], child;
+ for (var i = 0, length = children.length; i < length; i++) {
+ child = children[i];
+ if (Element.hasClassName(child, className))
+ elements.push(Element.extend(child));
+ }
return elements;
- });
-}
+ }
+};
/*--------------------------------------------------------------------------*/
@@ -892,21 +1107,28 @@ if (!window.Element)
var Element = new Object();
Element.extend = function(element) {
- if (!element) return;
- if (_nativeExtensions) return element;
+ if (!element || _nativeExtensions || element.nodeType == 3) return element;
if (!element._extended && element.tagName && element != window) {
- var methods = Element.Methods, cache = Element.extend.cache;
- for (property in methods) {
+ var methods = Object.clone(Element.Methods), cache = Element.extend.cache;
+
+ if (element.tagName == 'FORM')
+ Object.extend(methods, Form.Methods);
+ if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName))
+ Object.extend(methods, Form.Element.Methods);
+
+ Object.extend(methods, Element.Methods.Simulated);
+
+ for (var property in methods) {
var value = methods[property];
- if (typeof value == 'function')
+ if (typeof value == 'function' && !(property in element))
element[property] = cache.findOrStore(value);
}
}
element._extended = true;
return element;
-}
+};
Element.extend.cache = {
findOrStore: function(value) {
@@ -914,46 +1136,45 @@ Element.extend.cache = {
return value.apply(null, [this].concat($A(arguments)));
}
}
-}
+};
Element.Methods = {
visible: function(element) {
return $(element).style.display != 'none';
},
- toggle: function() {
- for (var i = 0; i < arguments.length; i++) {
- var element = $(arguments[i]);
- Element[Element.visible(element) ? 'hide' : 'show'](element);
- }
+ toggle: function(element) {
+ element = $(element);
+ Element[Element.visible(element) ? 'hide' : 'show'](element);
+ return element;
},
- hide: function() {
- for (var i = 0; i < arguments.length; i++) {
- var element = $(arguments[i]);
- element.style.display = 'none';
- }
+ hide: function(element) {
+ $(element).style.display = 'none';
+ return element;
},
- show: function() {
- for (var i = 0; i < arguments.length; i++) {
- var element = $(arguments[i]);
- element.style.display = '';
- }
+ show: function(element) {
+ $(element).style.display = '';
+ return element;
},
remove: function(element) {
element = $(element);
element.parentNode.removeChild(element);
+ return element;
},
update: function(element, html) {
+ html = typeof html == 'undefined' ? '' : html.toString();
$(element).innerHTML = html.stripScripts();
setTimeout(function() {html.evalScripts()}, 10);
+ return element;
},
replace: function(element, html) {
element = $(element);
+ html = typeof html == 'undefined' ? '' : html.toString();
if (element.outerHTML) {
element.outerHTML = html.stripScripts();
} else {
@@ -963,11 +1184,106 @@ Element.Methods = {
range.createContextualFragment(html.stripScripts()), element);
}
setTimeout(function() {html.evalScripts()}, 10);
+ return element;
+ },
+
+ inspect: function(element) {
+ element = $(element);
+ var result = '<' + element.tagName.toLowerCase();
+ $H({'id': 'id', 'className': 'class'}).each(function(pair) {
+ var property = pair.first(), attribute = pair.last();
+ var value = (element[property] || '').toString();
+ if (value) result += ' ' + attribute + '=' + value.inspect(true);
+ });
+ return result + '>';
+ },
+
+ recursivelyCollect: function(element, property) {
+ element = $(element);
+ var elements = [];
+ while (element = element[property])
+ if (element.nodeType == 1)
+ elements.push(Element.extend(element));
+ return elements;
+ },
+
+ ancestors: function(element) {
+ return $(element).recursivelyCollect('parentNode');
+ },
+
+ descendants: function(element) {
+ return $A($(element).getElementsByTagName('*'));
+ },
+
+ immediateDescendants: function(element) {
+ if (!(element = $(element).firstChild)) return [];
+ while (element && element.nodeType != 1) element = element.nextSibling;
+ if (element) return [element].concat($(element).nextSiblings());
+ return [];
+ },
+
+ previousSiblings: function(element) {
+ return $(element).recursivelyCollect('previousSibling');
+ },
+
+ nextSiblings: function(element) {
+ return $(element).recursivelyCollect('nextSibling');
+ },
+
+ siblings: function(element) {
+ element = $(element);
+ return element.previousSiblings().reverse().concat(element.nextSiblings());
+ },
+
+ match: function(element, selector) {
+ if (typeof selector == 'string')
+ selector = new Selector(selector);
+ return selector.match($(element));
+ },
+
+ up: function(element, expression, index) {
+ return Selector.findElement($(element).ancestors(), expression, index);
+ },
+
+ down: function(element, expression, index) {
+ return Selector.findElement($(element).descendants(), expression, index);
+ },
+
+ previous: function(element, expression, index) {
+ return Selector.findElement($(element).previousSiblings(), expression, index);
+ },
+
+ next: function(element, expression, index) {
+ return Selector.findElement($(element).nextSiblings(), expression, index);
+ },
+
+ getElementsBySelector: function() {
+ var args = $A(arguments), element = $(args.shift());
+ return Selector.findChildElements(element, args);
+ },
+
+ getElementsByClassName: function(element, className) {
+ return document.getElementsByClassName(className, element);
+ },
+
+ readAttribute: function(element, name) {
+ element = $(element);
+ if (document.all && !window.opera) {
+ var t = Element._attributeTranslations;
+ if (t.values[name]) return t.values[name](element, name);
+ if (t.names[name]) name = t.names[name];
+ var attribute = element.attributes[name];
+ if(attribute) return attribute.nodeValue;
+ }
+ return element.getAttribute(name);
},
getHeight: function(element) {
- element = $(element);
- return element.offsetHeight;
+ return $(element).getDimensions().height;
+ },
+
+ getWidth: function(element) {
+ return $(element).getDimensions().width;
},
classNames: function(element) {
@@ -976,34 +1292,60 @@ Element.Methods = {
hasClassName: function(element, className) {
if (!(element = $(element))) return;
- return Element.classNames(element).include(className);
+ var elementClassName = element.className;
+ if (elementClassName.length == 0) return false;
+ if (elementClassName == className ||
+ elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
+ return true;
+ return false;
},
addClassName: function(element, className) {
if (!(element = $(element))) return;
- return Element.classNames(element).add(className);
+ Element.classNames(element).add(className);
+ return element;
},
removeClassName: function(element, className) {
if (!(element = $(element))) return;
- return Element.classNames(element).remove(className);
+ Element.classNames(element).remove(className);
+ return element;
+ },
+
+ toggleClassName: function(element, className) {
+ if (!(element = $(element))) return;
+ Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className);
+ return element;
+ },
+
+ observe: function() {
+ Event.observe.apply(Event, arguments);
+ return $A(arguments).first();
+ },
+
+ stopObserving: function() {
+ Event.stopObserving.apply(Event, arguments);
+ return $A(arguments).first();
},
// removes whitespace-only text node children
cleanWhitespace: function(element) {
element = $(element);
- for (var i = 0; i < element.childNodes.length; i++) {
- var node = element.childNodes[i];
+ var node = element.firstChild;
+ while (node) {
+ var nextNode = node.nextSibling;
if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
- Element.remove(node);
+ element.removeChild(node);
+ node = nextNode;
}
+ return element;
},
empty: function(element) {
return $(element).innerHTML.match(/^\s*$/);
},
- childOf: function(element, ancestor) {
+ descendantOf: function(element, ancestor) {
element = $(element), ancestor = $(ancestor);
while (element = element.parentNode)
if (element == ancestor) return true;
@@ -1012,38 +1354,69 @@ Element.Methods = {
scrollTo: function(element) {
element = $(element);
- var x = element.x ? element.x : element.offsetLeft,
- y = element.y ? element.y : element.offsetTop;
- window.scrollTo(x, y);
+ var pos = Position.cumulativeOffset(element);
+ window.scrollTo(pos[0], pos[1]);
+ return element;
},
getStyle: function(element, style) {
element = $(element);
- var value = element.style[style.camelize()];
+ if (['float','cssFloat'].include(style))
+ style = (typeof element.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat');
+ style = style.camelize();
+ var value = element.style[style];
if (!value) {
if (document.defaultView && document.defaultView.getComputedStyle) {
var css = document.defaultView.getComputedStyle(element, null);
- value = css ? css.getPropertyValue(style) : null;
+ value = css ? css[style] : null;
} else if (element.currentStyle) {
- value = element.currentStyle[style.camelize()];
+ value = element.currentStyle[style];
}
}
+ if((value == 'auto') && ['width','height'].include(style) && (element.getStyle('display') != 'none'))
+ value = element['offset'+style.capitalize()] + 'px';
+
if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
if (Element.getStyle(element, 'position') == 'static') value = 'auto';
-
+ if(style == 'opacity') {
+ if(value) return parseFloat(value);
+ if(value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
+ if(value[1]) return parseFloat(value[1]) / 100;
+ return 1.0;
+ }
return value == 'auto' ? null : value;
},
setStyle: function(element, style) {
element = $(element);
- for (var name in style)
- element.style[name.camelize()] = style[name];
+ for (var name in style) {
+ var value = style[name];
+ if(name == 'opacity') {
+ if (value == 1) {
+ value = (/Gecko/.test(navigator.userAgent) &&
+ !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0;
+ if(/MSIE/.test(navigator.userAgent) && !window.opera)
+ element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
+ } else if(value == '') {
+ if(/MSIE/.test(navigator.userAgent) && !window.opera)
+ element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
+ } else {
+ if(value < 0.00001) value = 0;
+ if(/MSIE/.test(navigator.userAgent) && !window.opera)
+ element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') +
+ 'alpha(opacity='+value*100+')';
+ }
+ } else if(['float','cssFloat'].include(name)) name = (typeof element.style.styleFloat != 'undefined') ? 'styleFloat' : 'cssFloat';
+ element.style[name.camelize()] = value;
+ }
+ return element;
},
getDimensions: function(element) {
element = $(element);
- if (Element.getStyle(element, 'display') != 'none')
+ var display = $(element).getStyle('display');
+ if (display != 'none' && display != null) // Safari bug
return {width: element.offsetWidth, height: element.offsetHeight};
// All *Width and *Height properties give 0 on elements with display none,
@@ -1051,12 +1424,13 @@ Element.Methods = {
var els = element.style;
var originalVisibility = els.visibility;
var originalPosition = els.position;
+ var originalDisplay = els.display;
els.visibility = 'hidden';
els.position = 'absolute';
- els.display = '';
+ els.display = 'block';
var originalWidth = element.clientWidth;
var originalHeight = element.clientHeight;
- els.display = 'none';
+ els.display = originalDisplay;
els.position = originalPosition;
els.visibility = originalVisibility;
return {width: originalWidth, height: originalHeight};
@@ -1075,6 +1449,7 @@ Element.Methods = {
element.style.left = 0;
}
}
+ return element;
},
undoPositioned: function(element) {
@@ -1087,49 +1462,153 @@ Element.Methods = {
element.style.bottom =
element.style.right = '';
}
+ return element;
},
makeClipping: function(element) {
element = $(element);
- if (element._overflow) return;
- element._overflow = element.style.overflow;
+ if (element._overflow) return element;
+ element._overflow = element.style.overflow || 'auto';
if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
element.style.overflow = 'hidden';
+ return element;
},
undoClipping: function(element) {
element = $(element);
- if (element._overflow) return;
- element.style.overflow = element._overflow;
- element._overflow = undefined;
+ if (!element._overflow) return element;
+ element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
+ element._overflow = null;
+ return element;
}
-}
+};
+
+Object.extend(Element.Methods, {childOf: Element.Methods.descendantOf});
+
+Element._attributeTranslations = {};
+
+Element._attributeTranslations.names = {
+ colspan: "colSpan",
+ rowspan: "rowSpan",
+ valign: "vAlign",
+ datetime: "dateTime",
+ accesskey: "accessKey",
+ tabindex: "tabIndex",
+ enctype: "encType",
+ maxlength: "maxLength",
+ readonly: "readOnly",
+ longdesc: "longDesc"
+};
+
+Element._attributeTranslations.values = {
+ _getAttr: function(element, attribute) {
+ return element.getAttribute(attribute, 2);
+ },
+
+ _flag: function(element, attribute) {
+ return $(element).hasAttribute(attribute) ? attribute : null;
+ },
+
+ style: function(element) {
+ return element.style.cssText.toLowerCase();
+ },
+
+ title: function(element) {
+ var node = element.getAttributeNode('title');
+ return node.specified ? node.nodeValue : null;
+ }
+};
+
+Object.extend(Element._attributeTranslations.values, {
+ href: Element._attributeTranslations.values._getAttr,
+ src: Element._attributeTranslations.values._getAttr,
+ disabled: Element._attributeTranslations.values._flag,
+ checked: Element._attributeTranslations.values._flag,
+ readonly: Element._attributeTranslations.values._flag,
+ multiple: Element._attributeTranslations.values._flag
+});
+
+Element.Methods.Simulated = {
+ hasAttribute: function(element, attribute) {
+ var t = Element._attributeTranslations;
+ attribute = t.names[attribute] || attribute;
+ return $(element).getAttributeNode(attribute).specified;
+ }
+};
+
+// IE is missing .innerHTML support for TABLE-related elements
+if (document.all && !window.opera){
+ Element.Methods.update = function(element, html) {
+ element = $(element);
+ html = typeof html == 'undefined' ? '' : html.toString();
+ var tagName = element.tagName.toUpperCase();
+ if (['THEAD','TBODY','TR','TD'].include(tagName)) {
+ var div = document.createElement('div');
+ switch (tagName) {
+ case 'THEAD':
+ case 'TBODY':
+ div.innerHTML = '
- # <% end %>
- # <%= javascript_tag(replacement_function) %>
- #
- # This method can also be used in combination with remote method call
- # where the result is evaluated afterwards to cause multiple updates on
- # a page. Example:
- #
- # # Calling view
- # <%= form_remote_tag :url => { :action => "buy" },
- # :complete => evaluate_remote_response %>
- # all the inputs here...
- #
- # # Controller action
- # def buy
- # @product = Product.find(1)
- # end
- #
- # # Returning view
- # <%= update_element_function(
- # "cart", :action => :update, :position => :bottom,
- # :content => "
New Product: #{@product.name}
")) %>
- # <% update_element_function("status", :binding => binding) do %>
- # You've bought a new product!
- # <% end %>
- #
- # Notice how the second call doesn't need to be in an ERb output block
- # since it uses a block and passes in the binding to render directly.
- # This trick will however only work in ERb (not Builder or other
- # template forms).
- #
- # See also JavaScriptGenerator and update_page.
- def update_element_function(element_id, options = {}, &block)
- content = escape_javascript(options[:content] || '')
- content = escape_javascript(capture(&block)) if block
-
- javascript_function = case (options[:action] || :update)
- when :update
- if options[:position]
- "new Insertion.#{options[:position].to_s.camelize}('#{element_id}','#{content}')"
- else
- "$('#{element_id}').innerHTML = '#{content}'"
- end
-
- when :empty
- "$('#{element_id}').innerHTML = ''"
-
- when :remove
- "Element.remove('#{element_id}')"
-
- else
- raise ArgumentError, "Invalid action, choose one of :update, :remove, :empty"
- end
-
- javascript_function << ";\n"
- options[:binding] ? concat(javascript_function, options[:binding]) : javascript_function
- end
-
# Returns 'eval(request.responseText)' which is the JavaScript function
# that form_remote_tag can call in :complete to evaluate a multiple
# update return document using update_element_function calls.
@@ -289,7 +224,7 @@ module ActionView
javascript_options = options_for_ajax(options)
update = ''
- if options[:update] and options[:update].is_a?Hash
+ if options[:update] && options[:update].is_a?(Hash)
update = []
update << "success:'#{options[:update][:success]}'" if options[:update][:success]
update << "failure:'#{options[:update][:failure]}'" if options[:update][:failure]
@@ -303,7 +238,7 @@ module ActionView
"new Ajax.Updater(#{update}, "
url_options = options[:url]
- url_options = url_options.merge(:escape => false) if url_options.is_a? Hash
+ url_options = url_options.merge(:escape => false) if url_options.is_a?(Hash)
function << "'#{url_for(url_options)}'"
function << ", #{javascript_options})"
@@ -438,7 +373,7 @@ module ActionView
if ActionView::Base.debug_rjs
source = javascript.dup
javascript.replace "try {\n#{source}\n} catch (e) "
- javascript << "{ alert('RJS error:\\n\\n' + e.toString()); alert('#{source.gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" }}'); throw e }"
+ javascript << "{ alert('RJS error:\\n\\n' + e.toString()); alert('#{source.gsub('\\','\0\0').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" }}'); throw e }"
end
end
end
@@ -453,6 +388,12 @@ module ActionView
JavaScriptElementProxy.new(self, id)
end
+ # Returns an object whose #to_json evaluates to +code+. Use this to pass a literal JavaScript
+ # expression as an argument to another JavaScriptGenerator method.
+ def literal(code)
+ ActiveSupport::JSON::Variable.new(code.to_s)
+ end
+
# Returns a collection reference by finding it through a CSS +pattern+ in the DOM. This collection can then be
# used for further method calls. Examples:
#
@@ -526,7 +467,7 @@ module ActionView
#
# # Replace the DOM element having ID 'person-45' with the
# # 'person' partial for the appropriate object.
- # replace_html 'person-45', :partial => 'person', :object => @person
+ # replace 'person-45', :partial => 'person', :object => @person
#
# This allows the same partial that is used for the +insert_html+ to
# be also used for the input to +replace+ without resorting to
@@ -550,22 +491,22 @@ module ActionView
# Removes the DOM elements with the given +ids+ from the page.
def remove(*ids)
- record "#{javascript_object_for(ids)}.each(Element.remove)"
+ loop_on_multiple_args 'Element.remove', ids
end
# Shows hidden DOM elements with the given +ids+.
def show(*ids)
- call 'Element.show', *ids
+ loop_on_multiple_args 'Element.show', ids
end
# Hides the visible DOM elements with the given +ids+.
def hide(*ids)
- call 'Element.hide', *ids
+ loop_on_multiple_args 'Element.hide', ids
end
# Toggles the visibility of the DOM elements with the given +ids+.
def toggle(*ids)
- call 'Element.toggle', *ids
+ loop_on_multiple_args 'Element.toggle', ids
end
# Displays an alert dialog with the given +message+.
@@ -573,16 +514,18 @@ module ActionView
call 'alert', message
end
- # Redirects the browser to the given +location+, in the same form as
- # +url_for+.
+ # Redirects the browser to the given +location+, in the same form as +url_for+.
def redirect_to(location)
assign 'window.location.href', @context.url_for(location)
end
- # Calls the JavaScript +function+, optionally with the given
- # +arguments+.
- def call(function, *arguments)
- record "#{function}(#{arguments_for_call(arguments)})"
+ # Calls the JavaScript +function+, optionally with the given +arguments+.
+ #
+ # If a block is given, the block will be passed to a new JavaScriptGenerator;
+ # the resulting JavaScript code will then be wrapped inside function() { ... }
+ # and passed as the called function's final argument.
+ def call(function, *arguments, &block)
+ record "#{function}(#{arguments_for_call(arguments, block)})"
end
# Assigns the JavaScript +variable+ the given +value+.
@@ -633,12 +576,18 @@ module ActionView
end
private
+ def loop_on_multiple_args(method, ids)
+ record(ids.size>1 ?
+ "#{javascript_object_for(ids)}.each(#{method})" :
+ "#{method}(#{ids.first.to_json})")
+ end
+
def page
self
end
def record(line)
- returning line = "#{line.to_s.chomp.gsub /\;$/, ''};" do
+ returning line = "#{line.to_s.chomp.gsub(/\;\z/, '')};" do
self << line
end
end
@@ -653,10 +602,16 @@ module ActionView
object.respond_to?(:to_json) ? object.to_json : object.inspect
end
- def arguments_for_call(arguments)
+ def arguments_for_call(arguments, block = nil)
+ arguments << block_to_function(block) if block
arguments.map { |argument| javascript_object_for(argument) }.join ', '
end
+ def block_to_function(block)
+ generator = self.class.new(@context, &block)
+ literal("function() { #{generator.to_s} }")
+ end
+
def method_missing(method, *arguments)
JavaScriptProxy.new(self, method.to_s.camelize)
end
@@ -673,8 +628,11 @@ module ActionView
# Works like update_page but wraps the generated JavaScript in a ')
+ # => <script> do_nasty_stuff() </script>
+ # sanitize('Click here for $100')
+ # => Click here for $100
def sanitize(html)
# only do this if absolutely necessary
if html.index("<")
@@ -192,8 +233,8 @@ module ActionView
else
if node.closing != :close
node.attributes.delete_if { |attr,v| attr =~ VERBOTEN_ATTRS }
- if node.attributes["href"] =~ /^javascript:/i
- node.attributes.delete "href"
+ %w(href src).each do |attr|
+ node.attributes.delete attr if node.attributes[attr] =~ /^javascript:/i
end
end
node.to_s
@@ -209,11 +250,11 @@ module ActionView
html
end
- # Strips all HTML tags from the input, including comments. This uses the html-scanner
- # tokenizer and so it's HTML parsing ability is limited by that of html-scanner.
- #
- # Returns the tag free text.
- def strip_tags(html)
+ # Strips all HTML tags from the +html+, including comments. This uses the
+ # html-scanner tokenizer and so its HTML parsing ability is limited by
+ # that of html-scanner.
+ def strip_tags(html)
+ return html if html.blank?
if html.index("<")
text = ""
tokenizer = HTML::Tokenizer.new(html)
@@ -231,32 +272,33 @@ module ActionView
end
end
- # Returns a Cycle object whose to_s value cycles through items of an
- # array every time it is called. This can be used to alternate classes
- # for table rows:
+ # Creates a Cycle object whose _to_s_ method cycles through elements of an
+ # array every time it is called. This can be used for example, to alternate
+ # classes for table rows:
#
- # <%- for item in @items do -%>
- #
">
- # ... use item ...
+ # <% @items.each do |item| %>
+ #
">
+ #
item
#
- # <%- end -%>
+ # <% end %>
#
- # You can use named cycles to prevent clashes in nested loops. You'll
- # have to reset the inner cycle, manually:
+ # You can use named cycles to allow nesting in loops. Passing a Hash as
+ # the last parameter with a :name key will create a named cycle.
+ # You can manually reset a cycle by calling reset_cycle and passing the
+ # name of the cycle.
#
- # <%- for item in @items do -%>
+ # <% @items.each do |item| %>
#
"row_class")
#
- # <%- for value in item.values do -%>
- # "colors") %>'">
- # item
+ # <% item.values.each do |value| %>
+ # "colors") -%>">
+ # value
#
- # <%- end -%>
- # <%- reset_cycle("colors") -%>
+ # <% end %>
+ # <% reset_cycle("colors") %>
#