diff options
author | TomK32 <tomk32@tomk32.de> | 2008-06-11 19:22:51 +0200 |
---|---|---|
committer | TomK32 <tomk32@tomk32.de> | 2008-06-11 19:22:51 +0200 |
commit | 6a5ac86207765e2c041378b35c05812f9bfe68b9 (patch) | |
tree | 4b341329991f2bd08c01d2f139c4c3721a8fbe25 | |
parent | fa0cca368f74119b561595cc6ca7454f7debdf6b (diff) | |
parent | d4b7cd99e8e7051c9d3ed6722f9627d5d4dea4e9 (diff) | |
download | rails-6a5ac86207765e2c041378b35c05812f9bfe68b9.tar.gz rails-6a5ac86207765e2c041378b35c05812f9bfe68b9.tar.bz2 rails-6a5ac86207765e2c041378b35c05812f9bfe68b9.zip |
Merge branch 'master' of git@github.com:lifo/docrails
249 files changed, 3929 insertions, 1547 deletions
diff --git a/.gitignore b/.gitignore index d19b982f85..8c5dfb64e1 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,10 @@ actionpack/doc actionmailer/doc activesupport/doc railties/doc +activeresource/pkg +activerecord/pkg +actionpack/pkg +actionmailer/pkg +activesupport/pkg +railties/pkg +*.rbc diff --git a/actionmailer/CHANGELOG b/actionmailer/CHANGELOG index b2ce462f0c..bdae0d4d3d 100644 --- a/actionmailer/CHANGELOG +++ b/actionmailer/CHANGELOG @@ -1,4 +1,4 @@ -*2.1.0 RC1 (May 11th, 2008)* +*2.1.0 (May 31st, 2008)* * Fixed that a return-path header would be ignored #7572 [joost] diff --git a/actionmailer/Rakefile b/actionmailer/Rakefile index 22ed396417..c09526cbef 100755 --- a/actionmailer/Rakefile +++ b/actionmailer/Rakefile @@ -55,7 +55,7 @@ spec = Gem::Specification.new do |s| s.rubyforge_project = "actionmailer" s.homepage = "http://www.rubyonrails.org" - s.add_dependency('actionpack', '= 2.0.991' + PKG_BUILD) + s.add_dependency('actionpack', '= 2.1.0' + PKG_BUILD) s.has_rdoc = true s.requirements << 'none' diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index 7ed133d099..e065132107 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -5,12 +5,12 @@ require 'action_mailer/utils' require 'tmail/net' module ActionMailer #:nodoc: - # ActionMailer allows you to send email from your application using a mailer model and views. + # Action Mailer 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. + # To use Action Mailer, you need to create a mailer model. # # $ script/generate mailer Notifier # @@ -35,7 +35,8 @@ module ActionMailer #:nodoc: # * <tt>subject</tt> - The subject of your email. Sets the <tt>Subject:</tt> header. # * <tt>from</tt> - Who the email you are sending is from. Sets the <tt>From:</tt> header. # * <tt>cc</tt> - Takes one or more email addresses. These addresses will receive a carbon copy of your email. Sets the <tt>Cc:</tt> header. - # * <tt>bcc</tt> - Takes one or more email address. These addresses will receive a blind carbon copy of your email. Sets the <tt>Bcc:</tt> header. + # * <tt>bcc</tt> - Takes one or more email addresses. These addresses will receive a blind carbon copy of your email. Sets the <tt>Bcc:</tt> header. + # * <tt>reply_to</tt> - Takes one or more email addresses. These addresses will be listed as the default recipients when replying to your email. Sets the <tt>Reply-To:</tt> header. # * <tt>sent_on</tt> - The date on which the message was sent. If not set, the header wil be set by the delivery agent. # * <tt>content_type</tt> - Specify the content type of the message. Defaults to <tt>text/plain</tt>. # * <tt>headers</tt> - Specify additional headers to be set for the message, e.g. <tt>headers 'X-Mail-Count' => 107370</tt>. @@ -54,7 +55,7 @@ module ActionMailer #:nodoc: # # = Mailer views # - # Like ActionController, each mailer class has a corresponding view directory + # Like Action Controller, 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 <tt>.erb</tt> file with the same name as the method # in your mailer model. For example, in the mailer defined above, the template at @@ -157,7 +158,7 @@ module ActionMailer #:nodoc: # end # end # - # Multipart messages can also be used implicitly because ActionMailer will automatically + # Multipart messages can also be used implicitly because Action Mailer will automatically # detect and use multipart templates, where each template is named after the name of the action, followed # by the content type. Each such detected template will be added as separate part to the message. # @@ -317,6 +318,10 @@ module ActionMailer #:nodoc: # Specify the from address for the message. adv_attr_accessor :from + # Specify the address (if different than the "from" address) to direct + # replies to this message. + adv_attr_accessor :reply_to + # Specify additional headers to be added to the message. adv_attr_accessor :headers @@ -383,8 +388,8 @@ module ActionMailer #:nodoc: # Receives a raw email, parses it into an email object, decodes it, # instantiates a new mailer, and passes the email object to the mailer - # object's #receive method. If you want your mailer to be able to - # process incoming messages, you'll need to implement a #receive + # object's +receive+ method. If you want your mailer to be able to + # process incoming messages, you'll need to implement a +receive+ # method that accepts the email object as a parameter: # # class MyMailer < ActionMailer::Base @@ -490,7 +495,7 @@ module ActionMailer #:nodoc: end # Delivers a TMail::Mail object. By default, it delivers the cached mail - # object (from the #create! method). If no cached mail object exists, and + # object (from the <tt>create!</tt> method). If no cached mail object exists, and # no alternate has been given as the parameter, this will fail. def deliver!(mail = @mail) raise "no mail object available for delivery!" unless mail @@ -576,13 +581,14 @@ module ActionMailer #:nodoc: def create_mail m = TMail::Mail.new - m.subject, = quote_any_if_necessary(charset, subject) - m.to, m.from = quote_any_address_if_necessary(charset, recipients, from) - m.bcc = quote_address_if_necessary(bcc, charset) unless bcc.nil? - m.cc = quote_address_if_necessary(cc, charset) unless cc.nil? - + m.subject, = quote_any_if_necessary(charset, subject) + m.to, m.from = quote_any_address_if_necessary(charset, recipients, from) + m.bcc = quote_address_if_necessary(bcc, charset) unless bcc.nil? + m.cc = quote_address_if_necessary(cc, charset) unless cc.nil? + m.reply_to = quote_address_if_necessary(reply_to, charset) unless reply_to.nil? m.mime_version = mime_version unless mime_version.nil? - m.date = sent_on.to_time rescue sent_on if sent_on + m.date = sent_on.to_time rescue sent_on if sent_on + headers.each { |k, v| m[k] = v } real_content_type, ctype_attrs = parse_content_type diff --git a/actionmailer/lib/action_mailer/helpers.rb b/actionmailer/lib/action_mailer/helpers.rb index 3e5ed9e9d7..9c5fcc6afb 100644 --- a/actionmailer/lib/action_mailer/helpers.rb +++ b/actionmailer/lib/action_mailer/helpers.rb @@ -34,7 +34,7 @@ module ActionMailer # helper FooHelper # includes FooHelper in the template class. # helper { def foo() "#{bar} is the very best" end } - # evaluates the block in the template class, adding method #foo. + # evaluates the block in the template class, adding method +foo+. # helper(:three, BlindHelper) { def mice() 'mice' end } # does all three. def helper(*args, &block) diff --git a/actionmailer/lib/action_mailer/part.rb b/actionmailer/lib/action_mailer/part.rb index de1b1689f7..2dabf15f08 100644 --- a/actionmailer/lib/action_mailer/part.rb +++ b/actionmailer/lib/action_mailer/part.rb @@ -5,7 +5,7 @@ require 'action_mailer/utils' module ActionMailer # Represents a subpart of an email message. It shares many similar # attributes of ActionMailer::Base. Although you can create parts manually - # and add them to the #parts list of the mailer, it is easier + # and add them to the +parts+ list of the mailer, it is easier # to use the helper methods in ActionMailer::PartContainer. class Part include ActionMailer::AdvAttrAccessor @@ -13,7 +13,7 @@ module ActionMailer # Represents the body of the part, as a string. This should not be a # Hash (like ActionMailer::Base), but if you want a template to be rendered - # into the body of a subpart you can do it with the mailer's #render method + # into the body of a subpart you can do it with the mailer's +render+ method # and assign the result here. adv_attr_accessor :body diff --git a/actionmailer/lib/action_mailer/quoting.rb b/actionmailer/lib/action_mailer/quoting.rb index b222432787..a2f2c70799 100644 --- a/actionmailer/lib/action_mailer/quoting.rb +++ b/actionmailer/lib/action_mailer/quoting.rb @@ -40,7 +40,7 @@ module ActionMailer # regular email address, or it can be a phrase followed by an address in # brackets. The phrase is the only part that will be quoted, and only if # it needs to be. This allows extended characters to be used in the - # "to", "from", "cc", and "bcc" headers. + # "to", "from", "cc", "bcc" and "reply-to" headers. def quote_address_if_necessary(address, charset) if Array === address address.map { |a| quote_address_if_necessary(a, charset) } diff --git a/actionmailer/lib/action_mailer/vendor.rb b/actionmailer/lib/action_mailer/vendor.rb index 56a2858be5..7a20e9bd6e 100644 --- a/actionmailer/lib/action_mailer/vendor.rb +++ b/actionmailer/lib/action_mailer/vendor.rb @@ -2,9 +2,9 @@ require 'rubygems' begin - gem 'tmail', '~> 1.2.2' + gem 'tmail', '~> 1.2.3' rescue Gem::LoadError - $:.unshift "#{File.dirname(__FILE__)}/vendor/tmail-1.2.2" + $:.unshift "#{File.dirname(__FILE__)}/vendor/tmail-1.2.3" end begin diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail.rb index 18003659a6..18003659a6 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/address.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/address.rb index fa8e5bcd8c..982ad5b661 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/address.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/address.rb @@ -38,7 +38,7 @@ module TMail # = Class Address # # Provides a complete handling library for email addresses. Can parse a string of an - # address directly or take in preformatted addresses themseleves. Allows you to add + # address directly or take in preformatted addresses themselves. Allows you to add # and remove phrases from the front of the address and provides a compare function for # email addresses. # @@ -143,7 +143,7 @@ module TMail # This is to catch an unquoted "@" symbol in the local part of the # address. Handles addresses like <"@"@me.com> and makes sure they - # stay like <"@"@me.com> (previously were becomming <@@me.com>) + # stay like <"@"@me.com> (previously were becoming <@@me.com>) if local && (local.join == '@' || local.join =~ /\A[^"].*?@.*?[^"]\Z/) @local = "\"#{local.join}\"" else diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/attachments.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/attachments.rb index 5dc5efae5e..5dc5efae5e 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/attachments.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/attachments.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/base64.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/base64.rb index e294c62960..e294c62960 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/base64.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/base64.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/compat.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/compat.rb index 1275df79a6..1275df79a6 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/compat.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/compat.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/config.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/config.rb index 3a876dcdbd..3a876dcdbd 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/config.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/config.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/core_extensions.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/core_extensions.rb index da62c33bbf..da62c33bbf 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/core_extensions.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/core_extensions.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/encode.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/encode.rb index 63bccce4fc..458dbbfe6a 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/encode.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/encode.rb @@ -339,22 +339,36 @@ module TMail def scanadd( str, force = false ) types = '' strs = [] - + if str.respond_to?(:encoding) + enc = str.encoding + str.force_encoding(Encoding::ASCII_8BIT) + end until str.empty? if m = /\A[^\e\t\r\n ]+/.match(str) types << (force ? 'j' : 'a') - strs.push m[0] - + if str.respond_to?(:encoding) + strs.push m[0].force_encoding(enc) + else + strs.push m[0] + end elsif m = /\A[\t\r\n ]+/.match(str) types << 's' - strs.push m[0] + if str.respond_to?(:encoding) + strs.push m[0].force_encoding(enc) + else + strs.push m[0] + end elsif m = /\A\e../.match(str) esc = m[0] str = m.post_match if esc != "\e(B" and m = /\A[^\e]+/.match(str) types << 'j' - strs.push m[0] + if str.respond_to?(:encoding) + strs.push m[0].force_encoding(enc) + else + strs.push m[0] + end end else @@ -453,7 +467,13 @@ module TMail size = max_bytes(chunksize, str.size) - 6 size = (size % 2 == 0) ? (size) : (size - 1) return nil if size <= 0 - "\e$B#{str.slice!(0, size)}\e(B" + if str.respond_to?(:encoding) + enc = str.encoding + str.force_encoding(Encoding::ASCII_8BIT) + "\e$B#{str.slice!(0, size)}\e(B".force_encoding(enc) + else + "\e$B#{str.slice!(0, size)}\e(B" + end end def extract_A( chunksize, str ) diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/header.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/header.rb index 9153dcd7c6..dbdefcf979 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/header.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/header.rb @@ -59,7 +59,7 @@ module TMail # # This is because a mailbox doesn't have the : after the From that designates the # beginning of the envelope sender (which can be different to the from address of - # the emial) + # the email) # # Other fields can be passed as normal, "Reply-To", "Received" etc. # diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/index.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/index.rb index 554e2fd696..554e2fd696 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/index.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/index.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/interface.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/interface.rb index 206653bd5d..2fc2dbdfc7 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/interface.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/interface.rb @@ -42,7 +42,7 @@ module TMail # Allows you to query the mail object with a string to get the contents # of the field you want. # - # Returns a string of the exact contnts of the field + # Returns a string of the exact contents of the field # # mail.from = "mikel <mikel@lindsaar.net>" # mail.header_string("From") #=> "mikel <mikel@lindsaar.net>" @@ -591,12 +591,17 @@ module TMail end # Destructively sets the message ID of the mail object instance to the passed in string + # + # Invalid message IDs are ignored (silently, unless configured otherwise) and result in + # a nil message ID. Left and right angle brackets are required. # # Example: # # mail = TMail::Mail.new + # mail.message_id = "<348F04F142D69C21-291E56D292BC@xxxx.net>" + # mail.message_id #=> "<348F04F142D69C21-291E56D292BC@xxxx.net>" # mail.message_id = "this_is_my_badly_formatted_message_id" - # mail.message_id #=> "this_is_my_badly_formatted_message_id" + # mail.message_id #=> nil def message_id=( str ) set_string_attr 'Message-Id', str end diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/loader.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/loader.rb index 6c0e251102..6c0e251102 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/loader.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/loader.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/mail.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mail.rb index fef6b01c39..c3a8803dc4 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/mail.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mail.rb @@ -255,7 +255,7 @@ module TMail alias fetch [] # Allows you to set or delete TMail header objects at will. - # Eamples: + # Examples: # @mail = TMail::Mail.new # @mail['to'].to_s # => 'mikel@test.com.au' # @mail['to'] = 'mikel@elsewhere.org' @@ -265,7 +265,7 @@ module TMail # @mail['to'].to_s # => nil # @mail.encoded # => "\r\n" # - # Note: setting mail[] = nil actualy deletes the header field in question from the object, + # Note: setting mail[] = nil actually deletes the header field in question from the object, # it does not just set the value of the hash to nil def []=( key, val ) dkey = key.downcase @@ -408,8 +408,8 @@ module TMail when /\AFrom (\S+)/ unixfrom = $1 - when /^charset=.*/ - + when /^charset=.*/ + else raise SyntaxError, "wrong mail header: '#{line.inspect}'" end diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/mailbox.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mailbox.rb index b0bc6a7f74..b0bc6a7f74 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/mailbox.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mailbox.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/main.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/main.rb index e52772793f..e52772793f 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/main.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/main.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/mbox.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mbox.rb index 6c0e251102..6c0e251102 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/mbox.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mbox.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/net.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/net.rb index 65147228a1..65147228a1 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/net.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/net.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/obsolete.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/obsolete.rb index 22b0a126ca..22b0a126ca 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/obsolete.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/obsolete.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/parser.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/parser.rb index ab1a828471..ab1a828471 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/parser.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/parser.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/port.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/port.rb index 445f0e632b..445f0e632b 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/port.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/port.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/quoting.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/quoting.rb index cb9f4288f1..cb9f4288f1 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/quoting.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/quoting.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/require_arch.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/require_arch.rb index b4fffb8abb..b4fffb8abb 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/require_arch.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/require_arch.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/scanner.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner.rb index a5d01396b8..a5d01396b8 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/scanner.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/scanner_r.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner_r.rb index f2075502d8..f2075502d8 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/scanner_r.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner_r.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/stringio.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/stringio.rb index 8357398788..8357398788 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/stringio.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/stringio.rb diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/utils.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/utils.rb index 9a3afe8985..dc594a4229 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/utils.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/utils.rb @@ -118,7 +118,7 @@ module TMail ATOM_UNSAFE = /[#{Regexp.quote aspecial}#{control}#{lwsp}]/n PHRASE_UNSAFE = /[#{Regexp.quote aspecial}#{control}]/n TOKEN_UNSAFE = /[#{Regexp.quote tspecial}#{control}#{lwsp}]/n - + # Returns true if the string supplied is free from characters not allowed as an ATOM def atom_safe?( str ) not ATOM_UNSAFE === str diff --git a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/version.rb b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/version.rb index 6bf8cc8061..95228497c0 100644 --- a/actionmailer/lib/action_mailer/vendor/tmail-1.2.2/tmail/version.rb +++ b/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/version.rb @@ -32,7 +32,7 @@ module TMail module VERSION MAJOR = 1 MINOR = 2 - TINY = 2 + TINY = 3 STRING = [MAJOR, MINOR, TINY].join('.') end diff --git a/actionmailer/lib/action_mailer/version.rb b/actionmailer/lib/action_mailer/version.rb index 88b9a3c200..c35b648baf 100644 --- a/actionmailer/lib/action_mailer/version.rb +++ b/actionmailer/lib/action_mailer/version.rb @@ -1,8 +1,8 @@ module ActionMailer module VERSION #:nodoc: MAJOR = 2 - MINOR = 0 - TINY = 991 + MINOR = 1 + TINY = 0 STRING = [MAJOR, MINOR, TINY].join('.') end diff --git a/actionmailer/test/mail_service_test.rb b/actionmailer/test/mail_service_test.rb index 57a651ccd4..e5ecb0e254 100755 --- a/actionmailer/test/mail_service_test.rb +++ b/actionmailer/test/mail_service_test.rb @@ -40,6 +40,15 @@ class TestMailer < ActionMailer::Base body "Nothing to see here." end + def different_reply_to(recipient) + recipients recipient + subject "testing reply_to" + from "system@loudthinking.com" + sent_on Time.local(2008, 5, 23) + reply_to "atraver@gmail.com" + body "Nothing to see here." + end + def iso_charset(recipient) @recipients = recipient @subject = "testing isø charsets" @@ -445,6 +454,31 @@ class ActionMailerTest < Test::Unit::TestCase assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded end + def test_reply_to + expected = new_mail + + expected.to = @recipient + expected.subject = "testing reply_to" + expected.body = "Nothing to see here." + expected.from = "system@loudthinking.com" + expected.reply_to = "atraver@gmail.com" + expected.date = Time.local 2008, 5, 23 + + created = nil + assert_nothing_raised do + created = TestMailer.create_different_reply_to @recipient + end + assert_not_nil created + assert_equal expected.encoded, created.encoded + + assert_nothing_raised do + TestMailer.deliver_different_reply_to @recipient + end + + assert_not_nil ActionMailer::Base.deliveries.first + assert_equal expected.encoded, ActionMailer::Base.deliveries.first.encoded + end + def test_iso_charset expected = new_mail( "iso-8859-1" ) expected.to = @recipient diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index 4a24d2f8b9..9622029362 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,4 +1,9 @@ -*2.1.0 RC1 (May 11th, 2008)* +* Added Rack processor [Ezra Zygmuntowicz, Josh Peek] + + +*2.1.0 (May 31st, 2008)* + +* InstanceTag#default_time_from_options overflows to DateTime [Geoff Buesing] * Fixed that forgery protection can be used without session tracking (Peter Jones) [#139] diff --git a/actionpack/README b/actionpack/README index 2746c3cc43..6090089bb9 100644 --- a/actionpack/README +++ b/actionpack/README @@ -31,7 +31,7 @@ http://www.rubyonrails.org. A short rundown of the major features: * Actions grouped in controller as methods instead of separate command objects - and can therefore share helper methods. + and can therefore share helper methods BlogController < ActionController::Base def show @@ -168,7 +168,7 @@ A short rundown of the major features: {Learn more}[link:classes/ActionController/Base.html] -* Javascript and Ajax integration. +* Javascript and Ajax integration link_to_function "Greeting", "alert('Hello world!')" link_to_remote "Delete this post", :update => "posts", @@ -177,7 +177,7 @@ A short rundown of the major features: {Learn more}[link:classes/ActionView/Helpers/JavaScriptHelper.html] -* Pagination for navigating lists of results. +* Pagination for navigating lists of results # controller def list @@ -192,15 +192,9 @@ A short rundown of the major features: {Learn more}[link:classes/ActionController/Pagination.html] -* Easy testing of both controller and template result through TestRequest/Response - - class LoginControllerTest < Test::Unit::TestCase - def setup - @controller = LoginController.new - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - end +* Easy testing of both controller and rendered template through ActionController::TestCase + class LoginControllerTest < ActionController::TestCase def test_failing_authenticate process :authenticate, :user_name => "nop", :password => "" assert flash.has_key?(:alert) @@ -208,7 +202,7 @@ A short rundown of the major features: end end - {Learn more}[link:classes/ActionController/TestRequest.html] + {Learn more}[link:classes/ActionController/TestCase.html] * Automated benchmarking and integrated logging diff --git a/actionpack/Rakefile b/actionpack/Rakefile index 0147a5c1e8..b37f756c1e 100644 --- a/actionpack/Rakefile +++ b/actionpack/Rakefile @@ -76,7 +76,7 @@ spec = Gem::Specification.new do |s| s.has_rdoc = true s.requirements << 'none' - s.add_dependency('activesupport', '= 2.0.991' + PKG_BUILD) + s.add_dependency('activesupport', '= 2.1.0' + PKG_BUILD) s.require_path = 'lib' s.autorequire = 'action_controller' diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb index 810a5fb9b5..3c4a339d50 100755 --- a/actionpack/lib/action_controller.rb +++ b/actionpack/lib/action_controller.rb @@ -53,6 +53,7 @@ require 'action_controller/streaming' require 'action_controller/session_management' require 'action_controller/http_authentication' require 'action_controller/components' +require 'action_controller/rack_process' require 'action_controller/record_identifier' require 'action_controller/request_forgery_protection' require 'action_controller/headers' diff --git a/actionpack/lib/action_controller/assertions/model_assertions.rb b/actionpack/lib/action_controller/assertions/model_assertions.rb index 0b4313055a..d25214bb66 100644 --- a/actionpack/lib/action_controller/assertions/model_assertions.rb +++ b/actionpack/lib/action_controller/assertions/model_assertions.rb @@ -1,7 +1,8 @@ module ActionController module Assertions module ModelAssertions - # Ensures that the passed record is valid by ActiveRecord standards and returns any error messages if it is not. + # Ensures that the passed record is valid by Active Record standards and + # returns any error messages if it is not. # # ==== Examples # diff --git a/actionpack/lib/action_controller/assertions/routing_assertions.rb b/actionpack/lib/action_controller/assertions/routing_assertions.rb index 2acd003243..491b72d586 100644 --- a/actionpack/lib/action_controller/assertions/routing_assertions.rb +++ b/actionpack/lib/action_controller/assertions/routing_assertions.rb @@ -59,7 +59,7 @@ module ActionController end end - # Asserts that the provided options can be used to generate the provided path. This is the inverse of #assert_recognizes. + # Asserts that the provided options can be used to generate the provided path. This is the inverse of +assert_recognizes+. # The +extras+ parameter is used to tell the request the names and values of additional request parameters that would be in # a query string. The +message+ parameter allows you to specify a custom error message for assertion failures. # @@ -96,8 +96,8 @@ module ActionController end # Asserts that path and options match both ways; in other words, it verifies that <tt>path</tt> generates - # <tt>options</tt> and then that <tt>options</tt> generates <tt>path</tt>. This essentially combines #assert_recognizes - # and #assert_generates into one step. + # <tt>options</tt> and then that <tt>options</tt> generates <tt>path</tt>. This essentially combines +assert_recognizes+ + # and +assert_generates+ into one step. # # The +extras+ hash allows you to specify options that would normally be provided as a query string to the action. The # +message+ parameter allows you to specify a custom error message to display upon failure. diff --git a/actionpack/lib/action_controller/assertions/selector_assertions.rb b/actionpack/lib/action_controller/assertions/selector_assertions.rb index 9ef093acfc..d3594e711c 100644 --- a/actionpack/lib/action_controller/assertions/selector_assertions.rb +++ b/actionpack/lib/action_controller/assertions/selector_assertions.rb @@ -12,12 +12,12 @@ module ActionController NO_STRIP = %w{pre script style textarea} end - # Adds the #assert_select method for use in Rails functional + # Adds the +assert_select+ method for use in Rails functional # test cases, which can be used to make assertions on the response HTML of a controller - # action. You can also call #assert_select within another #assert_select to + # action. You can also call +assert_select+ within another +assert_select+ to # make assertions on elements selected by the enclosing assertion. # - # Use #css_select to select elements without making an assertions, either + # Use +css_select+ to select elements without making an assertions, either # from the response HTML or elements selected by the enclosing assertion. # # In addition to HTML responses, you can make the following assertions: @@ -44,8 +44,8 @@ module ActionController # base element and any of its children. Returns an empty array if no # match is found. # - # The selector may be a CSS selector expression (+String+), an expression - # with substitution values (+Array+) or an HTML::Selector object. + # The selector may be a CSS selector expression (String), an expression + # with substitution values (Array) or an HTML::Selector object. # # ==== Examples # # Selects all div tags @@ -114,8 +114,8 @@ module ActionController # starting from (and including) that element and all its children in # depth-first order. # - # If no element if specified, calling #assert_select will select from the - # response HTML. Calling #assert_select inside an #assert_select block will + # If no element if specified, calling +assert_select+ will select from the + # response HTML. Calling #assert_select inside an +assert_select+ block will # run the assertion for each element selected by the enclosing assertion. # # ==== Example @@ -130,7 +130,7 @@ module ActionController # assert_select "li" # end # - # The selector may be a CSS selector expression (+String+), an expression + # The selector may be a CSS selector expression (String), an expression # with substitution values, or an HTML::Selector object. # # === Equality Tests @@ -356,16 +356,16 @@ module ActionController # # === Using blocks # - # Without a block, #assert_select_rjs merely asserts that the response + # Without a block, +assert_select_rjs+ merely asserts that the response # contains one or more RJS statements that replace or update content. # - # With a block, #assert_select_rjs also selects all elements used in + # With a block, +assert_select_rjs+ also selects all elements used in # these statements and passes them to the block. Nested assertions are # supported. # - # Calling #assert_select_rjs with no arguments and using nested asserts + # Calling +assert_select_rjs+ with no arguments and using nested asserts # asserts that the HTML content is returned by one or more RJS statements. - # Using #assert_select directly makes the same assertion on the content, + # Using +assert_select+ directly makes the same assertion on the content, # but without distinguishing whether the content is returned in an HTML # or JavaScript. # @@ -601,7 +601,7 @@ module ActionController RJS_PATTERN_UNICODE_ESCAPED_CHAR = /\\u([0-9a-zA-Z]{4})/ end - # #assert_select and #css_select call this to obtain the content in the HTML + # +assert_select+ and +css_select+ call this to obtain the content in the HTML # page, or from all the RJS statements, depending on the type of response. def response_from_page_or_rjs() content_type = @response.content_type diff --git a/actionpack/lib/action_controller/assertions/tag_assertions.rb b/actionpack/lib/action_controller/assertions/tag_assertions.rb index 4ac489520a..90ba3668fb 100644 --- a/actionpack/lib/action_controller/assertions/tag_assertions.rb +++ b/actionpack/lib/action_controller/assertions/tag_assertions.rb @@ -91,7 +91,7 @@ module ActionController # :descendant => { :tag => "span", # :child => /hello world/ } # - # <b>Please note</b>: #assert_tag and #assert_no_tag only work + # <b>Please note</b>: +assert_tag+ and +assert_no_tag+ only work # with well-formed XHTML. They recognize a few tags as implicitly self-closing # (like br and hr and such) but will not work correctly with tags # that allow optional closing tags (p, li, td). <em>You must explicitly @@ -104,8 +104,8 @@ module ActionController 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.) + # Identical to +assert_tag+, but asserts that a matching tag does _not_ + # exist. (See +assert_tag+ for a full discussion of the syntax.) # # === Examples # # Assert that there is not a "div" containing a "p" diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index ea55fe42ce..6222c3205d 100755 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -104,7 +104,7 @@ module ActionController #:nodoc: # end # # Actions, by default, render a template in the <tt>app/views</tt> 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 <tt>app/views/guestbook/index.erb</tt> by default after populating the <tt>@entries</tt> instance variable. # # Unlike index, the sign action will not render a template. After performing its main purpose (creating a @@ -118,10 +118,10 @@ module ActionController #:nodoc: # # Requests are processed by the Action Controller framework by extracting the value of the "action" key in the request parameters. # This value should hold the name of the action to be performed. Once the action has been identified, the remaining - # request parameters, the session (if one is available), and the full request with all the http headers are made available to + # request parameters, the session (if one is available), and the full request with all the HTTP headers are made available to # the action through instance variables. Then the action is performed. # - # The full request object is available with the request accessor and is primarily used to query for http headers. These queries + # The full request object is available with the request accessor and is primarily used to query for HTTP headers. These queries # are made by accessing the environment hash, like this: # # def server_ip @@ -291,10 +291,10 @@ module ActionController #:nodoc: 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 which will process the http body and add parameters to the - # <tt>params</tt> hash. These handlers are invoked for post and put requests. + # The <tt>@@param_parsers</tt> hash lets you register handlers which will process the HTTP body and add parameters to the + # <tt>params</tt> 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 instantiated + # By default <tt>application/xml</tt> is enabled. A XmlSimple class with the same param name as the root will be instantiated # in the <tt>params</tt>. 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. # @@ -307,7 +307,7 @@ module ActionController #:nodoc: # # 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 "<r><name>David</name></r>" results - # in params[:r][:name] for "David" instead of params[:name]. To get the old behavior, you can + # in <tt>params[:r][:name]</tt> for "David" instead of <tt>params[:name]</tt>. To get the old behavior, you can # re-register XmlSimple as application/xml handler ike this: # # ActionController::Base.param_parsers[Mime::XML] = @@ -347,7 +347,7 @@ module ActionController #:nodoc: cattr_accessor :optimise_named_routes self.optimise_named_routes = true - # Controls whether request forgergy protection is turned on or not. Turned off by default only in test mode. + # Controls whether request forgery protection is turned on or not. Turned off by default only in test mode. class_inheritable_accessor :allow_forgery_protection self.allow_forgery_protection = true diff --git a/actionpack/lib/action_controller/caching/fragments.rb b/actionpack/lib/action_controller/caching/fragments.rb index e4d8678a07..578e031a17 100644 --- a/actionpack/lib/action_controller/caching/fragments.rb +++ b/actionpack/lib/action_controller/caching/fragments.rb @@ -2,7 +2,7 @@ module ActionController #:nodoc: module Caching # Fragment caching is used for caching various blocks within templates without caching the entire action as a whole. This is useful when # certain elements of an action change frequently or depend on complicated state while other parts rarely change or can be shared amongst multiple - # parties. The caching is doing using the cache helper available in the Action View. A template with caching might look something like: + # parties. The caching is done using the cache helper available in the Action View. A template with caching might look something like: # # <b>Hello <%= @name %></b> # <% cache do %> @@ -98,6 +98,17 @@ module ActionController #:nodoc: end end + # Check if a cached fragment from the location signified by <tt>key</tt> exists (see <tt>expire_fragment</tt> for acceptable formats) + def fragment_exist?(key, options = nil) + return unless cache_configured? + + key = fragment_cache_key(key) + + self.class.benchmark "Cached fragment exists?: #{key}" do + cache_store.exist?(key, options) + end + end + # 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 } @@ -124,4 +135,4 @@ module ActionController #:nodoc: end end end -end
\ No newline at end of file +end diff --git a/actionpack/lib/action_controller/cgi_ext/cookie.rb b/actionpack/lib/action_controller/cgi_ext/cookie.rb index a244e2a39a..009ddd1c64 100644 --- a/actionpack/lib/action_controller/cgi_ext/cookie.rb +++ b/actionpack/lib/action_controller/cgi_ext/cookie.rb @@ -6,25 +6,24 @@ class CGI #:nodoc: attr_accessor :name, :value, :path, :domain, :expires attr_reader :secure, :http_only - # Create a new CGI::Cookie object. + # Creates a new CGI::Cookie object. # # The contents of the cookie can be specified as a +name+ and one # or more +value+ arguments. Alternatively, the contents can # be specified as a single hash argument. The possible keywords of # this hash are as follows: # - # name:: the name of the cookie. Required. - # value:: the cookie's value or list of values. - # path:: the path for which this cookie applies. Defaults to the - # base directory of the CGI script. - # domain:: the domain for which this cookie applies. - # expires:: the time at which this cookie expires, as a +Time+ object. - # secure:: whether this cookie is a secure cookie or not (default to - # false). Secure cookies are only transmitted to HTTPS - # servers. - # http_only:: whether this cookie can be accessed by client side scripts (e.g. document.cookie) or only over HTTP - # More details: http://msdn2.microsoft.com/en-us/library/system.web.httpcookie.httponly.aspx - # Defaults to false. + # * <tt>:name</tt> - The name of the cookie. Required. + # * <tt>:value</tt> - The cookie's value or list of values. + # * <tt>:path</tt> - The path for which this cookie applies. Defaults to the + # base directory of the CGI script. + # * <tt>:domain</tt> - The domain for which this cookie applies. + # * <tt>:expires</tt> - The time at which this cookie expires, as a Time object. + # * <tt>:secure</tt> - Whether this cookie is a secure cookie or not (defaults to + # +false+). Secure cookies are only transmitted to HTTPS servers. + # * <tt>:http_only</tt> - Whether this cookie can be accessed by client side scripts (e.g. document.cookie) or only over HTTP. + # More details in http://msdn2.microsoft.com/en-us/library/system.web.httpcookie.httponly.aspx. Defaults to +false+. + # # These keywords correspond to attributes of the cookie object. def initialize(name = '', *value) if name.kind_of?(String) @@ -56,17 +55,17 @@ class CGI #:nodoc: super(@value) end - # Set whether the Cookie is a secure cookie or not. + # Sets whether the Cookie is a secure cookie or not. def secure=(val) @secure = val == true end - # Set whether the Cookie is an HTTP only cookie or not. + # Sets whether the Cookie is an HTTP only cookie or not. def http_only=(val) @http_only = val == true end - # Convert the Cookie to its string representation. + # Converts the Cookie to its string representation. def to_s buf = '' buf << @name << '=' @@ -79,11 +78,17 @@ class CGI #:nodoc: buf end - # Parse a raw cookie string into a hash of cookie-name=>Cookie + # FIXME: work around broken 1.8.7 DelegateClass#respond_to? + def respond_to?(method, include_private = false) + return true if super(method) + return __getobj__.respond_to?(method, include_private) + end + + # Parses a raw cookie string into a hash of <tt>cookie-name => cookie-object</tt> # pairs. # # cookies = CGI::Cookie::parse("raw_cookie_string") - # # { "name1" => cookie1, "name2" => cookie2, ... } + # # => { "name1" => cookie1, "name2" => cookie2, ... } # def self.parse(raw_cookie) cookies = Hash.new([]) diff --git a/actionpack/lib/action_controller/cgi_ext/stdinput.rb b/actionpack/lib/action_controller/cgi_ext/stdinput.rb index b0ca63ef2f..5e9b6784af 100644 --- a/actionpack/lib/action_controller/cgi_ext/stdinput.rb +++ b/actionpack/lib/action_controller/cgi_ext/stdinput.rb @@ -16,6 +16,7 @@ module ActionController def initialize_with_stdinput(type = nil, stdinput = $stdin) @stdinput = stdinput + @stdinput.set_encoding(Encoding::BINARY) if @stdinput.respond_to?(:set_encoding) initialize_without_stdinput(type || 'query') end end diff --git a/actionpack/lib/action_controller/cgi_process.rb b/actionpack/lib/action_controller/cgi_process.rb index b529db8af4..8bc5e4c3a7 100644 --- a/actionpack/lib/action_controller/cgi_process.rb +++ b/actionpack/lib/action_controller/cgi_process.rb @@ -15,7 +15,7 @@ module ActionController #:nodoc: # * <tt>:new_session</tt> - 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, # an ArgumentError is raised. - # * <tt>:session_expires</tt> - the time the current session expires, as a +Time+ object. If not set, the session will continue + # * <tt>:session_expires</tt> - the time the current session expires, as a Time object. If not set, the session will continue # indefinitely. # * <tt>:session_domain</tt> - the hostname domain for which this session is valid. If not set, defaults to the hostname of the # server. @@ -65,6 +65,7 @@ module ActionController #:nodoc: # variable is already set, wrap it in a StringIO. def body if raw_post = env['RAW_POST_DATA'] + raw_post.force_encoding(Encoding::BINARY) if raw_post.respond_to?(:force_encoding) StringIO.new(raw_post) else @cgi.stdinput diff --git a/actionpack/lib/action_controller/dispatcher.rb b/actionpack/lib/action_controller/dispatcher.rb index 6e1e7a261f..b40f1ba9be 100644 --- a/actionpack/lib/action_controller/dispatcher.rb +++ b/actionpack/lib/action_controller/dispatcher.rb @@ -96,7 +96,7 @@ module ActionController include ActiveSupport::Callbacks define_callbacks :prepare_dispatch, :before_dispatch, :after_dispatch - def initialize(output, request = nil, response = nil) + def initialize(output = $stdout, request = nil, response = nil) @output, @request, @response = output, request, response end @@ -123,6 +123,12 @@ module ActionController failsafe_rescue exception end + def call(env) + @request = RackRequest.new(env) + @response = RackResponse.new + dispatch + end + def reload_application # Run prepare callbacks before every request in development mode run_callbacks :prepare_dispatch diff --git a/actionpack/lib/action_controller/filters.rb b/actionpack/lib/action_controller/filters.rb index 6d0c83eb40..60d92d9b98 100644 --- a/actionpack/lib/action_controller/filters.rb +++ b/actionpack/lib/action_controller/filters.rb @@ -100,10 +100,10 @@ module ActionController #:nodoc: # # 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 +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. + # To use a method as an +around_filter+, pass a symbol naming the Ruby method. + # Yield (or <tt>block.call</tt>) within the method to run the action. # # around_filter :catch_exceptions # @@ -115,9 +115,9 @@ module ActionController #:nodoc: # raise # end # - # To use a block as an around_filter, pass a block taking as args both + # 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: + # an +around_filter+ block; explicitly call the action block instead: # # around_filter do |controller, action| # logger.debug "before #{controller.action_name}" @@ -125,7 +125,7 @@ module ActionController #:nodoc: # logger.debug "after #{controller.action_name}" # end # - # To use a filter object with around_filter, pass an object responding + # To use a filter object with +around_filter+, pass an object responding # to <tt>:filter</tt> or both <tt>:before</tt> and <tt>:after</tt>. With a # filter method, yield to the block as above: # @@ -137,7 +137,7 @@ module ActionController #:nodoc: # end # end # - # With before and after methods: + # With +before+ and +after+ methods: # # around_filter Authorizer.new # @@ -154,9 +154,9 @@ module ActionController #:nodoc: # end # end # - # If the filter has before and after methods, the before method will be - # called before the action. If before renders or redirects, the filter chain is - # halted and after will not be run. See Filter Chain Halting below for + # If the filter has +before+ and +after+ methods, the +before+ method will be + # called before the action. If +before+ renders or redirects, the filter chain is + # halted and +after+ will not be run. See Filter Chain Halting below for # an example. # # == Filter chain skipping @@ -215,7 +215,7 @@ module ActionController #:nodoc: # # <tt>before_filter</tt> and <tt>around_filter</tt> may halt the request # before a controller action is run. This is useful, for example, to deny - # access to unauthenticated users or to redirect from http to https. + # access to unauthenticated users or to redirect from HTTP to HTTPS. # Simply call render or redirect. After filters will not be executed if the filter # chain is halted. # @@ -241,10 +241,10 @@ module ActionController #:nodoc: # . / # #after (actual filter code is run, unless the around filter does not yield) # - # If #around returns before yielding, #after will still not be run. The #before - # filter and controller action will not be run. If #before renders or redirects, - # the second half of #around and will still run but #after and the - # action will not. If #around fails to yield, #after will not be run. + # If +around+ returns before yielding, +after+ will still not be run. The +before+ + # filter and controller action will not be run. If +before+ renders or redirects, + # the second half of +around+ and will still run but +after+ and the + # action will not. If +around+ fails to yield, +after+ will not be run. class FilterChain < ActiveSupport::Callbacks::CallbackChain #:nodoc: def append_filter_to_chain(filters, filter_type, &block) @@ -471,7 +471,7 @@ module ActionController #:nodoc: # Shorthand for append_after_filter since it's the most common. alias :after_filter :append_after_filter - # If you append_around_filter A.new, B.new, the filter chain looks like + # If you <tt>append_around_filter A.new, B.new</tt>, the filter chain looks like # # B#before # A#before @@ -479,13 +479,13 @@ module ActionController #:nodoc: # A#after # B#after # - # With around filters which yield to the action block, #before and #after + # 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) filter_chain.append_filter_to_chain(filters, :around, &block) end - # If you prepend_around_filter A.new, B.new, the filter chain looks like: + # If you <tt>prepend_around_filter A.new, B.new</tt>, the filter chain looks like: # # A#before # B#before @@ -493,13 +493,13 @@ module ActionController #:nodoc: # B#after # A#after # - # With around filters which yield to the action block, #before and #after + # 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) filter_chain.prepend_filter_to_chain(filters, :around, &block) end - # Shorthand for append_around_filter since it's the most common. + # 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 diff --git a/actionpack/lib/action_controller/helpers.rb b/actionpack/lib/action_controller/helpers.rb index a8bead4d34..ce5e8be54c 100644 --- a/actionpack/lib/action_controller/helpers.rb +++ b/actionpack/lib/action_controller/helpers.rb @@ -20,7 +20,7 @@ module ActionController #:nodoc: end # The Rails framework provides a large number of helpers for working with +assets+, +dates+, +forms+, - # +numbers+ and +ActiveRecord+ objects, to name a few. These helpers are available to all templates + # +numbers+ and Active Record objects, to name a few. These helpers are available to all templates # by default. # # In addition to using the standard template helpers provided in the Rails framework, creating custom helpers to @@ -32,7 +32,7 @@ module ActionController #:nodoc: # controller which inherits from it. # # ==== Examples - # The +to_s+ method from the +Time+ class can be wrapped in a helper method to display a custom message if + # The +to_s+ method from the Time class can be wrapped in a helper method to display a custom message if # the Time object is blank: # # module FormattedTimeHelper @@ -41,7 +41,7 @@ module ActionController #:nodoc: # end # end # - # +FormattedTimeHelper+ can now be included in a controller, using the +helper+ class method: + # FormattedTimeHelper can now be included in a controller, using the +helper+ class method: # # class EventsController < ActionController::Base # helper FormattedTimeHelper @@ -74,22 +74,22 @@ module ActionController #:nodoc: # The +helper+ class method can take a series of helper module names, a block, or both. # - # * <tt>*args</tt>: One or more +Modules+, +Strings+ or +Symbols+, or the special symbol <tt>:all</tt>. + # * <tt>*args</tt>: One or more modules, strings or symbols, or the special symbol <tt>:all</tt>. # * <tt>&block</tt>: A block defining helper methods. # # ==== Examples - # When the argument is a +String+ or +Symbol+, the method will provide the "_helper" suffix, require the file + # When the argument is a string or symbol, the method will provide the "_helper" suffix, require the file # and include the module in the template class. The second form illustrates how to include custom helpers # when working with namespaced controllers, or other cases where the file containing the helper definition is not # in one of Rails' standard load paths: # helper :foo # => requires 'foo_helper' and includes FooHelper # helper 'resources/foo' # => requires 'resources/foo_helper' and includes Resources::FooHelper # - # When the argument is a +Module+, it will be included directly in the template class. + # When the argument is a module it will be included directly in the template class. # helper FooHelper # => includes FooHelper # # When the argument is the symbol <tt>:all</tt>, the controller will include all helpers from - # <tt>app/helpers/**/*.rb</tt> under +RAILS_ROOT+. + # <tt>app/helpers/**/*.rb</tt> under RAILS_ROOT. # helper :all # # Additionally, the +helper+ class method can receive and evaluate a block, making the methods defined available diff --git a/actionpack/lib/action_controller/integration.rb b/actionpack/lib/action_controller/integration.rb index a4bbee9c54..12e1b4d493 100644 --- a/actionpack/lib/action_controller/integration.rb +++ b/actionpack/lib/action_controller/integration.rb @@ -58,7 +58,7 @@ module ActionController class MultiPartNeededException < Exception end - # Create and initialize a new +Session+ instance. + # Create and initialize a new Session instance. def initialize reset! end @@ -100,7 +100,7 @@ module ActionController @https = flag end - # Return +true+ if the session is mimicing a secure HTTPS request. + # Return +true+ if the session is mimicking a secure HTTPS request. # # if session.https? # ... @@ -136,25 +136,25 @@ module ActionController end # Performs a GET request, following any subsequent redirect. - # See #request_via_redirect() for more information. + # See +request_via_redirect+ for more information. def get_via_redirect(path, parameters = nil, headers = nil) request_via_redirect(:get, path, parameters, headers) end # Performs a POST request, following any subsequent redirect. - # See #request_via_redirect() for more information. + # See +request_via_redirect+ for more information. def post_via_redirect(path, parameters = nil, headers = nil) request_via_redirect(:post, path, parameters, headers) end # Performs a PUT request, following any subsequent redirect. - # See #request_via_redirect() for more information. + # See +request_via_redirect+ for more information. def put_via_redirect(path, parameters = nil, headers = nil) request_via_redirect(:put, path, parameters, headers) end # Performs a DELETE request, following any subsequent redirect. - # See #request_via_redirect() for more information. + # See +request_via_redirect+ for more information. def delete_via_redirect(path, parameters = nil, headers = nil) request_via_redirect(:delete, path, parameters, headers) end @@ -166,12 +166,12 @@ module ActionController # Performs a GET request with the given parameters. The parameters may # be +nil+, a Hash, or a string that is appropriately encoded - # (application/x-www-form-urlencoded or multipart/form-data). The headers - # should be a hash. The keys will automatically be upcased, with the + # (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>). + # The headers should be a hash. The keys will automatically be upcased, with the # prefix 'HTTP_' added if needed. # - # You can also perform POST, PUT, DELETE, and HEAD requests with #post, - # #put, #delete, and #head. + # You can also perform POST, PUT, DELETE, and HEAD requests with +post+, + # +put+, +delete+, and +head+. def get(path, parameters = nil, headers = nil) process :get, path, parameters, headers end @@ -228,6 +228,8 @@ module ActionController super + stdinput.set_encoding(Encoding::BINARY) if stdinput.respond_to?(:set_encoding) + stdinput.force_encoding(Encoding::BINARY) if stdinput.respond_to?(:force_encoding) @stdinput = stdinput.is_a?(IO) ? stdinput : StringIO.new(stdinput || '') end end @@ -382,6 +384,8 @@ module ActionController multipart_requestify(params).map do |key, value| if value.respond_to?(:original_filename) File.open(value.path) do |f| + f.set_encoding(Encoding::BINARY) if f.respond_to?(:set_encoding) + <<-EOF --#{boundary}\r Content-Disposition: form-data; name="#{key}"; filename="#{CGI.escape(value.original_filename)}"\r diff --git a/actionpack/lib/action_controller/mime_responds.rb b/actionpack/lib/action_controller/mime_responds.rb index a17782cafc..1dbd8b9e6f 100644 --- a/actionpack/lib/action_controller/mime_responds.rb +++ b/actionpack/lib/action_controller/mime_responds.rb @@ -92,7 +92,7 @@ module ActionController #:nodoc: # with the remaining data. # # Note that you can define your own XML parameter parser which would allow you to describe multiple entities - # in a single request (i.e., by wrapping them all in a single root note), but if you just go with the flow + # in a single request (i.e., by wrapping them all in a single root node), but if you just go with the flow # and accept Rails' defaults, life will be much easier. # # If you need to use a MIME type which isn't supported by default, you can register your own handlers in diff --git a/actionpack/lib/action_controller/mime_type.rb b/actionpack/lib/action_controller/mime_type.rb index f43e2ba06d..fa123f7808 100644 --- a/actionpack/lib/action_controller/mime_type.rb +++ b/actionpack/lib/action_controller/mime_type.rb @@ -104,7 +104,7 @@ module Mime list[text_xml].name = Mime::XML.to_s end - # Look for more specific xml-based types and sort them ahead of app/xml + # Look for more specific XML-based types and sort them ahead of app/xml if app_xml idx = app_xml @@ -158,7 +158,7 @@ module Mime end end - # Returns true if ActionPack should check requests using this Mime Type for possible request forgery. See + # Returns true if Action Pack should check requests using this Mime Type for possible request forgery. See # ActionController::RequestForgerProtection. def verify_request? !@@unverifiable_types.include?(to_sym) diff --git a/actionpack/lib/action_controller/polymorphic_routes.rb b/actionpack/lib/action_controller/polymorphic_routes.rb index e2b7716aa2..509fa6a08e 100644 --- a/actionpack/lib/action_controller/polymorphic_routes.rb +++ b/actionpack/lib/action_controller/polymorphic_routes.rb @@ -1,6 +1,6 @@ module ActionController # Polymorphic URL helpers are methods for smart resolution to a named route call when - # given an ActiveRecord model instance. They are to be used in combination with + # given an Active Record model instance. They are to be used in combination with # ActionController::Resources. # # These methods are useful when you want to generate correct URL or path to a RESTful @@ -9,7 +9,9 @@ module ActionController # Nested resources and/or namespaces are also supported, as illustrated in the example: # # polymorphic_url([:admin, @article, @comment]) - # #-> results in: + # + # results in: + # # admin_article_comment_url(@article, @comment) # # == Usage within the framework @@ -38,11 +40,8 @@ module ActionController # # Example usage: # - # edit_polymorphic_path(@post) - # #=> /posts/1/edit - # - # formatted_polymorphic_path([@post, :pdf]) - # #=> /posts/1.pdf + # edit_polymorphic_path(@post) # => "/posts/1/edit" + # formatted_polymorphic_path([@post, :pdf]) # => "/posts/1.pdf" module PolymorphicRoutes # Constructs a call to a named RESTful route for the given record and returns the # resulting URL string. For example: diff --git a/actionpack/lib/action_controller/rack_process.rb b/actionpack/lib/action_controller/rack_process.rb new file mode 100644 index 0000000000..f42212e740 --- /dev/null +++ b/actionpack/lib/action_controller/rack_process.rb @@ -0,0 +1,321 @@ +require 'action_controller/cgi_ext' +require 'action_controller/session/cookie_store' + +module ActionController #:nodoc: + class RackRequest < AbstractRequest #:nodoc: + attr_accessor :env, :session_options + + class SessionFixationAttempt < StandardError #:nodoc: + end + + DEFAULT_SESSION_OPTIONS = { + :database_manager => CGI::Session::CookieStore, # store data in cookie + :prefix => "ruby_sess.", # prefix session file names + :session_path => "/", # available to all paths in app + :session_key => "_session_id", + :cookie_only => true + } unless const_defined?(:DEFAULT_SESSION_OPTIONS) + + def initialize(env, session_options = DEFAULT_SESSION_OPTIONS) + @session_options = session_options + @env = env + @cgi = CGIWrapper.new(self) + super() + end + + # The request body is an IO input stream. If the RAW_POST_DATA environment + # variable is already set, wrap it in a StringIO. + def body + if raw_post = env['RAW_POST_DATA'] + StringIO.new(raw_post) + else + @env['rack.input'] + end + end + + def key?(key) + @env.key? key + end + + def query_parameters + @query_parameters ||= self.class.parse_query_parameters(query_string) + end + + def request_parameters + @request_parameters ||= parse_formatted_request_parameters + end + + def cookies + return {} unless @env["HTTP_COOKIE"] + + if @env["rack.request.cookie_string"] == @env["HTTP_COOKIE"] + @env["rack.request.cookie_hash"] + else + @env["rack.request.cookie_string"] = @env["HTTP_COOKIE"] + # According to RFC 2109: + # If multiple cookies satisfy the criteria above, they are ordered in + # the Cookie header such that those with more specific Path attributes + # precede those with less specific. Ordering with respect to other + # attributes (e.g., Domain) is unspecified. + @env["rack.request.cookie_hash"] = + parse_query(@env["rack.request.cookie_string"], ';,').inject({}) { |h, (k,v)| + h[k] = Array === v ? v.first : v + h + } + end + end + + def host_with_port_without_standard_port_handling + if forwarded = @env["HTTP_X_FORWARDED_HOST"] + forwarded.split(/,\s?/).last + elsif http_host = @env['HTTP_HOST'] + http_host + elsif server_name = @env['SERVER_NAME'] + server_name + else + "#{env['SERVER_ADDR']}:#{env['SERVER_PORT']}" + end + end + + def host + host_with_port_without_standard_port_handling.sub(/:\d+$/, '') + end + + def port + if host_with_port_without_standard_port_handling =~ /:(\d+)$/ + $1.to_i + else + standard_port + end + end + + def remote_addr + @env['REMOTE_ADDR'] + end + + def session + unless defined?(@session) + if @session_options == false + @session = Hash.new + else + stale_session_check! do + if cookie_only? && query_parameters[session_options_with_string_keys['session_key']] + raise SessionFixationAttempt + end + 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 + end + end + @session + end + + def reset_session + @session.delete if defined?(@session) && @session.is_a?(CGI::Session) + @session = new_session + end + + private + # Delete an old session if it exists then create a new one. + def new_session + if @session_options == false + Hash.new + else + CGI::Session.new(@cgi, session_options_with_string_keys.merge("new_session" => false)).delete rescue nil + CGI::Session.new(@cgi, session_options_with_string_keys.merge("new_session" => true)) + end + end + + def cookie_only? + session_options_with_string_keys['cookie_only'] + end + + def stale_session_check! + yield + rescue ArgumentError => argument_error + if argument_error.message =~ %r{undefined class/module ([\w:]*\w)} + begin + # Note that the regexp does not allow $1 to end with a ':' + $1.constantize + rescue LoadError, NameError => const_error + raise ActionController::SessionRestoreError, <<-end_msg +Session contains objects whose class definition isn\'t available. +Remember to require the classes for all objects kept in the session. +(Original exception: #{const_error.message} [#{const_error.class}]) +end_msg + end + + retry + else + raise + end + end + + def session_options_with_string_keys + @session_options_with_string_keys ||= DEFAULT_SESSION_OPTIONS.merge(@session_options).stringify_keys + end + + # From Rack::Utils + def parse_query(qs, d = '&;') + params = {} + (qs || '').split(/[#{d}] */n).inject(params) { |h,p| + k, v = unescape(p).split('=',2) + if cur = params[k] + if cur.class == Array + params[k] << v + else + params[k] = [cur, v] + end + else + params[k] = v + end + } + + return params + end + + def unescape(s) + s.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n){ + [$1.delete('%')].pack('H*') + } + end + end + + class RackResponse < AbstractResponse #:nodoc: + attr_accessor :status + + def initialize + @writer = lambda { |x| @body << x } + @block = nil + super() + end + + def out(output = $stdout, &block) + @block = block + normalize_headers(@headers) + if [204, 304].include?(@status.to_i) + @headers.delete "Content-Type" + [status.to_i, @headers.to_hash, []] + else + [status.to_i, @headers.to_hash, self] + end + end + alias to_a out + + def each(&callback) + if @body.respond_to?(:call) + @writer = lambda { |x| callback.call(x) } + @body.call(self, self) + else + @body.each(&callback) + end + + @writer = callback + @block.call(self) if @block + end + + def write(str) + @writer.call str.to_s + str + end + + def close + @body.close if @body.respond_to?(:close) + end + + def empty? + @block == nil && @body.empty? + end + + private + def normalize_headers(options = "text/html") + if options.is_a?(String) + headers['Content-Type'] = options unless headers['Content-Type'] + else + headers['Content-Length'] = options.delete('Content-Length').to_s if options['Content-Length'] + + headers['Content-Type'] = options.delete('type') || "text/html" + headers['Content-Type'] += "; charset=" + options.delete('charset') if options['charset'] + + headers['Content-Language'] = options.delete('language') if options['language'] + headers['Expires'] = options.delete('expires') if options['expires'] + + @status = options.delete('Status') if options['Status'] + @status ||= 200 + # Convert 'cookie' header to 'Set-Cookie' headers. + # Because Set-Cookie header can appear more the once in the response body, + # we store it in a line break separated string that will be translated to + # multiple Set-Cookie header by the handler. + if cookie = options.delete('cookie') + cookies = [] + + case cookie + when Array then cookie.each { |c| cookies << c.to_s } + when Hash then cookie.each { |_, c| cookies << c.to_s } + else cookies << cookie.to_s + end + + @output_cookies.each { |c| cookies << c.to_s } if @output_cookies + + headers['Set-Cookie'] = [headers['Set-Cookie'], cookies].compact.join("\n") + end + + options.each { |k,v| headers[k] = v } + end + + "" + end + end + + class CGIWrapper < ::CGI + def initialize(request, *args) + @request = request + @args = *args + @input = request.body + + super *args + end + + def params + @params ||= @request.params + end + + def cookies + @request.cookies + end + + def query_string + @request.query_string + end + + # Used to wrap the normal args variable used inside CGI. + def args + @args + end + + # Used to wrap the normal env_table variable used inside CGI. + def env_table + @request.env + end + + # Used to wrap the normal stdinput variable used inside CGI. + def stdinput + @input + end + end +end diff --git a/actionpack/lib/action_controller/request.rb b/actionpack/lib/action_controller/request.rb index d5ecbd9d29..914163a709 100755 --- a/actionpack/lib/action_controller/request.rb +++ b/actionpack/lib/action_controller/request.rb @@ -61,7 +61,7 @@ module ActionController request_method == :head end - # Provides acccess to the request's HTTP headers, for example: + # Provides access to the request's HTTP headers, for example: # request.headers["Content-Type"] # => "text/plain" def headers @headers ||= ActionController::Http::Headers.new(@env) @@ -231,7 +231,7 @@ EOM parts[0..-(tld_length+2)] end - # Return the query string, accounting for server idiosyncracies. + # Return the query string, accounting for server idiosyncrasies. def query_string if uri = @env['REQUEST_URI'] uri.split('?', 2)[1] || '' @@ -240,7 +240,7 @@ EOM end end - # Return the request URI, accounting for server idiosyncracies. + # Return the request URI, accounting for server idiosyncrasies. # WEBrick includes the full URL. IIS leaves REQUEST_URI blank. def request_uri if uri = @env['REQUEST_URI'] @@ -466,8 +466,8 @@ EOM parser.result end - def parse_multipart_form_parameters(body, boundary, content_length, env) - parse_request_parameters(read_multipart(body, boundary, content_length, env)) + def parse_multipart_form_parameters(body, boundary, body_size, env) + parse_request_parameters(read_multipart(body, boundary, body_size, env)) end def extract_multipart_boundary(content_type_with_parameters) @@ -519,7 +519,7 @@ EOM EOL = "\015\012" - def read_multipart(body, boundary, content_length, env) + def read_multipart(body, boundary, body_size, env) params = Hash.new([]) boundary = "--" + boundary quoted_boundary = Regexp.quote(boundary) @@ -529,8 +529,14 @@ EOM # start multipart/form-data body.binmode if defined? body.binmode + case body + when File + body.set_encoding(Encoding::BINARY) if body.respond_to?(:set_encoding) + when StringIO + body.string.force_encoding(Encoding::BINARY) if body.string.respond_to?(:force_encoding) + end boundary_size = boundary.size + EOL.size - content_length -= boundary_size + body_size -= boundary_size status = body.read(boundary_size) if nil == status raise EOFError, "no content body" @@ -541,7 +547,7 @@ EOM loop do head = nil content = - if 10240 < content_length + if 10240 < body_size UploadedTempfile.new("CGI") else UploadedStringIO.new @@ -563,24 +569,24 @@ EOM buf[0 ... (buf.size - (EOL + boundary + EOL).size)] = "" end - c = if bufsize < content_length + c = if bufsize < body_size body.read(bufsize) else - body.read(content_length) + body.read(body_size) end if c.nil? || c.empty? raise EOFError, "bad content body" end buf.concat(c) - content_length -= c.size + body_size -= c.size end buf = buf.sub(/\A((?:.|\n)*?)(?:[\r\n]{1,2})?#{quoted_boundary}([\r\n]{1,2}|--)/n) do content.print $1 if "--" == $2 - content_length = -1 + body_size = -1 end - boundary_end = $2.dup + boundary_end = $2.dup "" end @@ -607,7 +613,7 @@ EOM else params[name] = [content] end - break if content_length == -1 + break if body_size == -1 end raise EOFError, "bad boundary end of body part" unless boundary_end=~/--/ diff --git a/actionpack/lib/action_controller/request_forgery_protection.rb b/actionpack/lib/action_controller/request_forgery_protection.rb index 02c9d59d07..05a6d8bb79 100644 --- a/actionpack/lib/action_controller/request_forgery_protection.rb +++ b/actionpack/lib/action_controller/request_forgery_protection.rb @@ -17,7 +17,7 @@ module ActionController #:nodoc: # forged link from another site, is done by embedding a token based on the session (which an attacker wouldn't know) in all # forms and Ajax requests generated by Rails and then verifying the authenticity of that token in the controller. Only # HTML/JavaScript requests are checked, so this will not protect your XML API (presumably you'll have a different authentication - # scheme there anyway). Also, GET requests are not protected as these should be indempotent anyway. + # scheme there anyway). Also, GET requests are not protected as these should be idempotent anyway. # # This is turned on with the <tt>protect_from_forgery</tt> method, which will check the token and raise an # ActionController::InvalidAuthenticityToken if it doesn't match what was expected. You can customize the error message in diff --git a/actionpack/lib/action_controller/request_profiler.rb b/actionpack/lib/action_controller/request_profiler.rb index 8a18d194bd..a6471d0c08 100755 --- a/actionpack/lib/action_controller/request_profiler.rb +++ b/actionpack/lib/action_controller/request_profiler.rb @@ -17,13 +17,13 @@ module ActionController reset! end - def benchmark(n) + def benchmark(n, profiling = false) @quiet = true print ' ' result = Benchmark.realtime do n.times do |i| - run + run(profiling) print_progress(i) end end @@ -43,8 +43,15 @@ module ActionController script = File.read(script_path) source = <<-end_source - def run - #{script} + def run(profiling = false) + if profiling + RubyProf.resume do + #{script} + end + else + #{script} + end + old_request_count = request_count reset! self.request_count = old_request_count @@ -91,21 +98,22 @@ module ActionController def profile(sandbox) load_ruby_prof - results = RubyProf.profile { benchmark(sandbox) } + benchmark(sandbox, true) + results = RubyProf.stop show_profile_results results results end - def benchmark(sandbox) + def benchmark(sandbox, profiling = false) sandbox.request_count = 0 - elapsed = sandbox.benchmark(options[:n]).to_f + elapsed = sandbox.benchmark(options[:n], profiling).to_f count = sandbox.request_count.to_i puts '%.2f sec, %d requests, %d req/sec' % [elapsed, count, count / elapsed] end def warmup(sandbox) - Benchmark.realtime { sandbox.run } + Benchmark.realtime { sandbox.run(false) } end def default_options @@ -136,6 +144,7 @@ module ActionController protected def load_ruby_prof begin + gem 'ruby-prof', '>= 0.6.1' require 'ruby-prof' if mode = options[:measure] RubyProf.measure_mode = RubyProf.const_get(mode.upcase) diff --git a/actionpack/lib/action_controller/resources.rb b/actionpack/lib/action_controller/resources.rb index 26f75780c1..9fb1f9fa39 100644 --- a/actionpack/lib/action_controller/resources.rb +++ b/actionpack/lib/action_controller/resources.rb @@ -191,7 +191,7 @@ module ActionController # end # end # - # Along with the routes themselves, #resources generates named routes for use in + # Along with the routes themselves, +resources+ generates named routes for use in # controllers and views. <tt>map.resources :messages</tt> produces the following named routes and helpers: # # Named Route Helpers @@ -208,7 +208,7 @@ module ActionController # edit_message edit_message_url(id), hash_for_edit_message_url(id), # edit_message_path(id), hash_for_edit_message_path(id) # - # You can use these helpers instead of #url_for or methods that take #url_for parameters. For example: + # You can use these helpers instead of +url_for+ or methods that take +url_for+ parameters. For example: # # redirect_to :controller => 'messages', :action => 'index' # # and @@ -406,7 +406,7 @@ module ActionController # end # end # - # Along with the routes themselves, #resource generates named routes for + # Along with the routes themselves, +resource+ generates named routes for # use in controllers and views. <tt>map.resource :account</tt> produces # these named routes and helpers: # diff --git a/actionpack/lib/action_controller/routing/builder.rb b/actionpack/lib/action_controller/routing/builder.rb index b1a98d1a51..4740113ed0 100644 --- a/actionpack/lib/action_controller/routing/builder.rb +++ b/actionpack/lib/action_controller/routing/builder.rb @@ -23,9 +23,9 @@ module ActionController # 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. + # to be set separately, via the +assign_route_options+ method, and the + # <tt>optional?</tt> 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, [] diff --git a/actionpack/lib/action_controller/routing/segments.rb b/actionpack/lib/action_controller/routing/segments.rb index b142d18b47..864e068004 100644 --- a/actionpack/lib/action_controller/routing/segments.rb +++ b/actionpack/lib/action_controller/routing/segments.rb @@ -249,7 +249,7 @@ module ActionController end def extract_value - "#{local_name} = hash[:#{key}] && hash[:#{key}].collect { |path_component| URI.escape(path_component, ActionController::Routing::Segment::UNSAFE_PCHAR) }.to_param #{"|| #{default.inspect}" if default}" + "#{local_name} = hash[:#{key}] && hash[:#{key}].collect { |path_component| URI.escape(path_component.to_param, ActionController::Routing::Segment::UNSAFE_PCHAR) }.to_param #{"|| #{default.inspect}" if default}" end def default diff --git a/actionpack/lib/action_controller/session/cookie_store.rb b/actionpack/lib/action_controller/session/cookie_store.rb index ada1862c3e..b477c1f7da 100644 --- a/actionpack/lib/action_controller/session/cookie_store.rb +++ b/actionpack/lib/action_controller/session/cookie_store.rb @@ -34,7 +34,7 @@ require 'openssl' # to generate the HMAC message digest # such as 'MD5', 'RIPEMD160', 'SHA256', etc. # # To generate a secret key for an existing application, run -# `rake secret` and set the key in config/environment.rb. +# "rake secret" and set the key in config/environment.rb. # # Note that changing digest or secret invalidates all existing sessions! class CGI::Session::CookieStore diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 77c6f26eac..f26e65ba34 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -15,6 +15,27 @@ module ActionController end end + # Superclass for Action Controller functional tests. Infers the controller under test from the test class name, + # and creates @controller, @request, @response instance variables. + # + # class WidgetsControllerTest < ActionController::TestCase + # def test_index + # get :index + # end + # end + # + # * @controller - WidgetController.new + # * @request - ActionController::TestRequest.new + # * @response - ActionController::TestResponse.new + # + # (Earlier versions of Rails required each functional test to subclass Test::Unit::TestCase and define + # @controller, @request, @response in +setup+.) + # + # If the controller cannot be inferred from the test class name, you can explicity set it with +tests+. + # + # class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase + # tests WidgetController + # end class TestCase < ActiveSupport::TestCase # When the request.remote_addr remains the default for testing, which is 0.0.0.0, the exception is simply raised inline # (bystepping the regular exception handling from rescue_action). If the request.remote_addr is anything else, the regular @@ -41,6 +62,8 @@ module ActionController @@controller_class = nil class << self + # Sets the controller class name. Useful if the name can't be inferred from test class. + # Expects +controller_class+ as a constant. Example: <tt>tests WidgetController</tt>. def tests(controller_class) self.controller_class = controller_class end diff --git a/actionpack/lib/action_controller/test_process.rb b/actionpack/lib/action_controller/test_process.rb index dcb6cdf4ca..f179d9b1c7 100644 --- a/actionpack/lib/action_controller/test_process.rb +++ b/actionpack/lib/action_controller/test_process.rb @@ -3,7 +3,7 @@ require 'action_controller/test_case' module ActionController #:nodoc: class Base - # Process a test request called with a +TestRequest+ object. + # Process a test request called with a TestRequest object. def self.process_test(request) new.process_test(request) end @@ -49,7 +49,7 @@ module ActionController #:nodoc: # Either the RAW_POST_DATA environment variable or the URL-encoded request # parameters. def raw_post - env['RAW_POST_DATA'] ||= url_encoded_request_parameters + env['RAW_POST_DATA'] ||= returning(url_encoded_request_parameters) { |b| b.force_encoding(Encoding::BINARY) if b.respond_to?(:force_encoding) } end def port=(number) @@ -222,7 +222,7 @@ module ActionController #:nodoc: !rendered_file.nil? end - # A shortcut to the flash. Returns an empyt hash if no session flash exists. + # A shortcut to the flash. Returns an empty hash if no session flash exists. def flash session['flash'] || {} end @@ -340,6 +340,7 @@ module ActionController #:nodoc: @content_type = content_type @original_filename = path.sub(/^.*#{File::SEPARATOR}([^#{File::SEPARATOR}]+)$/) { $1 } @tempfile = Tempfile.new(@original_filename) + @tempfile.set_encoding(Encoding::BINARY) if @tempfile.respond_to?(:set_encoding) @tempfile.binmode if binary FileUtils.copy_file(path, @tempfile.path) end @@ -357,7 +358,7 @@ module ActionController #:nodoc: module TestProcess def self.included(base) - # execute the request simulating a specific http method and set/volley the response + # execute the request simulating a specific HTTP method and set/volley the response %w( get post put delete head ).each do |method| base.class_eval <<-EOV, __FILE__, __LINE__ def #{method}(action, parameters = nil, session = nil, flash = nil) diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb index 1a3c770254..376bb87409 100644 --- a/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb +++ b/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb @@ -64,7 +64,7 @@ module HTML # # When using a combination of the above, the element name comes first # followed by identifier, class names, attributes, pseudo classes and - # negation in any order. Do not seprate these parts with spaces! + # negation in any order. Do not separate these parts with spaces! # Space separation is used for descendant selectors. # # For example: @@ -158,7 +158,7 @@ module HTML # * <tt>:not(selector)</tt> -- Match the element only if the element does not # match the simple selector. # - # As you can see, <tt>:nth-child<tt> pseudo class and its varient can get quite + # As you can see, <tt>:nth-child<tt> pseudo class and its variant can get quite # tricky and the CSS specification doesn't do a much better job explaining it. # But after reading the examples and trying a few combinations, it's easy to # figure out. diff --git a/actionpack/lib/action_pack/version.rb b/actionpack/lib/action_pack/version.rb index 70fc1ced8c..c67654d9a8 100644 --- a/actionpack/lib/action_pack/version.rb +++ b/actionpack/lib/action_pack/version.rb @@ -1,8 +1,8 @@ module ActionPack #:nodoc: module VERSION #:nodoc: MAJOR = 2 - MINOR = 0 - TINY = 991 + MINOR = 1 + TINY = 0 STRING = [MAJOR, MINOR, TINY].join('.') end diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index 4840b2526d..c236666dcd 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -168,12 +168,12 @@ module ActionView #:nodoc: # Specify whether file modification times should be checked to see if a template needs recompilation @@cache_template_loading = false cattr_accessor :cache_template_loading - - # Specify whether file extension lookup should be cached, and whether template base path lookup should be cached. - # Should be +false+ for development environments. Defaults to +true+. - @@cache_template_extensions = true - cattr_accessor :cache_template_extensions + def self.cache_template_extensions=(*args) + ActiveSupport::Deprecation.warn("config.action_view.cache_template_extensions option has been deprecated and has no effect. " << + "Please remove it from your config files.", caller) + end + # Specify whether RJS responses should be wrapped in a try/catch block # that alert()s the caught exception (and then re-raises it). @@debug_rjs = false diff --git a/actionpack/lib/action_view/compiled_templates.rb b/actionpack/lib/action_view/compiled_templates.rb deleted file mode 100644 index 5a286432e3..0000000000 --- a/actionpack/lib/action_view/compiled_templates.rb +++ /dev/null @@ -1,69 +0,0 @@ -module ActionView - - # CompiledTemplates modules hold methods that have been compiled. - # Templates are compiled into these methods so that they do not need to be - # read and parsed for each request. - # - # Each template may be compiled into one or more methods. Each method accepts a given - # set of parameters which is used to implement local assigns passing. - # - # To use a compiled template module, create a new instance and include it into the class - # in which you want the template to be rendered. - class CompiledTemplates < Module - attr_reader :method_names - - def initialize - @method_names = Hash.new do |hash, key| - hash[key] = "__compiled_method_#{(hash.length + 1)}" - end - @mtimes = {} - end - - # Return the full key for the given identifier and argument names - def full_key(identifier, arg_names) - [identifier, arg_names] - end - - # Return the selector for this method or nil if it has not been compiled - def selector(identifier, arg_names) - key = full_key(identifier, arg_names) - method_names.key?(key) ? method_names[key] : nil - end - alias :compiled? :selector - - # Return the time at which the method for the given identifier and argument names was compiled. - def mtime(identifier, arg_names) - @mtimes[full_key(identifier, arg_names)] - end - - # Compile the provided source code for the given argument names and with the given initial line number. - # The identifier should be unique to this source. - # - # The file_name, if provided will appear in backtraces. If not provided, the file_name defaults - # to the identifier. - # - # This method will return the selector for the compiled version of this method. - def compile_source(identifier, arg_names, source, initial_line_number = 0, file_name = nil) - file_name ||= identifier - name = method_names[full_key(identifier, arg_names)] - arg_desc = arg_names.empty? ? '' : "(#{arg_names * ', '})" - fake_file_name = "#{file_name}#{arg_desc}" # Include the arguments for this version (for now) - - method_def = wrap_source(name, arg_names, source) - - begin - module_eval(method_def, fake_file_name, initial_line_number) - @mtimes[full_key(identifier, arg_names)] = Time.now - rescue Exception => e # errors from compiled source - e.blame_file! identifier - raise - end - name - end - - # Wrap the provided source in a def ... end block. - def wrap_source(name, arg_names, source) - "def #{name}(#{arg_names * ', '})\n#{source}\nend" - end - end -end diff --git a/actionpack/lib/action_view/helpers/active_record_helper.rb b/actionpack/lib/action_view/helpers/active_record_helper.rb index f3f204cc97..e788ebf359 100644 --- a/actionpack/lib/action_view/helpers/active_record_helper.rb +++ b/actionpack/lib/action_view/helpers/active_record_helper.rb @@ -141,7 +141,7 @@ module ActionView # # error_messages_for 'user_common', 'user', :object_name => 'user' # - # If the objects cannot be located as instance variables, you can add an extra <tt>:object</tt> paremeter which gives the actual + # If the objects cannot be located as instance variables, you can add an extra <tt>:object</tt> parameter which gives the actual # object (or array of objects to use): # # error_messages_for 'user', :object => @question.user diff --git a/actionpack/lib/action_view/helpers/asset_tag_helper.rb b/actionpack/lib/action_view/helpers/asset_tag_helper.rb index dfc7e2b3ed..e5a95a961c 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb @@ -11,8 +11,8 @@ module ActionView # === Using asset hosts # By default, Rails links to these assets on the current host in the public # folder, but you can direct Rails to link to assets from a dedicated assets server by - # setting ActionController::Base.asset_host in your environment.rb. For example, - # let's say your asset host is assets.example.com. + # setting ActionController::Base.asset_host in your <tt>config/environment.rb</tt>. For example, + # let's say your asset host is <tt>assets.example.com</tt>. # # ActionController::Base.asset_host = "assets.example.com" # image_tag("rails.png") @@ -22,8 +22,8 @@ module ActionView # # This is useful since browsers typically open at most two connections to a single host, # which means your assets often wait in single file for their turn to load. You can - # alleviate this by using a %d wildcard in <tt>asset_host</tt> (for example, "assets%d.example.com") - # to automatically distribute asset requests among four hosts (e.g., assets0.example.com through assets3.example.com) + # alleviate this by using a <tt>%d</tt> wildcard in <tt>asset_host</tt> (for example, "assets%d.example.com") + # to automatically distribute asset requests among four hosts (e.g., "assets0.example.com" through "assets3.example.com") # so browsers will open eight connections rather than two. # # image_tag("rails.png") @@ -293,9 +293,9 @@ module ActionView end # Computes the path to a stylesheet asset in the public stylesheets directory. - # If the +source+ filename has no extension, .css will be appended. + # If the +source+ filename has no extension, <tt>.css</tt> will be appended. # Full paths from the document root will be passed through. - # Used internally by stylesheet_link_tag to build the stylesheet path. + # Used internally by +stylesheet_link_tag+ to build the stylesheet path. # # ==== Examples # stylesheet_path "style" # => /stylesheets/style.css @@ -309,7 +309,7 @@ module ActionView alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route # Returns a stylesheet link tag for the sources specified as arguments. If - # you don't specify an extension, .css will be appended automatically. + # you don't specify an extension, <tt>.css</tt> will be appended automatically. # You can modify the link attributes by passing a hash as the last argument. # # ==== Examples @@ -379,7 +379,7 @@ module ActionView # 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. + # Used internally by +image_tag+ to build the image path. # # ==== Examples # image_path("edit") # => /images/edit @@ -454,8 +454,8 @@ module ActionView end end - # Add the .ext if not present. Return full URLs otherwise untouched. - # Prefix with /dir/ if lacking a leading /. Account for relative URL + # Add the the extension +ext+ if not present. Return full URLs otherwise untouched. + # Prefix with <tt>/dir/</tt> if lacking a leading +/+. Account for relative URL # roots. Rewrite the asset path for cache-busting asset ids. Include # asset host, if configured, with the correct request protocol. def compute_public_path(source, dir, ext = nil, include_host = true) @@ -502,9 +502,9 @@ module ActionView end end - # Pick an asset host for this source. Returns nil if no host is set, + # Pick an asset host for this source. Returns +nil+ if no host is set, # the host if no wildcard is set, the host interpolated with the - # numbers 0-3 if it contains %d (the number is the source hash mod 4), + # numbers 0-3 if it contains <tt>%d</tt> (the number is the source hash mod 4), # or the value returned from invoking the proc if it's a proc. def compute_asset_host(source) if host = ActionController::Base.asset_host diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index 8a9c8044ae..7ed6272898 100755 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -689,7 +689,7 @@ module ActionView default[key] ||= time.send(key) end - Time.utc(default[:year], default[:month], default[:day], default[:hour], default[:min], default[:sec]) + Time.utc_time(default[:year], default[:month], default[:day], default[:hour], default[:min], default[:sec]) end end end diff --git a/actionpack/lib/action_view/helpers/debug_helper.rb b/actionpack/lib/action_view/helpers/debug_helper.rb index 20de7e465f..ea70a697de 100644 --- a/actionpack/lib/action_view/helpers/debug_helper.rb +++ b/actionpack/lib/action_view/helpers/debug_helper.rb @@ -2,21 +2,28 @@ module ActionView module Helpers # Provides a set of methods for making it easier to debug Rails objects. module DebugHelper - # Returns a <pre>-tag that has +object+ dumped by YAML. This creates a very - # readable way to inspect an object. + # Returns a YAML representation of +object+ wrapped with <pre> and </pre>. + # If the object cannot be converted to YAML using +to_yaml+, +inspect+ will be called instead. + # Useful for inspecting an object at the time of rendering. # # ==== Example - # my_hash = {'first' => 1, 'second' => 'two', 'third' => [1,2,3]} - # debug(my_hash) # - # => <pre class='debug_dump'>--- - # first: 1 - # second: two - # third: - # - 1 - # - 2 - # - 3 - # </pre> + # @user = User.new({ :username => 'testing', :password => 'xyz', :age => 42}) %> + # debug(@user) + # # => + # <pre class='debug_dump'>--- !ruby/object:User + # attributes: + # updated_at: + # username: testing + # + # age: 42 + # password: xyz + # created_at: + # attributes_cache: {} + # + # new_record: true + # </pre> + def debug(object) begin Marshal::dump(object) @@ -28,4 +35,4 @@ module ActionView end end end -end
\ No newline at end of file +end diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb index b8600fe445..7d85799038 100644 --- a/actionpack/lib/action_view/helpers/form_helper.rb +++ b/actionpack/lib/action_view/helpers/form_helper.rb @@ -73,30 +73,81 @@ module ActionView # There are also methods for helping to build form tags in link:classes/ActionView/Helpers/FormOptionsHelper.html, # link:classes/ActionView/Helpers/DateHelper.html, and link:classes/ActionView/Helpers/ActiveRecordHelper.html module FormHelper - # Creates a form and a scope around a specific model object that is used as a base for questioning about - # values for the fields. + # Creates a form and a scope around a specific model object that is used as + # a base for questioning about values for the fields. # - # <% form_for :person, @person, :url => { :action => "update" } do |f| %> + # Rails provides succinct resource-oriented form generation with +form_for+ + # like this: + # + # <% form_for @offer do |f| %> + # <%= f.label :version, 'Version' %>: + # <%= f.text_field :version %><br /> + # <%= f.label :author, 'Author' %>: + # <%= f.text_field :author %><br /> + # <% end %> + # + # There, +form_for+ is able to generate the rest of RESTful form parameters + # based on introspection on the record, but to understand what it does we + # need to dig first into the alternative generic usage it is based upon. + # + # === Generic form_for + # + # The generic way to call +form_for+ yields a form builder around a model: + # + # <% form_for :person, :url => { :action => "update" } do |f| %> # <%= f.error_messages %> - # First name: <%= f.text_field :first_name %> - # Last name : <%= f.text_field :last_name %> - # Biography : <%= f.text_area :biography %> - # Admin? : <%= f.check_box :admin %> + # First name: <%= f.text_field :first_name %><br /> + # Last name : <%= f.text_field :last_name %><br /> + # Biography : <%= f.text_area :biography %><br /> + # Admin? : <%= f.check_box :admin %><br /> # <% end %> # - # Worth noting is that the form_for tag is called in a ERb evaluation block, not an ERb output block. So that's <tt><% %></tt>, - # not <tt><%= %></tt>. Also worth noting is that form_for yields a <tt>form_builder</tt> object, in this example as <tt>f</tt>, which emulates - # the API for the stand-alone FormHelper methods, but without the object name. So instead of <tt>text_field :person, :name</tt>, - # you get away with <tt>f.text_field :name</tt>. Notice that you can even do <tt><%= f.error_messages %></tt> to display the - # error messsages of the model object in question. + # There, the first argument is a symbol or string with the name of the + # object the form is about, and also the name of the instance variable the + # object is stored in. + # + # The form builder acts as a regular form helper that somehow carries the + # model. Thus, the idea is that + # + # <%= f.text_field :first_name %> + # + # gets expanded to # - # Even further, the form_for method allows you to more easily escape the instance variable convention. So while the stand-alone - # approach would require <tt>text_field :person, :name, :object => person</tt> - # to work with local variables instead of instance ones, the form_for calls remain the same. You simply declare once with - # <tt>:person, person</tt> and all subsequent field calls save <tt>:person</tt> and <tt>:object => person</tt>. + # <%= text_field :person, :first_name %> + # + # If the instance variable is not <tt>@person</tt> you can pass the actual + # record as the second argument: + # + # <% form_for :person, person, :url => { :action => "update" } do |f| %> + # ... + # <% end %> # - # Also note that form_for doesn't create an exclusive scope. It's still possible to use both the stand-alone FormHelper methods - # and methods from FormTagHelper. For example: + # In that case you can think + # + # <%= f.text_field :first_name %> + # + # gets expanded to + # + # <%= text_field :person, :first_name, :object => person %> + # + # You can even display error messages of the wrapped model this way: + # + # <%= f.error_messages %> + # + # In any of its variants, the rightmost argument to +form_for+ is an + # optional hash of options: + # + # * <tt>:url</tt> - The URL the form is submitted to. It takes the same fields + # you pass to +url_for+ or +link_to+. In particular you may pass here a + # named route directly as well. Defaults to the current action. + # * <tt>:html</tt> - Optional HTML attributes for the form tag. + # + # Worth noting is that the +form_for+ tag is called in a ERb evaluation block, + # not an ERb output block. So that's <tt><% %></tt>, not <tt><%= %></tt>. + # + # Also note that +form_for+ doesn't create an exclusive scope. It's still + # possible to use both the stand-alone FormHelper methods and methods from + # FormTagHelper. For example: # # <% form_for :person, @person, :url => { :action => "update" } do |f| %> # First name: <%= f.text_field :first_name %> @@ -105,42 +156,38 @@ module ActionView # Admin? : <%= check_box_tag "person[admin]", @person.company.admin? %> # <% end %> # - # Note: This also works for the methods in FormOptionHelper and DateHelper that are designed to work with an object as base, - # like FormOptionHelper#collection_select and DateHelper#datetime_select. - # - # HTML attributes for the form tag can be given as <tt>:html => {...}</tt>. For example: - # - # <% form_for :person, @person, :html => {:id => 'person_form'} do |f| %> - # ... - # <% end %> + # This also works for the methods in FormOptionHelper and DateHelper that are + # designed to work with an object as base, like FormOptionHelper#collection_select + # and DateHelper#datetime_select. # - # The above form will then have the <tt>id</tt> attribute with the value </tt>person_form</tt>, which you can then - # style with CSS or manipulate with JavaScript. + # === Resource-oriented style # - # === Relying on record identification + # As we said above, in addition to manually configuring the +form_for+ call, + # you can rely on automated resource identification, which will use the conventions + # and named routes of that approach. This is the preferred way to use +form_for+ + # nowadays. # - # In addition to manually configuring the form_for call, you can also rely on record identification, which will use - # the conventions and named routes of that approach. Examples: + # For example, if <tt>@post</tt> is an existing record you want to edit # - # <% form_for(@post) do |f| %> + # <% form_for @post do |f| %> # ... # <% end %> # - # This will expand to be the same as: + # is equivalent to something like: # # <% form_for :post, @post, :url => post_path(@post), :html => { :method => :put, :class => "edit_post", :id => "edit_post_45" } do |f| %> # ... # <% end %> # - # And for new records: + # And for new records # # <% form_for(Post.new) do |f| %> # ... # <% end %> # - # This will expand to be the same as: + # expands to # - # <% form_for :post, @post, :url => posts_path, :html => { :class => "new_post", :id => "new_post" } do |f| %> + # <% form_for :post, Post.new, :url => posts_path, :html => { :class => "new_post", :id => "new_post" } do |f| %> # ... # <% end %> # @@ -150,7 +197,7 @@ module ActionView # ... # <% end %> # - # And for namespaced routes, like admin_post_url: + # And for namespaced routes, like +admin_post_url+: # # <% form_for([:admin, @post]) do |f| %> # ... @@ -277,13 +324,13 @@ module ActionView # # ==== Examples # label(:post, :title) - # #=> <label for="post_title">Title</label> + # # => <label for="post_title">Title</label> # # label(:post, :title, "A short title") - # #=> <label for="post_title">A short title</label> + # # => <label for="post_title">A short title</label> # # label(:post, :title, "A short title", :class => "title_label") - # #=> <label for="post_title" class="title_label">A short title</label> + # # => <label for="post_title" class="title_label">A short title</label> # def label(object_name, method, text = nil, options = {}) InstanceTag.new(object_name, method, self, nil, options.delete(:object)).to_label_tag(text, options) @@ -588,6 +635,8 @@ module ActionView value != 0 when String value == checked_value + when Array + value.include?(checked_value) else value.to_i != 0 end diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb index bf65fe5574..c0cba24be4 100644 --- a/actionpack/lib/action_view/helpers/form_options_helper.rb +++ b/actionpack/lib/action_view/helpers/form_options_helper.rb @@ -119,7 +119,7 @@ module ActionView # end # end # - # Sample usage (selecting the associated +Author+ for an instance of +Post+, <tt>@post</tt>): + # Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>): # collection_select(:post, :author_id, Author.find(:all), :id, :name_with_initial, {:prompt => true}) # # If <tt>@post.author_id</tt> is already <tt>1</tt>, this would return: @@ -144,10 +144,16 @@ module ActionView # In addition to the <tt>:include_blank</tt> option documented above, # this method also supports a <tt>:model</tt> option, which defaults # to TimeZone. This may be used by users to specify a different time - # zone model object. (See #time_zone_options_for_select for more + # zone model object. (See +time_zone_options_for_select+ for more # information.) + # + # You can also supply an array of TimeZone objects + # as +priority_zones+, so that they will be listed above the rest of the + # (long) list. (You can use TimeZone.us_zones as a convenience for + # obtaining a list of the US time zones.) + # # Finally, this method supports a <tt>:default</tt> option, which selects - # a default TimeZone if the object's time zone is nil. + # a default TimeZone if the object's time zone is +nil+. # # Examples: # time_zone_select( "user", "time_zone", nil, :include_blank => true) @@ -156,6 +162,8 @@ module ActionView # # time_zone_select( "user", 'time_zone', TimeZone.us_zones, :default => "Pacific Time (US & Canada)") # + # time_zone_select( "user", 'time_zone', [ TimeZone['Alaska'], TimeZone['Hawaii'] ]) + # # time_zone_select( "user", "time_zone", TZInfo::Timezone.all.sort, :model => TZInfo::Timezone) def time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {}) InstanceTag.new(object, method, self, nil, options.delete(:object)).to_time_zone_select_tag(priority_zones, options, html_options) @@ -164,7 +172,7 @@ module ActionView # Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. Given a container # where the elements respond to first and last (such as a two-element array), the "lasts" serve as option values and # the "firsts" as option text. Hashes are turned into this form automatically, so the keys become "firsts" and values - # become lasts. If +selected+ is specified, the matching "last" or element will get the selected option-tag. +Selected+ + # become lasts. If +selected+ is specified, the matching "last" or element will get the selected option-tag. +selected+ # may also be an array of values to be selected when using a multiple select. # # Examples (call, result): @@ -209,24 +217,22 @@ module ActionView options_for_select(options, selected) end - # Returns a string of <tt><option></tt> tags, like <tt>#options_from_collection_for_select</tt>, but + # Returns a string of <tt><option></tt> tags, like <tt>options_from_collection_for_select</tt>, but # groups them by <tt><optgroup></tt> tags based on the object relationships of the arguments. # # Parameters: - # +collection+:: An array of objects representing the <tt><optgroup></tt> tags - # +group_method+:: The name of a method which, when called on a member of +collection+, returns an - # array of child objects representing the <tt><option></tt> tags - # +group_label_method+:: The name of a method which, when called on a member of +collection+, returns a - # string to be used as the +label+ attribute for its <tt><optgroup></tt> tag - # +option_key_method+:: The name of a method which, when called on a child object of a member of - # +collection+, returns a value to be used as the +value+ attribute for its - # <tt><option></tt> tag - # +option_value_method+:: The name of a method which, when called on a child object of a member of - # +collection+, returns a value to be used as the contents of its - # <tt><option></tt> tag - # +selected_key+:: A value equal to the +value+ attribute for one of the <tt><option></tt> tags, - # which will have the +selected+ attribute set. Corresponds to the return value - # of one of the calls to +option_key_method+. If +nil+, no selection is made. + # * +collection+ - An array of objects representing the <tt><optgroup></tt> tags. + # * +group_method+ - The name of a method which, when called on a member of +collection+, returns an + # array of child objects representing the <tt><option></tt> tags. + # * group_label_method+ - The name of a method which, when called on a member of +collection+, returns a + # string to be used as the +label+ attribute for its <tt><optgroup></tt> tag. + # * +option_key_method+ - The name of a method which, when called on a child object of a member of + # +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag. + # * +option_value_method+ - The name of a method which, when called on a child object of a member of + # +collection+, returns a value to be used as the contents of its <tt><option></tt> tag. + # * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags, + # which will have the +selected+ attribute set. Corresponds to the return value of one of the calls + # to +option_key_method+. If +nil+, no selection is made. # # Example object structure for use with this method: # class Continent < ActiveRecord::Base @@ -265,9 +271,11 @@ module ActionView end end - # Returns a string of option tags for pretty much any country in the world. Supply a country name as +selected+ to - # have it marked as the selected option tag. You can also supply an array of countries as +priority_countries+, so - # that they will be listed above the rest of the (long) list. + # Returns a string of option tags for most countries in the + # world (as defined in COUNTRIES). Supply a country name as + # +selected+ to have it marked as the selected option tag. You + # can also supply an array of countries as +priority_countries+, + # so that they will be listed above the rest of the (long) list. # # NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag. def country_options_for_select(selected = nil, priority_countries = nil) @@ -292,8 +300,8 @@ module ActionView # a TimeZone. # # By default, +model+ is the TimeZone constant (which can be obtained - # in ActiveRecord as a value object). The only requirement is that the - # +model+ parameter be an object that responds to #all, and returns + # in Active Record as a value object). The only requirement is that the + # +model+ parameter be an object that responds to +all+, and returns # an array of objects that represent time zones. # # NOTE: Only the option tags are returned, you have to wrap this call in diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb index 922a0662fe..ca58f4ba26 100644 --- a/actionpack/lib/action_view/helpers/form_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb @@ -3,7 +3,7 @@ require 'action_view/helpers/tag_helper' module ActionView module Helpers - # Provides a number of methods for creating form tags that doesn't rely on an ActiveRecord object assigned to the template like + # Provides a number of methods for creating form tags that doesn't rely on an Active Record object assigned to the template like # FormHelper does. Instead, you provide the names and values manually. # # NOTE: The HTML options <tt>disabled</tt>, <tt>readonly</tt>, and <tt>multiple</tt> can all be treated as booleans. So specifying @@ -14,9 +14,9 @@ module ActionView # # ==== Options # * <tt>:multipart</tt> - If set to true, the enctype is set to "multipart/form-data". - # * <tt>:method</tt> - 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. + # * <tt>:method</tt> - 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 <tt>_method</tt> + # is added to simulate the verb over post. # * A list of parameters to feed to the URL the form will be posted to. # # ==== Examples diff --git a/actionpack/lib/action_view/helpers/javascript_helper.rb b/actionpack/lib/action_view/helpers/javascript_helper.rb index 1ea3cbd74e..ed931e064f 100644 --- a/actionpack/lib/action_view/helpers/javascript_helper.rb +++ b/actionpack/lib/action_view/helpers/javascript_helper.rb @@ -43,14 +43,23 @@ module ActionView end include PrototypeHelper - - # Returns a link that will trigger a JavaScript +function+ using the + + # Returns a link of the given +name+ that will trigger a JavaScript +function+ using the # onclick handler and return false after the fact. # + # The first argument +name+ is used as the link text. + # + # The next arguments are optional and may include the javascript function definition and a hash of html_options. + # # 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). # + # The +html_options+ will accept a hash of html attributes for the link tag. Some examples are :class => "nav_button", :id => "articles_nav_button" + # + # Note: if you choose to specify the javascript function in a block, but would like to pass html_options, set the +function+ parameter to nil + # + # # Examples: # link_to_function "Greeting", "alert('Hello world!')" # Produces: @@ -94,13 +103,21 @@ module ActionView ) end - # Returns a button that'll trigger a JavaScript +function+ using the + # Returns a button with the given +name+ text that'll trigger a JavaScript +function+ using the # onclick handler. # + # The first argument +name+ is used as the button's value or display text. + # + # The next arguments are optional and may include the javascript function definition and a hash of html_options. + # # 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). # + # The +html_options+ will accept a hash of html attributes for the link tag. Some examples are :class => "nav_button", :id => "articles_nav_button" + # + # Note: if you choose to specify the javascript function in a block, but would like to pass html_options, set the +function+ parameter to nil + # # Examples: # button_to_function "Greeting", "alert('Hello world!')" # button_to_function "Delete", "if (confirm('Really?')) do_delete()" diff --git a/actionpack/lib/action_view/helpers/prototype_helper.rb b/actionpack/lib/action_view/helpers/prototype_helper.rb index 1a0e660d52..c731824f18 100644 --- a/actionpack/lib/action_view/helpers/prototype_helper.rb +++ b/actionpack/lib/action_view/helpers/prototype_helper.rb @@ -61,7 +61,7 @@ module ActionView # # == Designing your Rails actions for Ajax # When building your action handlers (that is, the Rails actions that receive your background requests), it's - # important to remember a few things. First, whatever your action would normall return to the browser, it will + # important to remember a few things. First, whatever your action would normally return to the browser, it will # return to the Ajax call. As such, you typically don't want to render with a layout. This call will cause # the layout to be transmitted back to your page, and, if you have a full HTML/CSS, will likely mess a lot of things up. # You can turn the layout off on particular actions by doing the following: @@ -595,8 +595,8 @@ module ActionView # JavaScript sent with a Content-type of "text/javascript". # # Create new instances with PrototypeHelper#update_page or with - # ActionController::Base#render, then call #insert_html, #replace_html, - # #remove, #show, #hide, #visual_effect, or any other of the built-in + # ActionController::Base#render, then call +insert_html+, +replace_html+, + # +remove+, +show+, +hide+, +visual_effect+, or any other of the built-in # methods on the yielded generator in any order you like to modify the # content and appearance of the current page. # @@ -687,7 +687,7 @@ module ActionView end end - # Returns an object whose <tt>#to_json</tt> evaluates to +code+. Use this to pass a literal JavaScript + # Returns an object whose <tt>to_json</tt> 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) @@ -1068,7 +1068,7 @@ module ActionView def build_observer(klass, name, options = {}) if options[:with] && (options[:with] !~ /[\{=(.]/) - options[:with] = "'#{options[:with]}=' + value" + options[:with] = "'#{options[:with]}=' + encodeURIComponent(value)" else options[:with] ||= 'value' unless options[:function] end @@ -1173,7 +1173,7 @@ module ActionView super(generator) end - # The JSON Encoder calls this to check for the #to_json method + # The JSON Encoder calls this to check for the +to_json+ method # Since it's a blank slate object, I suppose it responds to anything. def respond_to?(method) true diff --git a/actionpack/lib/action_view/helpers/record_tag_helper.rb b/actionpack/lib/action_view/helpers/record_tag_helper.rb index 40b66be79f..66c596f3a9 100644 --- a/actionpack/lib/action_view/helpers/record_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/record_tag_helper.rb @@ -2,7 +2,7 @@ module ActionView module Helpers module RecordTagHelper # Produces a wrapper DIV element with id and class parameters that - # relate to the specified ActiveRecord object. Usage example: + # relate to the specified Active Record object. Usage example: # # <% div_for(@person, :class => "foo") do %> # <%=h @person.name %> @@ -17,7 +17,7 @@ module ActionView end # content_tag_for creates an HTML element with id and class parameters - # that relate to the specified ActiveRecord object. For example: + # that relate to the specified Active Record object. For example: # # <% content_tag_for(:tr, @person) do %> # <td><%=h @person.first_name %></td> diff --git a/actionpack/lib/action_view/helpers/sanitize_helper.rb b/actionpack/lib/action_view/helpers/sanitize_helper.rb index 6c0a7ec25c..c3c03394ee 100644 --- a/actionpack/lib/action_view/helpers/sanitize_helper.rb +++ b/actionpack/lib/action_view/helpers/sanitize_helper.rb @@ -57,7 +57,7 @@ module ActionView self.class.white_list_sanitizer.sanitize(html, options) end - # Sanitizes a block of css code. Used by #sanitize when it comes across a style attribute + # Sanitizes a block of CSS code. Used by +sanitize+ when it comes across a style attribute. def sanitize_css(style) self.class.white_list_sanitizer.sanitize_css(style) end @@ -111,8 +111,8 @@ module ActionView end end - # Gets the HTML::FullSanitizer instance used by strip_tags. Replace with - # any object that responds to #sanitize + # Gets the HTML::FullSanitizer instance used by +strip_tags+. Replace with + # any object that responds to +sanitize+. # # Rails::Initializer.run do |config| # config.action_view.full_sanitizer = MySpecialSanitizer.new @@ -122,8 +122,8 @@ module ActionView @full_sanitizer ||= HTML::FullSanitizer.new end - # Gets the HTML::LinkSanitizer instance used by strip_links. Replace with - # any object that responds to #sanitize + # Gets the HTML::LinkSanitizer instance used by +strip_links+. Replace with + # any object that responds to +sanitize+. # # Rails::Initializer.run do |config| # config.action_view.link_sanitizer = MySpecialSanitizer.new @@ -133,8 +133,8 @@ module ActionView @link_sanitizer ||= HTML::LinkSanitizer.new end - # Gets the HTML::WhiteListSanitizer instance used by sanitize and sanitize_css. - # Replace with any object that responds to #sanitize + # Gets the HTML::WhiteListSanitizer instance used by sanitize and +sanitize_css+. + # Replace with any object that responds to +sanitize+. # # Rails::Initializer.run do |config| # config.action_view.white_list_sanitizer = MySpecialSanitizer.new @@ -144,7 +144,7 @@ module ActionView @white_list_sanitizer ||= HTML::WhiteListSanitizer.new end - # Adds valid HTML attributes that the #sanitize helper checks for URIs. + # Adds valid HTML attributes that the +sanitize+ helper checks for URIs. # # Rails::Initializer.run do |config| # config.action_view.sanitized_uri_attributes = 'lowsrc', 'target' @@ -154,7 +154,7 @@ module ActionView HTML::WhiteListSanitizer.uri_attributes.merge(attributes) end - # Adds to the Set of 'bad' tags for the #sanitize helper. + # Adds to the Set of 'bad' tags for the +sanitize+ helper. # # Rails::Initializer.run do |config| # config.action_view.sanitized_bad_tags = 'embed', 'object' @@ -163,7 +163,8 @@ module ActionView def sanitized_bad_tags=(attributes) HTML::WhiteListSanitizer.bad_tags.merge(attributes) end - # Adds to the Set of allowed tags for the #sanitize helper. + + # Adds to the Set of allowed tags for the +sanitize+ helper. # # Rails::Initializer.run do |config| # config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td' @@ -173,7 +174,7 @@ module ActionView HTML::WhiteListSanitizer.allowed_tags.merge(attributes) end - # Adds to the Set of allowed html attributes for the #sanitize helper. + # Adds to the Set of allowed HTML attributes for the +sanitize+ helper. # # Rails::Initializer.run do |config| # config.action_view.sanitized_allowed_attributes = 'onclick', 'longdesc' @@ -183,7 +184,7 @@ module ActionView HTML::WhiteListSanitizer.allowed_attributes.merge(attributes) end - # Adds to the Set of allowed css properties for the #sanitize and #sanitize_css heleprs. + # Adds to the Set of allowed CSS properties for the #sanitize and +sanitize_css+ helpers. # # Rails::Initializer.run do |config| # config.action_view.sanitized_allowed_css_properties = 'expression' @@ -193,7 +194,7 @@ module ActionView HTML::WhiteListSanitizer.allowed_css_properties.merge(attributes) end - # Adds to the Set of allowed css keywords for the #sanitize and #sanitize_css helpers. + # Adds to the Set of allowed CSS keywords for the +sanitize+ and +sanitize_css+ helpers. # # Rails::Initializer.run do |config| # config.action_view.sanitized_allowed_css_keywords = 'expression' @@ -203,7 +204,7 @@ module ActionView HTML::WhiteListSanitizer.allowed_css_keywords.merge(attributes) end - # Adds to the Set of allowed shorthand css properties for the #sanitize and #sanitize_css helpers. + # Adds to the Set of allowed shorthand CSS properties for the +sanitize+ and +sanitize_css+ helpers. # # Rails::Initializer.run do |config| # config.action_view.sanitized_shorthand_css_properties = 'expression' @@ -213,7 +214,7 @@ module ActionView HTML::WhiteListSanitizer.shorthand_css_properties.merge(attributes) end - # Adds to the Set of allowed protocols for the #sanitize helper. + # Adds to the Set of allowed protocols for the +sanitize+ helper. # # Rails::Initializer.run do |config| # config.action_view.sanitized_allowed_protocols = 'ssh', 'feed' diff --git a/actionpack/lib/action_view/helpers/scriptaculous_helper.rb b/actionpack/lib/action_view/helpers/scriptaculous_helper.rb index 12b4cfd3f8..b938c1a801 100644 --- a/actionpack/lib/action_view/helpers/scriptaculous_helper.rb +++ b/actionpack/lib/action_view/helpers/scriptaculous_helper.rb @@ -26,9 +26,9 @@ module ActionView # :url => { :action => "reload" }, # :complete => visual_effect(:highlight, "posts", :duration => 0.5) # - # If no element_id is given, it assumes "element" which should be a local + # If no +element_id+ is given, it assumes "element" which should be a local # variable in the generated JavaScript execution context. This can be - # used for example with drop_receiving_element: + # used for example with +drop_receiving_element+: # # <%= drop_receiving_element (...), :loading => visual_effect(:fade) %> # @@ -67,6 +67,7 @@ module ActionView # element as parameters. # # Example: + # # <%= sortable_element("my_list", :url => { :action => "order" }) %> # # In the example, the action gets a "my_list" array parameter @@ -79,60 +80,56 @@ module ActionView # # Additional +options+ are: # - # <tt>:format</tt>:: A regular expression to determine what to send - # as the serialized id to the server (the default - # is <tt>/^[^_]*_(.*)$/</tt>). - # - # <tt>:constraint</tt>:: Whether to constrain the dragging to either <tt>:horizontal</tt> - # or <tt>:vertical</tt> (or false to make it unconstrained). - # - # <tt>:overlap</tt>:: Calculate the item overlap in the <tt>:horizontal</tt> or - # <tt>:vertical</tt> direction. - # - # <tt>:tag</tt>:: Which children of the container element to treat as - # sortable (default is <tt>li</tt>). - # - # <tt>:containment</tt>:: Takes an element or array of elements to treat as - # potential drop targets (defaults to the original - # target element). - # - # <tt>:only</tt>:: A CSS class name or arry of class names used to filter - # out child elements as candidates. - # - # <tt>:scroll</tt>:: Determines whether to scroll the list during drag - # operations if the list runs past the visual border. - # - # <tt>:tree</tt>:: Determines whether to treat nested lists as part of the - # main sortable list. This means that you can create multi- - # layer lists, and not only sort items at the same level, - # but drag and sort items between levels. - # - # <tt>:hoverclass</tt>:: If set, the Droppable will have this additional CSS class - # when an accepted Draggable is hovered over it. - # - # <tt>:handle</tt>:: Sets whether the element should only be draggable by an - # embedded handle. The value may be a string referencing a - # CSS class value (as of script.aculo.us V1.5). The first - # child/grandchild/etc. element found within the element - # that has this CSS class value will be used as the handle. - # - # <tt>:ghosting</tt>:: Clones the element and drags the clone, leaving the original - # in place until the clone is dropped (default is <tt>false</tt>). - # - # <tt>:dropOnEmpty</tt>:: If set to true, the Sortable container will be made into - # a Droppable, that can receive a Draggable (as according to - # the containment rules) as a child element when there are no - # more elements inside (default is <tt>false</tt>). - # - # <tt>:onChange</tt>:: Called whenever the sort order changes while dragging. When - # dragging from one Sortable to another, the callback is - # called once on each Sortable. Gets the affected element as - # its parameter. - # - # <tt>:onUpdate</tt>:: Called when the drag ends and the Sortable's order is - # changed in any way. When dragging from one Sortable to - # another, the callback is called once on each Sortable. Gets - # the container as its parameter. + # * <tt>:format</tt> - A regular expression to determine what to send as the + # serialized id to the server (the default is <tt>/^[^_]*_(.*)$/</tt>). + # + # * <tt>:constraint</tt> - Whether to constrain the dragging to either + # <tt>:horizontal</tt> or <tt>:vertical</tt> (or false to make it unconstrained). + # + # * <tt>:overlap</tt> - Calculate the item overlap in the <tt>:horizontal</tt> + # or <tt>:vertical</tt> direction. + # + # * <tt>:tag</tt> - Which children of the container element to treat as + # sortable (default is <tt>li</tt>). + # + # * <tt>:containment</tt> - Takes an element or array of elements to treat as + # potential drop targets (defaults to the original target element). + # + # * <tt>:only</tt> - A CSS class name or arry of class names used to filter + # out child elements as candidates. + # + # * <tt>:scroll</tt> - Determines whether to scroll the list during drag + # operations if the list runs past the visual border. + # + # * <tt>:tree</tt> - Determines whether to treat nested lists as part of the + # main sortable list. This means that you can create multi-layer lists, + # and not only sort items at the same level, but drag and sort items + # between levels. + # + # * <tt>:hoverclass</tt> - If set, the Droppable will have this additional CSS class + # when an accepted Draggable is hovered over it. + # + # * <tt>:handle</tt> - Sets whether the element should only be draggable by an + # embedded handle. The value may be a string referencing a CSS class value + # (as of script.aculo.us V1.5). The first child/grandchild/etc. element + # found within the element that has this CSS class value will be used as + # the handle. + # + # * <tt>:ghosting</tt> - Clones the element and drags the clone, leaving + # the original in place until the clone is dropped (default is <tt>false</tt>). + # + # * <tt>:dropOnEmpty</tt> - If true the Sortable container will be made into + # a Droppable, that can receive a Draggable (as according to the containment + # rules) as a child element when there are no more elements inside (default + # is <tt>false</tt>). + # + # * <tt>:onChange</tt> - Called whenever the sort order changes while dragging. When + # dragging from one Sortable to another, the callback is called once on each + # Sortable. Gets the affected element as its parameter. + # + # * <tt>:onUpdate</tt> - Called when the drag ends and the Sortable's order is + # changed in any way. When dragging from one Sortable to another, the callback + # is called once on each Sortable. Gets the container as its parameter. # # See http://script.aculo.us for more documentation. def sortable_element(element_id, options = {}) @@ -170,8 +167,8 @@ module ActionView end # Makes the element with the DOM ID specified by +element_id+ receive - # dropped draggable elements (created by draggable_element). - # and make an AJAX call By default, the action called gets the DOM ID + # dropped draggable elements (created by +draggable_element+). + # and make an AJAX call. By default, the action called gets the DOM ID # of the element as parameter. # # Example: @@ -182,32 +179,30 @@ module ActionView # http://script.aculo.us for more documentation. # # Some of these +options+ include: - # <tt>:accept</tt>:: Set this to a string or an array of strings describing the - # allowable CSS classes that the draggable_element must have in order - # to be accepted by this drop_receiving_element. - # - # <tt>:confirm</tt>:: Adds a confirmation dialog. - # - # Example: - # :confirm => "Are you sure you want to do this?" - # - # <tt>:hoverclass</tt>:: If set, the drop_receiving_element will have this additional CSS class - # when an accepted draggable_element is hovered over it. - # - # <tt>:onDrop</tt>:: Called when a draggable_element is dropped onto this element. - # Override this callback with a javascript expression to - # change the default drop behavour. - # - # Example: - # :onDrop => "function(draggable_element, droppable_element, event) { alert('I like bananas') }" - # - # This callback gets three parameters: - # The +Draggable+ element, the +Droppable+ element and the - # +Event+ object. You can extract additional information about the - # drop - like if the Ctrl or Shift keys were pressed - from the +Event+ object. - # - # <tt>:with</tt>:: A JavaScript expression specifying the parameters for the XMLHttpRequest. - # Any expressions should return a valid URL query string. + # * <tt>:accept</tt> - Set this to a string or an array of strings describing the + # allowable CSS classes that the +draggable_element+ must have in order + # to be accepted by this +drop_receiving_element+. + # + # * <tt>:confirm</tt> - Adds a confirmation dialog. Example: + # + # :confirm => "Are you sure you want to do this?" + # + # * <tt>:hoverclass</tt> - If set, the +drop_receiving_element+ will have + # this additional CSS class when an accepted +draggable_element+ is + # hovered over it. + # + # * <tt>:onDrop</tt> - Called when a +draggable_element+ is dropped onto + # this element. Override this callback with a JavaScript expression to + # change the default drop behaviour. Example: + # + # :onDrop => "function(draggable_element, droppable_element, event) { alert('I like bananas') }" + # + # This callback gets three parameters: The Draggable element, the Droppable + # element and the Event object. You can extract additional information about + # the drop - like if the Ctrl or Shift keys were pressed - from the Event object. + # + # * <tt>:with</tt> - A JavaScript expression specifying the parameters for + # the XMLHttpRequest. Any expressions should return a valid URL query string. def drop_receiving_element(element_id, options = {}) javascript_tag(drop_receiving_element_js(element_id, options).chop!) end diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb index 9d220c546a..669a285424 100644 --- a/actionpack/lib/action_view/helpers/text_helper.rb +++ b/actionpack/lib/action_view/helpers/text_helper.rb @@ -464,11 +464,11 @@ module ActionView [-\w]+ # subdomain or domain (?:\.[-\w]+)* # remaining subdomains or domain (?::\d+)? # port - (?:/(?:(?:[~\w\+@%=-]|(?:[,.;:][^\s$]))+)?)* # path + (?:/(?:(?:[~\w\+@%=\(\)-]|(?:[,.;:][^\s$]))+)?)* # path (?:\?[\w\+@%&=.;-]+)? # query string (?:\#[\w\-]*)? # trailing anchor ) - ([[:punct:]]|\s|<|$) # trailing text + ([[:punct:]]|<|$|) # trailing text }x unless const_defined?(:AUTO_LINK_RE) # Turns all urls into clickable links. If a block is given, each url diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb index 38c8d18cb0..7bb189420b 100644 --- a/actionpack/lib/action_view/helpers/url_helper.rb +++ b/actionpack/lib/action_view/helpers/url_helper.rb @@ -10,7 +10,7 @@ module ActionView include JavaScriptHelper # Returns the URL for the set of +options+ provided. This takes the - # same options as url_for in ActionController (see the + # same options as +url_for+ in Action Controller (see the # documentation for ActionController::Base#url_for). Note that by default # <tt>:only_path</tt> is <tt>true</tt> so you'll get the relative /controller/action # instead of the fully qualified URL like http://example.com/controller/action. @@ -173,7 +173,7 @@ module ActionView # link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux") # # => <a href="/searches?foo=bar&baz=quux">Nonsense search</a> # - # The three options specfic to +link_to+ (<tt>:confirm</tt>, <tt>:popup</tt>, and <tt>:method</tt>) are used as follows: + # The three options specific to +link_to+ (<tt>:confirm</tt>, <tt>:popup</tt>, and <tt>:method</tt>) are used as follows: # # link_to "Visit Other Site", "http://www.rubyonrails.org/", :confirm => "Are you sure?" # # => <a href="http://www.rubyonrails.org/" onclick="return confirm('Are you sure?');">Visit Other Site</a> diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb index 2cda3d94b5..369526188f 100644 --- a/actionpack/lib/action_view/template.rb +++ b/actionpack/lib/action_view/template.rb @@ -93,9 +93,9 @@ module ActionView #:nodoc: # Register a class that knows how to handle template files with the given # extension. This can be used to implement new template types. # The constructor for the class must take the ActiveView::Base instance - # as a parameter, and the class must implement a #render method that + # as a parameter, and the class must implement a +render+ method that # takes the contents of the template to render as well as the Hash of - # local assigns available to the template. The #render method ought to + # local assigns available to the template. The +render+ method ought to # return the rendered template as a string. def self.register_template_handler(extension, klass) @@template_handlers[extension.to_sym] = klass diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb index b2e6589d81..16fedd9732 100644 --- a/actionpack/lib/action_view/test_case.rb +++ b/actionpack/lib/action_view/test_case.rb @@ -1,14 +1,6 @@ require 'active_support/test_case' module ActionView - class NonInferrableHelperError < ActionViewError - def initialize(name) - super "Unable to determine the helper to test from #{name}. " + - "You'll need to specify it using tests YourHelper in your " + - "test case definition" - end - end - class TestCase < ActiveSupport::TestCase class_inheritable_accessor :helper_class @@helper_class = nil @@ -29,7 +21,7 @@ module ActionView def determine_default_helper_class(name) name.sub(/Test$/, '').constantize rescue NameError - raise NonInferrableHelperError.new(name) + nil end end @@ -42,7 +34,9 @@ module ActionView setup :setup_with_helper_class def setup_with_helper_class - self.class.send(:include, helper_class) + if helper_class && !self.class.ancestors.include?(helper_class) + self.class.send(:include, helper_class) + end end class TestController < ActionController::Base diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb index 1db057580b..f152b1d19c 100644 --- a/actionpack/test/controller/action_pack_assertions_test.rb +++ b/actionpack/test/controller/action_pack_assertions_test.rb @@ -131,6 +131,10 @@ class AssertResponseWithUnexpectedErrorController < ActionController::Base def index raise 'FAIL' end + + def show + render :text => "Boom", :status => 500 + end end module Admin @@ -483,6 +487,16 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase rescue Test::Unit::AssertionFailedError => e assert e.message.include?('FAIL') end + + def test_assert_response_failure_response_with_no_exception + @controller = AssertResponseWithUnexpectedErrorController.new + get :show + assert_response :success + flunk 'Expected non-success response' + rescue Test::Unit::AssertionFailedError + rescue + flunk "assert_response failed to handle failure response with missing, but optional, exception." + end end class ActionPackHeaderTest < Test::Unit::TestCase diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index 4aacb4a78a..f9b6b87bc6 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -232,7 +232,7 @@ class ActionCacheTest < Test::Unit::TestCase get :index cached_time = content_to_cache assert_equal cached_time, @response.body - assert_cache_exists 'hostname.com/action_caching_test' + assert fragment_exist?('hostname.com/action_caching_test') reset! get :index @@ -243,7 +243,7 @@ class ActionCacheTest < Test::Unit::TestCase get :destroy cached_time = content_to_cache assert_equal cached_time, @response.body - assert_cache_does_not_exist 'hostname.com/action_caching_test/destroy' + assert !fragment_exist?('hostname.com/action_caching_test/destroy') reset! get :destroy @@ -254,7 +254,7 @@ class ActionCacheTest < Test::Unit::TestCase get :with_layout cached_time = content_to_cache assert_not_equal cached_time, @response.body - assert_cache_exists 'hostname.com/action_caching_test/with_layout' + assert fragment_exist?('hostname.com/action_caching_test/with_layout') reset! get :with_layout @@ -266,14 +266,14 @@ class ActionCacheTest < Test::Unit::TestCase def test_action_cache_conditional_options @request.env['HTTP_ACCEPT'] = 'application/json' get :index - assert_cache_does_not_exist 'hostname.com/action_caching_test' + assert !fragment_exist?('hostname.com/action_caching_test') end def test_action_cache_with_custom_cache_path get :show cached_time = content_to_cache assert_equal cached_time, @response.body - assert_cache_exists 'test.host/custom/show' + assert fragment_exist?('test.host/custom/show') reset! get :show @@ -282,11 +282,11 @@ class ActionCacheTest < Test::Unit::TestCase def test_action_cache_with_custom_cache_path_in_block get :edit - assert_cache_exists 'test.host/edit' + assert fragment_exist?('test.host/edit') reset! get :edit, :id => 1 - assert_cache_exists 'test.host/1;edit' + assert fragment_exist?('test.host/1;edit') end def test_cache_expiration @@ -395,18 +395,8 @@ class ActionCacheTest < Test::Unit::TestCase @request.host = 'hostname.com' end - def assert_cache_exists(path) - full_path = cache_path(path) - assert File.exist?(full_path), "#{full_path.inspect} does not exist." - end - - def assert_cache_does_not_exist(path) - full_path = cache_path(path) - assert !File.exist?(full_path), "#{full_path.inspect} should not exist." - end - - def cache_path(path) - File.join(FILE_STORE_PATH, 'views', path + '.cache') + def fragment_exist?(path) + @controller.fragment_exist?(path) end def read_fragment(path) @@ -450,6 +440,19 @@ class FragmentCachingTest < Test::Unit::TestCase assert_nil @controller.read_fragment('name') end + def test_fragment_exist__with_caching_enabled + @store.write('views/name', 'value') + assert @controller.fragment_exist?('name') + assert !@controller.fragment_exist?('other_name') + end + + def test_fragment_exist__with_caching_disabled + ActionController::Base.perform_caching = false + @store.write('views/name', 'value') + assert !@controller.fragment_exist?('name') + assert !@controller.fragment_exist?('other_name') + end + def test_write_fragment__with_caching_enabled assert_nil @store.read('views/name') assert_equal 'value', @controller.write_fragment('name', 'value') @@ -494,7 +497,6 @@ class FragmentCachingTest < Test::Unit::TestCase assert_equal 'generated till now -> ', buffer end - def test_fragment_for @store.write('views/expensive', 'fragment content') fragment_computed = false diff --git a/actionpack/test/controller/cgi_test.rb b/actionpack/test/controller/cgi_test.rb index 87f72fda77..f0f3a4b826 100755 --- a/actionpack/test/controller/cgi_test.rb +++ b/actionpack/test/controller/cgi_test.rb @@ -114,3 +114,36 @@ class CgiRequestNeedsRewoundTest < BaseCgiTest assert_equal 0, request.body.pos end end + +class CgiResponseTest < BaseCgiTest + def setup + super + @fake_cgi.expects(:header).returns("HTTP/1.0 200 OK\nContent-Type: text/html\n") + @response = ActionController::CgiResponse.new(@fake_cgi) + @output = StringIO.new('') + end + + def test_simple_output + @response.body = "Hello, World!" + + @response.out(@output) + assert_equal "HTTP/1.0 200 OK\nContent-Type: text/html\nHello, World!", @output.string + end + + def test_head_request + @fake_cgi.env_table['REQUEST_METHOD'] = 'HEAD' + @response.body = "Hello, World!" + + @response.out(@output) + assert_equal "HTTP/1.0 200 OK\nContent-Type: text/html\n", @output.string + end + + def test_streaming_block + @response.body = Proc.new do |response, output| + 5.times { |n| output.write(n) } + end + + @response.out(@output) + assert_equal "HTTP/1.0 200 OK\nContent-Type: text/html\n01234", @output.string + end +end diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb index 6dc77a4aaf..83e3b085e7 100644 --- a/actionpack/test/controller/helper_test.rb +++ b/actionpack/test/controller/helper_test.rb @@ -85,7 +85,7 @@ class HelperTest < Test::Unit::TestCase def test_helper_block_include assert_equal expected_helper_methods, missing_methods assert_nothing_raised { - @controller_class.helper { include TestHelper } + @controller_class.helper { include HelperTest::TestHelper } } assert [], missing_methods end diff --git a/actionpack/test/controller/rack_test.rb b/actionpack/test/controller/rack_test.rb new file mode 100644 index 0000000000..cd4151783e --- /dev/null +++ b/actionpack/test/controller/rack_test.rb @@ -0,0 +1,150 @@ +require 'abstract_unit' +require 'action_controller/rack_process' + +class BaseRackTest < Test::Unit::TestCase + def setup + @env = {"HTTP_MAX_FORWARDS"=>"10", "SERVER_NAME"=>"glu.ttono.us:8007", "FCGI_ROLE"=>"RESPONDER", "HTTP_X_FORWARDED_HOST"=>"glu.ttono.us", "HTTP_ACCEPT_ENCODING"=>"gzip, deflate", "HTTP_USER_AGENT"=>"Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/312.5.1 (KHTML, like Gecko) Safari/312.3.1", "PATH_INFO"=>"", "HTTP_ACCEPT_LANGUAGE"=>"en", "HTTP_HOST"=>"glu.ttono.us:8007", "SERVER_PROTOCOL"=>"HTTP/1.1", "REDIRECT_URI"=>"/dispatch.fcgi", "SCRIPT_NAME"=>"/dispatch.fcgi", "SERVER_ADDR"=>"207.7.108.53", "REMOTE_ADDR"=>"207.7.108.53", "SERVER_SOFTWARE"=>"lighttpd/1.4.5", "HTTP_COOKIE"=>"_session_id=c84ace84796670c052c6ceb2451fb0f2; is_admin=yes", "HTTP_X_FORWARDED_SERVER"=>"glu.ttono.us", "REQUEST_URI"=>"/admin", "DOCUMENT_ROOT"=>"/home/kevinc/sites/typo/public", "SERVER_PORT"=>"8007", "QUERY_STRING"=>"", "REMOTE_PORT"=>"63137", "GATEWAY_INTERFACE"=>"CGI/1.1", "HTTP_X_FORWARDED_FOR"=>"65.88.180.234", "HTTP_ACCEPT"=>"*/*", "SCRIPT_FILENAME"=>"/home/kevinc/sites/typo/public/dispatch.fcgi", "REDIRECT_STATUS"=>"200", "REQUEST_METHOD"=>"GET"} + # some Nokia phone browsers omit the space after the semicolon separator. + # some developers have grown accustomed to using comma in cookie values. + @alt_cookie_fmt_request_hash = {"HTTP_COOKIE"=>"_session_id=c84ace847,96670c052c6ceb2451fb0f2;is_admin=yes"} + @request = ActionController::RackRequest.new(@env) + end + + def default_test; end +end + + +class RackRequestTest < BaseRackTest + def test_proxy_request + assert_equal 'glu.ttono.us', @request.host_with_port + end + + def test_http_host + @env.delete "HTTP_X_FORWARDED_HOST" + @env['HTTP_HOST'] = "rubyonrails.org:8080" + assert_equal "rubyonrails.org:8080", @request.host_with_port + + @env['HTTP_X_FORWARDED_HOST'] = "www.firsthost.org, www.secondhost.org" + assert_equal "www.secondhost.org", @request.host + end + + def test_http_host_with_default_port_overrides_server_port + @env.delete "HTTP_X_FORWARDED_HOST" + @env['HTTP_HOST'] = "rubyonrails.org" + assert_equal "rubyonrails.org", @request.host_with_port + end + + def test_host_with_port_defaults_to_server_name_if_no_host_headers + @env.delete "HTTP_X_FORWARDED_HOST" + @env.delete "HTTP_HOST" + assert_equal "glu.ttono.us:8007", @request.host_with_port + end + + def test_host_with_port_falls_back_to_server_addr_if_necessary + @env.delete "HTTP_X_FORWARDED_HOST" + @env.delete "HTTP_HOST" + @env.delete "SERVER_NAME" + assert_equal "207.7.108.53:8007", @request.host_with_port + end + + def test_host_with_port_if_http_standard_port_is_specified + @env['HTTP_X_FORWARDED_HOST'] = "glu.ttono.us:80" + assert_equal "glu.ttono.us", @request.host_with_port + end + + def test_host_with_port_if_https_standard_port_is_specified + @env['HTTP_X_FORWARDED_PROTO'] = "https" + @env['HTTP_X_FORWARDED_HOST'] = "glu.ttono.us:443" + assert_equal "glu.ttono.us", @request.host_with_port + end + + def test_host_if_ipv6_reference + @env.delete "HTTP_X_FORWARDED_HOST" + @env['HTTP_HOST'] = "[2001:1234:5678:9abc:def0::dead:beef]" + assert_equal "[2001:1234:5678:9abc:def0::dead:beef]", @request.host + end + + def test_host_if_ipv6_reference_with_port + @env.delete "HTTP_X_FORWARDED_HOST" + @env['HTTP_HOST'] = "[2001:1234:5678:9abc:def0::dead:beef]:8008" + assert_equal "[2001:1234:5678:9abc:def0::dead:beef]", @request.host + end + + def test_cookie_syntax_resilience + cookies = CGI::Cookie::parse(@env["HTTP_COOKIE"]); + assert_equal ["c84ace84796670c052c6ceb2451fb0f2"], cookies["_session_id"], cookies.inspect + assert_equal ["yes"], cookies["is_admin"], cookies.inspect + + alt_cookies = CGI::Cookie::parse(@alt_cookie_fmt_request_hash["HTTP_COOKIE"]); + assert_equal ["c84ace847,96670c052c6ceb2451fb0f2"], alt_cookies["_session_id"], alt_cookies.inspect + assert_equal ["yes"], alt_cookies["is_admin"], alt_cookies.inspect + end +end + + +class RackRequestParamsParsingTest < BaseRackTest + def test_doesnt_break_when_content_type_has_charset + data = 'flamenco=love' + @request.env['CONTENT_LENGTH'] = data.length + @request.env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8' + @request.env['RAW_POST_DATA'] = data + assert_equal({"flamenco"=> "love"}, @request.request_parameters) + end + + def test_doesnt_interpret_request_uri_as_query_string_when_missing + @request.env['REQUEST_URI'] = 'foo' + assert_equal({}, @request.query_parameters) + end +end + + +class RackRequestNeedsRewoundTest < BaseRackTest + def test_body_should_be_rewound + data = 'foo' + @env['rack.input'] = StringIO.new(data) + @env['CONTENT_LENGTH'] = data.length + @env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8' + + # Read the request body by parsing params. + request = ActionController::RackRequest.new(@env) + request.request_parameters + + # Should have rewound the body. + assert_equal 0, request.body.pos + end +end + + +class RackResponseTest < BaseRackTest + def setup + super + @response = ActionController::RackResponse.new + @output = StringIO.new('') + end + + def test_simple_output + @response.body = "Hello, World!" + + status, headers, body = @response.out(@output) + assert_equal 200, status + assert_equal({"Content-Type" => "text/html", "Cache-Control" => "no-cache", "Set-Cookie" => ""}, headers) + + parts = [] + body.each { |part| parts << part } + assert_equal ["Hello, World!"], parts + end + + def test_streaming_block + @response.body = Proc.new do |response, output| + 5.times { |n| output.write(n) } + end + + status, headers, body = @response.out(@output) + assert_equal 200, status + assert_equal({"Content-Type" => "text/html", "Cache-Control" => "no-cache", "Set-Cookie" => ""}, headers) + + parts = [] + body.each { |part| parts << part } + assert_equal ["0", "1", "2", "3", "4"], parts + end +end diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index b28f7bcdff..5e5503fd52 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -50,6 +50,13 @@ class UriReservedCharactersRoutingTest < Test::Unit::TestCase :additional => ["add#{@segment}itional-1", "add#{@segment}itional-2"] } assert_equal options, @set.recognize_path("/controller/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2") end + + def test_route_generation_allows_passing_non_string_values_to_generated_helper + assert_equal "/controller/action/variable/1/2", @set.generate(:controller => "controller", + :action => "action", + :variable => "variable", + :additional => [1, 2]) + end end class LegacyRouteSetTests < Test::Unit::TestCase diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb index ba6c7f4299..38898a1f75 100644 --- a/actionpack/test/controller/test_test.rb +++ b/actionpack/test/controller/test_test.rb @@ -511,16 +511,26 @@ XML FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart' + if RUBY_VERSION < '1.9' + READ_BINARY = 'rb' + READ_PLAIN = 'r' + else + READ_BINARY = 'rb:binary' + READ_PLAIN = 'r:binary' + end + def test_test_uploaded_file filename = 'mona_lisa.jpg' path = "#{FILES_DIR}/#{filename}" content_type = 'image/png' + expected = File.read(path) + expected.force_encoding(Encoding::BINARY) if expected.respond_to?(:force_encoding) file = ActionController::TestUploadedFile.new(path, content_type) assert_equal filename, file.original_filename assert_equal content_type, file.content_type assert_equal file.path, file.local_path - assert_equal File.read(path), file.read + assert_equal expected, file.read end def test_test_uploaded_file_with_binary @@ -529,10 +539,10 @@ XML content_type = 'image/png' binary_uploaded_file = ActionController::TestUploadedFile.new(path, content_type, :binary) - assert_equal File.open(path, 'rb').read, binary_uploaded_file.read + assert_equal File.open(path, READ_BINARY).read, binary_uploaded_file.read plain_uploaded_file = ActionController::TestUploadedFile.new(path, content_type) - assert_equal File.open(path, 'r').read, plain_uploaded_file.read + assert_equal File.open(path, READ_PLAIN).read, plain_uploaded_file.read end def test_fixture_file_upload_with_binary @@ -541,10 +551,10 @@ XML content_type = 'image/jpg' binary_file_upload = fixture_file_upload(path, content_type, :binary) - assert_equal File.open(path, 'rb').read, binary_file_upload.read + assert_equal File.open(path, READ_BINARY).read, binary_file_upload.read plain_file_upload = fixture_file_upload(path, content_type) - assert_equal File.open(path, 'r').read, plain_file_upload.read + assert_equal File.open(path, READ_PLAIN).read, plain_file_upload.read end def test_fixture_file_upload diff --git a/actionpack/test/template/compiled_templates_test.rb b/actionpack/test/template/compiled_templates_test.rb deleted file mode 100644 index 73e7ec1d76..0000000000 --- a/actionpack/test/template/compiled_templates_test.rb +++ /dev/null @@ -1,192 +0,0 @@ -require 'abstract_unit' -require 'action_view/helpers/date_helper' -require 'action_view/compiled_templates' - -class CompiledTemplateTests < Test::Unit::TestCase - def setup - @ct = ActionView::CompiledTemplates.new - @v = Class.new - @v.send :include, @ct - @a = './test_compile_template_a.rhtml' - @b = './test_compile_template_b.rhtml' - @s = './test_compile_template_link.rhtml' - end - def teardown - [@a, @b, @s].each do |f| - FileUtils.rm(f) if File.exist?(f) || File.symlink?(f) - end - end - attr_reader :ct, :v - - def test_name_allocation - hi_world = ct.method_names['hi world'] - hi_sexy = ct.method_names['hi sexy'] - wish_upon_a_star = ct.method_names['I love seeing decent error messages'] - - assert_equal hi_world, ct.method_names['hi world'] - assert_equal hi_sexy, ct.method_names['hi sexy'] - assert_equal wish_upon_a_star, ct.method_names['I love seeing decent error messages'] - assert_equal 3, [hi_world, hi_sexy, wish_upon_a_star].uniq.length - end - - def test_wrap_source - assert_equal( - "def aliased_assignment(value)\nself.value = value\nend", - @ct.wrap_source(:aliased_assignment, [:value], 'self.value = value') - ) - - assert_equal( - "def simple()\nnil\nend", - @ct.wrap_source(:simple, [], 'nil') - ) - end - - def test_compile_source_single_method - selector = ct.compile_source('doubling method', [:a], 'a + a') - assert_equal 2, @v.new.send(selector, 1) - assert_equal 4, @v.new.send(selector, 2) - assert_equal -4, @v.new.send(selector, -2) - assert_equal 0, @v.new.send(selector, 0) - selector - end - - def test_compile_source_two_method - sel1 = test_compile_source_single_method # compile the method in the other test - sel2 = ct.compile_source('doubling method', [:a, :b], 'a + b + a + b') - assert_not_equal sel1, sel2 - - assert_equal 2, @v.new.send(sel1, 1) - assert_equal 4, @v.new.send(sel1, 2) - - assert_equal 6, @v.new.send(sel2, 1, 2) - assert_equal 32, @v.new.send(sel2, 15, 1) - end - - def test_mtime - t1 = Time.now - - test_compile_source_single_method - mtime = ct.mtime('doubling method', [:a]) - - assert mtime < Time.now - assert mtime > t1 - end - - uses_mocha 'test_compile_time' do - - def test_compile_time - t = Time.now - - File.open(@a, "w"){|f| f.puts @a} - File.open(@b, "w"){|f| f.puts @b} - # windows doesn't support symlinks (even under cygwin) - windows = (RUBY_PLATFORM =~ /win32/) - `ln -s #{@a} #{@s}` unless windows - - v = ActionView::Base.new - v.base_path = '.' - v.cache_template_loading = false - - ta = ActionView::Template.new(v, @a, false, {}) - tb = ActionView::Template.new(v, @b, false, {}) - ts = ActionView::Template.new(v, @s, false, {}) - - @handler_class = ActionView::Template.handler_class_for_extension(:rhtml) - @handler = @handler_class.new(v) - - # All templates were created at t+1 - File::Stat.any_instance.expects(:mtime).times(windows ? 2 : 3).returns(t + 1.second) - - # private methods template_changed_since? and compile_template? - # should report true for all since they have not been compiled - assert @handler.send(:template_changed_since?, @a, t) - assert @handler.send(:template_changed_since?, @b, t) - assert @handler.send(:template_changed_since?, @s, t) unless windows - - assert @handler.send(:compile_template?, ta) - assert @handler.send(:compile_template?, tb) - assert @handler.send(:compile_template?, ts) unless windows - - # All templates are rendered at t+2 - Time.expects(:now).times(windows ? 2 : 3).returns(t + 2.seconds) - v.send(:render_template, ta) - v.send(:render_template, tb) - v.send(:render_template, ts) unless windows - a_n = v.method_names[@a] - b_n = v.method_names[@b] - s_n = v.method_names[@s] unless windows - # all of the files have changed since last compile - assert @handler.compile_time[a_n] > t - assert @handler.compile_time[b_n] > t - assert @handler.compile_time[s_n] > t unless windows - - # private methods template_changed_since? and compile_template? - # should report false for all since none have changed since compile - File::Stat.any_instance.expects(:mtime).times(windows ? 6 : 12).returns(t + 1.second) - assert !@handler.send(:template_changed_since?, @a, @handler.compile_time[a_n]) - assert !@handler.send(:template_changed_since?, @b, @handler.compile_time[b_n]) - assert !@handler.send(:template_changed_since?, @s, @handler.compile_time[s_n]) unless windows - assert !@handler.send(:compile_template?, ta) - assert !@handler.send(:compile_template?, tb) - assert !@handler.send(:compile_template?, ts) unless windows - v.send(:render_template, ta) - v.send(:render_template, tb) - v.send(:render_template, ts) unless windows - # none of the files have changed since last compile - assert @handler.compile_time[a_n] < t + 3.seconds - assert @handler.compile_time[b_n] < t + 3.seconds - assert @handler.compile_time[s_n] < t + 3.seconds unless windows - - `rm #{@s}; ln -s #{@b} #{@s}` unless windows - # private methods template_changed_since? and compile_template? - # should report true for symlink since it has changed since compile - - # t + 3.seconds is for the symlink - File::Stat.any_instance.expects(:mtime).times(windows ? 6 : 9).returns( - *(windows ? [ t + 1.second, t + 1.second ] : - [ t + 1.second, t + 1.second, t + 3.second ]) * 3) - assert !@handler.send(:template_changed_since?, @a, @handler.compile_time[a_n]) - assert !@handler.send(:template_changed_since?, @b, @handler.compile_time[b_n]) - assert @handler.send(:template_changed_since?, @s, @handler.compile_time[s_n]) unless windows - assert !@handler.send(:compile_template?, ta) - assert !@handler.send(:compile_template?, tb) - assert @handler.send(:compile_template?, ts) unless windows - - # Only the symlink template gets rendered at t+3 - Time.stubs(:now).returns(t + 3.seconds) unless windows - v.send(:render_template, ta) - v.send(:render_template, tb) - v.send(:render_template, ts) unless windows - # the symlink has changed since last compile - assert @handler.compile_time[a_n] < t + 3.seconds - assert @handler.compile_time[b_n] < t + 3.seconds - assert_equal @handler.compile_time[s_n], t + 3.seconds unless windows - - FileUtils.touch @b - # private methods template_changed_since? and compile_template? - # should report true for symlink and file at end of symlink - # since it has changed since last compile - # - # t+4 is for @b and also for the file that @s points to, which is @b - File::Stat.any_instance.expects(:mtime).times(windows ? 6 : 12).returns( - *(windows ? [ t + 1.second, t + 4.seconds ] : - [ t + 1.second, t + 4.seconds, t + 3.second, t + 4.seconds ]) * 3) - assert !@handler.send(:template_changed_since?, @a, @handler.compile_time[a_n]) - assert @handler.send(:template_changed_since?, @b, @handler.compile_time[b_n]) - assert @handler.send(:template_changed_since?, @s, @handler.compile_time[s_n]) unless windows - assert !@handler.send(:compile_template?, ta) - assert @handler.send(:compile_template?, tb) - assert @handler.send(:compile_template?, ts) unless windows - - Time.expects(:now).times(windows ? 1 : 2).returns(t + 5.seconds) - v.send(:render_template, ta) - v.send(:render_template, tb) - v.send(:render_template, ts) unless windows - # the file at the end of the symlink has changed since last compile - # both the symlink and the file at the end of it should be recompiled - assert @handler.compile_time[a_n] < t + 5.seconds - assert_equal @handler.compile_time[b_n], t + 5.seconds - assert_equal @handler.compile_time[s_n], t + 5.seconds unless windows - end - end -end diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb index ae83c7bf47..0a7b19ba96 100755 --- a/actionpack/test/template/date_helper_test.rb +++ b/actionpack/test/template/date_helper_test.rb @@ -1722,6 +1722,12 @@ class DateHelperTest < ActionView::TestCase assert_equal 2, dummy_instance_tag.send!(:default_time_from_options, :hour => 2).hour end end + + def test_instance_tag_default_time_from_options_handles_far_future_date + dummy_instance_tag = ActionView::Helpers::InstanceTag.new(1,2,3) + time = dummy_instance_tag.send!(:default_time_from_options, :year => 2050, :month => 2, :day => 10, :hour => 15, :min => 30, :sec => 45) + assert_equal 2050, time.year + end end protected diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb index 4538b6dc6f..af99e6243d 100644 --- a/actionpack/test/template/form_helper_test.rb +++ b/actionpack/test/template/form_helper_test.rb @@ -181,6 +181,17 @@ class FormHelperTest < ActionView::TestCase '<input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />', check_box("post", "secret?") ) + + @post.secret = ['0'] + assert_dom_equal( + '<input id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />', + check_box("post", "secret") + ) + @post.secret = ['1'] + assert_dom_equal( + '<input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />', + check_box("post", "secret") + ) end def test_check_box_with_explicit_checked_and_unchecked_values diff --git a/actionpack/test/template/prototype_helper_test.rb b/actionpack/test/template/prototype_helper_test.rb index 9a1079b297..53a250f9d5 100644 --- a/actionpack/test/template/prototype_helper_test.rb +++ b/actionpack/test/template/prototype_helper_test.rb @@ -25,8 +25,6 @@ class Author::Nested < Author; end class PrototypeHelperBaseTest < ActionView::TestCase - tests ActionView::Helpers::PrototypeHelper - attr_accessor :template_format def setup @@ -219,9 +217,9 @@ class PrototypeHelperTest < PrototypeHelperBaseTest end def test_observe_field_using_with_option - expected = %(<script type=\"text/javascript\">\n//<![CDATA[\nnew Form.Element.Observer('glass', 300, function(element, value) {new Ajax.Request('http://www.example.com/check_value', {asynchronous:true, evalScripts:true, parameters:'id=' + value})})\n//]]>\n</script>) + expected = %(<script type=\"text/javascript\">\n//<![CDATA[\nnew Form.Element.Observer('glass', 300, function(element, value) {new Ajax.Request('http://www.example.com/check_value', {asynchronous:true, evalScripts:true, parameters:'id=' + encodeURIComponent(value)})})\n//]]>\n</script>) assert_dom_equal expected, observe_field("glass", :frequency => 5.minutes, :url => { :action => "check_value" }, :with => 'id') - assert_dom_equal expected, observe_field("glass", :frequency => 5.minutes, :url => { :action => "check_value" }, :with => "'id=' + value") + assert_dom_equal expected, observe_field("glass", :frequency => 5.minutes, :url => { :action => "check_value" }, :with => "'id=' + encodeURIComponent(value)") end def test_observe_field_using_json_in_with_option diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb index 06e1fd1929..62cdca03d1 100644 --- a/actionpack/test/template/text_helper_test.rb +++ b/actionpack/test/template/text_helper_test.rb @@ -186,6 +186,7 @@ class TextHelperTest < ActionView::TestCase http://en.wikipedia.org/wiki/Wikipedia:Today%27s_featured_picture_%28animation%29/January_20%2C_2007 http://www.mail-archive.com/rails@lists.rubyonrails.org/ http://www.amazon.com/Testing-Equal-Sign-In-Path/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1198861734&sr=8-1 + http://en.wikipedia.org/wiki/Sprite_(computer_graphics) ) urls.each do |url| @@ -262,6 +263,8 @@ class TextHelperTest < ActionView::TestCase assert_equal email2_result, auto_link(email2_raw) assert_equal '', auto_link(nil) assert_equal '', auto_link('') + assert_equal "#{link_result} #{link_result} #{link_result}", auto_link("#{link_raw} #{link_raw} #{link_raw}") + assert_equal '<a href="http://www.rubyonrails.com">Ruby On Rails</a>', auto_link('<a href="http://www.rubyonrails.com">Ruby On Rails</a>') end def test_auto_link_at_eol diff --git a/activemodel/Rakefile b/activemodel/Rakefile index cb9a61773f..87e9b547f3 100644 --- a/activemodel/Rakefile +++ b/activemodel/Rakefile @@ -1,4 +1,16 @@ #!/usr/bin/env ruby $LOAD_PATH << File.join(File.dirname(__FILE__), 'vendor', 'rspec', 'lib') require 'rake' -require 'spec/rake/spectask'
\ No newline at end of file +require 'spec/rake/spectask' +require 'rake/rdoctask' + +# Generate the RDoc documentation +Rake::RDocTask.new { |rdoc| + rdoc.rdoc_dir = 'doc' + rdoc.title = "Active Model" + rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' + rdoc.options << '--charset' << 'utf-8' + rdoc.template = "#{ENV['template']}.rb" if ENV['template'] + rdoc.rdoc_files.include('README', 'CHANGES') + rdoc.rdoc_files.include('lib/**/*.rb') +}
\ No newline at end of file diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index cd526a52a7..a65771648e 100644 --- a/activerecord/CHANGELOG +++ b/activerecord/CHANGELOG @@ -1,4 +1,17 @@ -*2.1.0 RC1 (May 11th, 2008)* +*Edge* + +* Added SQL escaping for :limit and :offset in MySQL [Jonathan Wiess] + + +*2.1.0 (May 31st, 2008)* + +* Add ActiveRecord::Base.sti_name that checks ActiveRecord::Base#store_full_sti_class? and returns either the full or demodulized name. [rick] + +* Add first/last methods to associations/named_scope. Resolved #226. [Ryan Bates] + +* Added SQL escaping for :limit and :offset #288 [Aaron Bedra, Steven Bristol, Jonathan Wiess] + +* Added first/last methods to associations/named_scope. Resolved #226. [Ryan Bates] * Ensure hm:t preloading honours reflection options. Resolves #137. [Frederick Cheung] diff --git a/activerecord/Rakefile b/activerecord/Rakefile index 043ab6d551..fc068b16c3 100755 --- a/activerecord/Rakefile +++ b/activerecord/Rakefile @@ -171,7 +171,7 @@ spec = Gem::Specification.new do |s| s.files = s.files + Dir.glob( "#{dir}/**/*" ).delete_if { |item| item.include?( "\.svn" ) } end - s.add_dependency('activesupport', '= 2.0.991' + PKG_BUILD) + s.add_dependency('activesupport', '= 2.1.0' + PKG_BUILD) s.files.delete FIXTURES_ROOT + "/fixture_database.sqlite" s.files.delete FIXTURES_ROOT + "/fixture_database_2.sqlite" diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb index 61446cde36..a5d3a50ef1 100644 --- a/activerecord/lib/active_record/aggregations.rb +++ b/activerecord/lib/active_record/aggregations.rb @@ -92,19 +92,19 @@ module ActiveRecord # # == Writing value objects # - # Value objects are immutable and interchangeable objects that represent a given value, such as a +Money+ object representing - # $5. Two +Money+ objects both representing $5 should be equal (through methods such as == and <=> from +Comparable+ if ranking - # makes sense). This is unlike entity objects where equality is determined by identity. An entity class such as +Customer+ can + # Value objects are immutable and interchangeable objects that represent a given value, such as a Money object representing + # $5. Two Money objects both representing $5 should be equal (through methods such as <tt>==</tt> and <tt><=></tt> from Comparable if ranking + # makes sense). This is unlike entity objects where equality is determined by identity. An entity class such as Customer can # easily have two different objects that both have an address on Hyancintvej. Entity identity is determined by object or - # relational unique identifiers (such as primary keys). Normal <tt>ActiveRecord::Base</tt> classes are entity objects. + # relational unique identifiers (such as primary keys). Normal ActiveRecord::Base classes are entity objects. # - # It's also important to treat the value objects as immutable. Don't allow the +Money+ object to have its amount changed after - # creation. Create a new +Money+ object with the new value instead. This is exemplified by the <tt>Money#exchanged_to</tt> method that + # It's also important to treat the value objects as immutable. Don't allow the Money object to have its amount changed after + # creation. Create a new Money object with the new value instead. This is exemplified by the Money#exchanged_to method that # returns a new value object instead of changing its own values. Active Record won't persist value objects that have been # changed through means other than the writer method. # # The immutable requirement is enforced by Active Record by freezing any object assigned as a value object. Attempting to - # change it afterwards will result in a <tt>ActiveSupport::FrozenObjectError</tt>. + # change it afterwards will result in a ActiveSupport::FrozenObjectError. # # Read more about value objects on http://c2.com/cgi/wiki?ValueObject and on the dangers of not keeping value objects # immutable on http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable @@ -123,8 +123,8 @@ module ActiveRecord # # Options are: # * <tt>:class_name</tt> - specify the class name of the association. Use it only if that name can't be inferred - # from the part id. So <tt>composed_of :address</tt> will by default be linked to the +Address+ class, but - # if the real class name is +CompanyAddress+, you'll have to specify it with this option. + # from the part id. So <tt>composed_of :address</tt> will by default be linked to the Address class, but + # if the real class name is CompanyAddress, you'll have to specify it with this option. # * <tt>:mapping</tt> - specifies a number of mapping arrays (attribute, parameter) that bind an attribute name # to a constructor parameter on the value class. # * <tt>:allow_nil</tt> - specifies that the aggregate object will not be instantiated when all mapped diff --git a/activerecord/lib/active_record/association_preload.rb b/activerecord/lib/active_record/association_preload.rb index a3d1f12b03..087ed2a587 100644 --- a/activerecord/lib/active_record/association_preload.rb +++ b/activerecord/lib/active_record/association_preload.rb @@ -34,7 +34,7 @@ module ActiveRecord class_to_reflection = {} # Not all records have the same class, so group then preload # group on the reflection itself so that if various subclass share the same association then we do not split them - # unncessarily + # unnecessarily records.group_by {|record| class_to_reflection[record.class] ||= record.class.reflections[association]}.each do |reflection, records| raise ConfigurationError, "Association named '#{ association }' was not found; perhaps you misspelled it?" unless reflection send("preload_#{reflection.macro}_association", records, reflection, preload_options) diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index c17e35f5e0..a3d1bbbada 100644..100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -155,7 +155,7 @@ module ActiveRecord # # == Cardinality and associations # - # ActiveRecord associations can be used to describe one-to-one, one-to-many and many-to-many + # Active Record associations can be used to describe one-to-one, one-to-many and many-to-many # relationships between models. Each model uses an association to describe its role in # the relation. The +belongs_to+ association is always used in the model that has # the foreign key. @@ -441,9 +441,9 @@ module ActiveRecord # # == Eager loading of associations # - # Eager loading is a way to find objects of a certain class and a number of named associations along with it in a single SQL call. This is + # Eager loading is a way to find objects of a certain class and a number of named associations. This is # one of the easiest ways of to prevent the dreaded 1+N problem in which fetching 100 posts that each need to display their author - # triggers 101 database queries. Through the use of eager loading, the 101 queries can be reduced to 1. Example: + # triggers 101 database queries. Through the use of eager loading, the 101 queries can be reduced to 2. Example: # # class Post < ActiveRecord::Base # belongs_to :author @@ -452,7 +452,7 @@ module ActiveRecord # # Consider the following loop using the class above: # - # for post in Post.find(:all) + # for post in Post.all # puts "Post: " + post.title # puts "Written by: " + post.author.name # puts "Last comment on: " + post.comments.first.created_on @@ -462,14 +462,15 @@ module ActiveRecord # # for post in Post.find(:all, :include => :author) # - # This references the name of the +belongs_to+ association that also used the <tt>:author</tt> symbol, so the find will now weave in a join something - # like this: <tt>LEFT OUTER JOIN authors ON authors.id = posts.author_id</tt>. Doing so will cut down the number of queries from 201 to 101. + # This references the name of the +belongs_to+ association that also used the <tt>:author</tt> symbol. After loading the posts, find + # will collect the +author_id+ from each one and load all the referenced authors with one query. Doing so will cut down the number of queries from 201 to 102. # # We can improve upon the situation further by referencing both associations in the finder with: # # for post in Post.find(:all, :include => [ :author, :comments ]) # - # That'll add another join along the lines of: <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt>. And we'll be down to 1 query. + # This will load all comments with a single query. This reduces the total number of queries to 3. More generally the number of queries + # will be 1 plus the number of associations named (except if some of the associations are polymorphic +belongs_to+ - see below). # # To include a deep hierarchy of associations, use a hash: # @@ -482,81 +483,91 @@ module ActiveRecord # the number of queries. The database still needs to send all the data to Active Record and it still needs to be processed. So it's no # catch-all for performance problems, but it's a great way to cut down on the number of queries in a situation as the one described above. # - # Since the eager loading pulls from multiple tables, you'll have to disambiguate any column references in both conditions and orders. So - # <tt>:order => "posts.id DESC"</tt> will work while <tt>:order => "id DESC"</tt> will not. Because eager loading generates the +SELECT+ statement too, the - # <tt>:select</tt> option is ignored. + # Since only one table is loaded at a time, conditions or orders cannot reference tables other than the main one. If this is the case + # Active Record falls back to the previously used LEFT OUTER JOIN based strategy. For example + # + # Post.find(:all, :include => [ :author, :comments ], :conditions => ['comments.approved = ?', true]) # - # You can use eager loading on multiple associations from the same table, but you cannot use those associations in orders and conditions - # as there is currently not any way to disambiguate them. Eager loading will not pull additional attributes on join tables, so "rich - # associations" with +has_and_belongs_to_many+ are not a good fit for eager loading. + # will result in a single SQL query with joins along the lines of: <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt> and + # <tt>LEFT OUTER JOIN authors ON authors.id = posts.author_id</tt>. Note that using conditions like this can have unintended consequences. + # In the above example posts with no approved comments are not returned at all, because the conditions apply to the SQL statement as a whole + # and not just to the association. You must disambiguate column references for this fallback to happen, for example + # <tt>:order => "author.name DESC"</tt> will work but <tt>:order => "name DESC"</tt> will not. + # + # If you do want eagerload only some members of an association it is usually more natural to <tt>:include</tt> an association + # which has conditions defined on it: + # + # class Post < ActiveRecord::Base + # has_many :approved_comments, :class_name => 'Comment', :conditions => ['approved = ?', true] + # end + # + # Post.find(:all, :include => :approved_comments) + # + # will load posts and eager load the +approved_comments+ association, which contains only those comments that have been approved. # # When eager loaded, conditions are interpolated in the context of the model class, not the model instance. Conditions are lazily interpolated # before the actual model exists. # - # Eager loading is not supported with polymorphic associations up to (and including) - # version 2.0.2. Given + # Eager loading is supported with polymorphic associations. # # class Address < ActiveRecord::Base # belongs_to :addressable, :polymorphic => true # end # - # a call that tries to eager load the addressable model + # A call that tries to eager load the addressable model # - # Address.find(:all, :include => :addressable) # INVALID + # Address.find(:all, :include => :addressable) # - # will raise ActiveRecord::EagerLoadPolymorphicError. The reason is that the parent model's type - # is a column value so its corresponding table name cannot be put in the +FROM+/+JOIN+ clauses of that early query. - # - # In versions greater than 2.0.2 eager loading in polymorphic associations is supported - # thanks to a change in the overall preloading strategy. - # - # It does work the other way around though: if the <tt>User</tt> model is <tt>addressable</tt> you can eager load - # their addresses with <tt>:include</tt> just fine, every piece needed to construct the query is known beforehand. + # will execute one query to load the addresses and load the addressables with one query per addressable type. + # For example if all the addressables are either of class Person or Company then a total of 3 queries will be executed. The list of + # addressable types to load is determined on the back of the addresses loaded. This is not supported if Active Record has to fallback + # to the previous implementation of eager loading and will raise ActiveRecord::EagerLoadPolymorphicError. The reason is that the parent + # model's type is a column value so its corresponding table name cannot be put in the +FROM+/+JOIN+ clauses of that query. # # == Table Aliasing # - # ActiveRecord uses table aliasing in the case that a table is referenced multiple times in a join. If a table is referenced only once, + # Active Record uses table aliasing in the case that a table is referenced multiple times in a join. If a table is referenced only once, # the standard table name is used. The second time, the table is aliased as <tt>#{reflection_name}_#{parent_table_name}</tt>. Indexes are appended # for any more successive uses of the table name. # - # Post.find :all, :include => :comments - # # => SELECT ... FROM posts LEFT OUTER JOIN comments ON ... - # Post.find :all, :include => :special_comments # STI - # # => SELECT ... FROM posts LEFT OUTER JOIN comments ON ... AND comments.type = 'SpecialComment' - # Post.find :all, :include => [:comments, :special_comments] # special_comments is the reflection name, posts is the parent table name - # # => SELECT ... FROM posts LEFT OUTER JOIN comments ON ... LEFT OUTER JOIN comments special_comments_posts + # Post.find :all, :joins => :comments + # # => SELECT ... FROM posts INNER JOIN comments ON ... + # Post.find :all, :joins => :special_comments # STI + # # => SELECT ... FROM posts INNER JOIN comments ON ... AND comments.type = 'SpecialComment' + # Post.find :all, :joins => [:comments, :special_comments] # special_comments is the reflection name, posts is the parent table name + # # => SELECT ... FROM posts INNER JOIN comments ON ... INNER JOIN comments special_comments_posts # # Acts as tree example: # - # TreeMixin.find :all, :include => :children - # # => SELECT ... FROM mixins LEFT OUTER JOIN mixins childrens_mixins ... - # TreeMixin.find :all, :include => {:children => :parent} # using cascading eager includes - # # => SELECT ... FROM mixins LEFT OUTER JOIN mixins childrens_mixins ... - # LEFT OUTER JOIN parents_mixins ... - # TreeMixin.find :all, :include => {:children => {:parent => :children}} - # # => SELECT ... FROM mixins LEFT OUTER JOIN mixins childrens_mixins ... - # LEFT OUTER JOIN parents_mixins ... - # LEFT OUTER JOIN mixins childrens_mixins_2 + # TreeMixin.find :all, :joins => :children + # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ... + # TreeMixin.find :all, :joins => {:children => :parent} + # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ... + # INNER JOIN parents_mixins ... + # TreeMixin.find :all, :joins => {:children => {:parent => :children}} + # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ... + # INNER JOIN parents_mixins ... + # INNER JOIN mixins childrens_mixins_2 # # Has and Belongs to Many join tables use the same idea, but add a <tt>_join</tt> suffix: # - # Post.find :all, :include => :categories - # # => SELECT ... FROM posts LEFT OUTER JOIN categories_posts ... LEFT OUTER JOIN categories ... - # Post.find :all, :include => {:categories => :posts} - # # => SELECT ... FROM posts LEFT OUTER JOIN categories_posts ... LEFT OUTER JOIN categories ... - # LEFT OUTER JOIN categories_posts posts_categories_join LEFT OUTER JOIN posts posts_categories - # Post.find :all, :include => {:categories => {:posts => :categories}} - # # => SELECT ... FROM posts LEFT OUTER JOIN categories_posts ... LEFT OUTER JOIN categories ... - # LEFT OUTER JOIN categories_posts posts_categories_join LEFT OUTER JOIN posts posts_categories - # LEFT OUTER JOIN categories_posts categories_posts_join LEFT OUTER JOIN categories categories_posts + # Post.find :all, :joins => :categories + # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ... + # Post.find :all, :joins => {:categories => :posts} + # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ... + # INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories + # Post.find :all, :joins => {:categories => {:posts => :categories}} + # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ... + # INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories + # INNER JOIN categories_posts categories_posts_join INNER JOIN categories categories_posts_2 # # If you wish to specify your own custom joins using a <tt>:joins</tt> option, those table names will take precedence over the eager associations: # - # Post.find :all, :include => :comments, :joins => "inner join comments ..." - # # => SELECT ... FROM posts LEFT OUTER JOIN comments_posts ON ... INNER JOIN comments ... - # Post.find :all, :include => [:comments, :special_comments], :joins => "inner join comments ..." - # # => SELECT ... FROM posts LEFT OUTER JOIN comments comments_posts ON ... - # LEFT OUTER JOIN comments special_comments_posts ... + # Post.find :all, :joins => :comments, :joins => "inner join comments ..." + # # => SELECT ... FROM posts INNER JOIN comments_posts ON ... INNER JOIN comments ... + # Post.find :all, :joins => [:comments, :special_comments], :joins => "inner join comments ..." + # # => SELECT ... FROM posts INNER JOIN comments comments_posts ON ... + # INNER JOIN comments special_comments_posts ... # INNER JOIN comments ... # # Table aliases are automatically truncated according to the maximum length of table identifiers according to the specific database. @@ -667,7 +678,7 @@ module ActiveRecord # * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned. # * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows. # * <tt>:select</tt> - By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if you, for example, want to do a join - # but not include the joined columns. + # but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will rise an error. # * <tt>:as</tt> - Specifies a polymorphic interface (See <tt>belongs_to</tt>). # * <tt>:through</tt> - Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt> and <tt>:foreign_key</tt> # are ignored, as the association uses the source reflection. You can only use a <tt>:through</tt> query through a <tt>belongs_to</tt> @@ -747,12 +758,16 @@ module ActiveRecord # as the default <tt>:foreign_key</tt>. # * <tt>:include</tt> - Specify second-order associations that should be eager loaded when this object is loaded. # * <tt>:as</tt> - Specifies a polymorphic interface (See <tt>belongs_to</tt>). + # * <tt>:select</tt> - By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join + # but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error. # * <tt>:through</tt>: Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt> and <tt>:foreign_key</tt> # are ignored, as the association uses the source reflection. You can only use a <tt>:through</tt> query through a # <tt>has_one</tt> or <tt>belongs_to</tt> association on the join model. # * <tt>:source</tt> - Specifies the source association name used by <tt>has_one :through</tt> queries. Only use it if the name cannot be # inferred from the association. <tt>has_one :favorite, :through => :favorites</tt> will look for a # <tt>:favorite</tt> on Favorite, unless a <tt>:source</tt> is given. + # * <tt>:source_type</tt> - Specifies type of the source association used by <tt>has_one :through</tt> queries where the source + # association is a polymorphic +belongs_to+. # * <tt>:readonly</tt> - If true, the associated object is readonly through the association. # # Option examples: @@ -819,8 +834,8 @@ module ActiveRecord # if the real class name is Person, you'll have to specify it with this option. # * <tt>:conditions</tt> - Specify the conditions that the associated object must meet in order to be included as a +WHERE+ # SQL fragment, such as <tt>authorized = 1</tt>. - # * <tt>:order</tt> - Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment, - # such as <tt>last_name, first_name DESC</tt>. + # * <tt>:select</tt> - By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join + # but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error. # * <tt>:foreign_key</tt> - Specify the foreign key used for the association. By default this is guessed to be the name # of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt> association will use # "person_id" as the default <tt>:foreign_key</tt>. Similarly, <tt>belongs_to :favorite_person, :class_name => "Person"</tt> @@ -838,7 +853,6 @@ module ActiveRecord # this results in a counter with +NULL+ value, which will never increment. # Note: Specifying a counter cache will add it to that model's list of readonly attributes using +attr_readonly+. # * <tt>:include</tt> - Specify second-order associations that should be eager loaded when this object is loaded. - # Not allowed if the association is polymorphic. # * <tt>:polymorphic</tt> - Specify this association is a polymorphic association by passing +true+. # Note: If you've enabled the counter cache, then you may want to add the counter cache attribute # to the +attr_readonly+ list in the associated classes (e.g. <tt>class Post; attr_readonly :comments_count; end</tt>). @@ -938,7 +952,7 @@ module ActiveRecord # # Deprecated: Any additional fields added to the join table will be placed as attributes when pulling records out through # +has_and_belongs_to_many+ associations. Records returned from join tables with additional attributes will be marked as - # +ReadOnly+ (because we can't save changes to the additional attributes). It's strongly recommended that you upgrade any + # readonly (because we can't save changes to the additional attributes). It's strongly recommended that you upgrade any # associations with attributes to a real join model (see introduction). # # Adds the following methods for retrieval and query: @@ -1009,7 +1023,7 @@ module ActiveRecord # * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned. # * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows. # * <tt>:select</tt> - By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join - # but not include the joined columns. + # but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error. # * <tt>:readonly</tt> - If true, all the associated objects are readonly through the association. # # Option examples: @@ -1339,7 +1353,7 @@ module ActiveRecord def create_has_one_reflection(association_id, options) options.assert_valid_keys( - :class_name, :foreign_key, :remote, :conditions, :order, :include, :dependent, :counter_cache, :extend, :as, :readonly + :class_name, :foreign_key, :remote, :select, :conditions, :order, :include, :dependent, :counter_cache, :extend, :as, :readonly ) create_reflection(:has_one, association_id, options, self) @@ -1347,14 +1361,14 @@ module ActiveRecord def create_has_one_through_reflection(association_id, options) options.assert_valid_keys( - :class_name, :foreign_key, :remote, :conditions, :order, :include, :dependent, :counter_cache, :extend, :as, :through, :source, :source_type + :class_name, :foreign_key, :remote, :select, :conditions, :order, :include, :dependent, :counter_cache, :extend, :as, :through, :source, :source_type ) create_reflection(:has_one, association_id, options, self) end def create_belongs_to_reflection(association_id, options) options.assert_valid_keys( - :class_name, :foreign_key, :foreign_type, :remote, :conditions, :order, :include, :dependent, + :class_name, :foreign_key, :foreign_type, :remote, :select, :conditions, :include, :dependent, :counter_cache, :extend, :polymorphic, :readonly ) diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb index 7e47bf7bdf..52d2a9864e 100644 --- a/activerecord/lib/active_record/associations/association_collection.rb +++ b/activerecord/lib/active_record/associations/association_collection.rb @@ -48,6 +48,26 @@ module ActiveRecord end end + # Fetches the first one using SQL if possible. + def first(*args) + if fetch_first_or_last_using_find? args + find(:first, *args) + else + load_target unless loaded? + @target.first(*args) + end + end + + # Fetches the last one using SQL if possible. + def last(*args) + if fetch_first_or_last_using_find? args + find(:last, *args) + else + load_target unless loaded? + @target.last(*args) + end + end + def to_ary load_target @target.to_ary @@ -146,12 +166,18 @@ module ActiveRecord if attrs.is_a?(Array) attrs.collect { |attr| create(attr) } else - create_record(attrs) { |record| record.save } + create_record(attrs) do |record| + yield(record) if block_given? + record.save + end end end def create!(attrs = {}) - create_record(attrs) { |record| record.save! } + create_record(attrs) do |record| + yield(record) if block_given? + record.save! + end end # Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and @@ -330,7 +356,10 @@ module ActiveRecord raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved" end end - + + def fetch_first_or_last_using_find?(args) + args.first.kind_of?(Hash) || !(loaded? || @owner.new_record? || @reflection.options[:finder_sql] || !@target.blank? || args.first.kind_of?(Integer)) + end end end end diff --git a/activerecord/lib/active_record/associations/association_proxy.rb b/activerecord/lib/active_record/associations/association_proxy.rb index 68503a3c40..11c64243a2 100644 --- a/activerecord/lib/active_record/associations/association_proxy.rb +++ b/activerecord/lib/active_record/associations/association_proxy.rb @@ -49,7 +49,7 @@ module ActiveRecord alias_method :proxy_respond_to?, :respond_to? alias_method :proxy_extend, :extend delegate :to_param, :to => :proxy_target - instance_methods.each { |m| undef_method m unless m =~ /(^__|^nil\?$|^send$|proxy_)/ } + instance_methods.each { |m| undef_method m unless m =~ /(^__|^nil\?$|^send$|proxy_|^object_id$)/ } def initialize(owner, reflection) @owner, @reflection = owner, reflection @@ -210,7 +210,8 @@ module ActiveRecord def raise_on_type_mismatch(record) unless record.is_a?(@reflection.klass) - raise ActiveRecord::AssociationTypeMismatch, "#{@reflection.klass} expected, got #{record.class}" + message = "#{@reflection.class_name}(##{@reflection.klass.object_id}) expected, got #{record.class}(##{record.class.object_id})" + raise ActiveRecord::AssociationTypeMismatch, message end end diff --git a/activerecord/lib/active_record/associations/belongs_to_association.rb b/activerecord/lib/active_record/associations/belongs_to_association.rb index 9ff3f13592..7c28cbdd07 100644..100755 --- a/activerecord/lib/active_record/associations/belongs_to_association.rb +++ b/activerecord/lib/active_record/associations/belongs_to_association.rb @@ -42,10 +42,11 @@ module ActiveRecord private def find_target @reflection.klass.find( - @owner[@reflection.primary_key_name], + @owner[@reflection.primary_key_name], + :select => @reflection.options[:select], :conditions => conditions, :include => @reflection.options[:include], - :readonly => @reflection.options[:readonly] + :readonly => @reflection.options[:readonly] ) end diff --git a/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb b/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb index 9549b959fc..d8146daa54 100644..100755 --- a/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb +++ b/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb @@ -7,10 +7,8 @@ module ActiveRecord else @target = (AssociationProxy === record ? record.target : record) - unless record.new_record? - @owner[@reflection.primary_key_name] = record.id - @owner[@reflection.options[:foreign_type]] = record.class.base_class.name.to_s - end + @owner[@reflection.primary_key_name] = record.id + @owner[@reflection.options[:foreign_type]] = record.class.base_class.name.to_s @updated = true end @@ -29,12 +27,13 @@ module ActiveRecord if @reflection.options[:conditions] association_class.find( - @owner[@reflection.primary_key_name], + @owner[@reflection.primary_key_name], + :select => @reflection.options[:select], :conditions => conditions, :include => @reflection.options[:include] ) else - association_class.find(@owner[@reflection.primary_key_name], :include => @reflection.options[:include]) + association_class.find(@owner[@reflection.primary_key_name], :select => @reflection.options[:select], :include => @reflection.options[:include]) end end diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb index 963a938485..f584a97cbb 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -9,7 +9,7 @@ module ActiveRecord @reflection.klass.count_by_sql(@finder_sql) else column_name, options = @reflection.klass.send(:construct_count_options_from_args, *args) - options[:conditions] = options[:conditions].nil? ? + options[:conditions] = options[:conditions].blank? ? @finder_sql : @finder_sql + " AND (#{sanitize_sql(options[:conditions])})" options[:include] ||= @reflection.options[:include] diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index f683669615..52ced36d16 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -34,7 +34,7 @@ module ActiveRecord def count(*args) column_name, options = @reflection.klass.send(:construct_count_options_from_args, *args) if @reflection.options[:uniq] - # This is needed because 'SELECT count(DISTINCT *)..' is not valid sql statement. + # This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL statement. column_name = "#{@reflection.quoted_table_name}.#{@reflection.klass.primary_key}" if column_name == :all options.merge!(:distinct => true) end @@ -237,7 +237,7 @@ module ActiveRecord end def build_sti_condition - "#{@reflection.through_reflection.quoted_table_name}.#{@reflection.through_reflection.klass.inheritance_column} = #{@reflection.klass.quote_value(@reflection.through_reflection.klass.name.demodulize)}" + "#{@reflection.through_reflection.quoted_table_name}.#{@reflection.through_reflection.klass.inheritance_column} = #{@reflection.klass.quote_value(@reflection.through_reflection.klass.sti_name)}" end alias_method :sql_conditions, :conditions diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb index 3ff9fe3b9f..c2b3503e0d 100644..100755 --- a/activerecord/lib/active_record/associations/has_one_association.rb +++ b/activerecord/lib/active_record/associations/has_one_association.rb @@ -51,10 +51,11 @@ module ActiveRecord private def find_target @reflection.klass.find(:first, - :conditions => @finder_sql, + :conditions => @finder_sql, + :select => @reflection.options[:select], :order => @reflection.options[:order], :include => @reflection.options[:include], - :readonly => @reflection.options[:readonly] + :readonly => @reflection.options[:readonly] ) end diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb index c2604894a8..fab16a4446 100644 --- a/activerecord/lib/active_record/attribute_methods.rb +++ b/activerecord/lib/active_record/attribute_methods.rb @@ -94,7 +94,7 @@ module ActiveRecord end # Checks whether the method is defined in the model or any of its subclasses - # that also derive from ActiveRecord. Raises DangerousAttributeError if the + # that also derive from Active Record. Raises DangerousAttributeError if the # method is defined by Active Record though. def instance_method_already_implemented?(method_name) method_name = method_name.to_s @@ -162,6 +162,8 @@ module ActiveRecord evaluate_attribute_method attr_name, "def #{attr_name}; unserialize_attribute('#{attr_name}'); end" end + # Defined for all +datetime+ and +timestamp+ attributes when +time_zone_aware_attributes+ are enabled. + # This enhanced read method automatically converts the UTC time stored in the database to the time zone stored in Time.zone. def define_read_method_for_time_zone_conversion(attr_name) method_body = <<-EOV def #{attr_name}(reload = false) @@ -174,7 +176,7 @@ module ActiveRecord evaluate_attribute_method attr_name, method_body end - # Define an attribute ? method. + # Defines a predicate method <tt>attr_name?</tt>. def define_question_method(attr_name) evaluate_attribute_method attr_name, "def #{attr_name}?; query_attribute('#{attr_name}'); end", "#{attr_name}?" end @@ -183,6 +185,8 @@ module ActiveRecord evaluate_attribute_method attr_name, "def #{attr_name}=(new_value);write_attribute('#{attr_name}', new_value);end", "#{attr_name}=" end + # Defined for all +datetime+ and +timestamp+ attributes when +time_zone_aware_attributes+ are enabled. + # This enhanced write method will automatically convert the time passed to it to the zone stored in Time.zone. def define_write_method_for_time_zone_conversion(attr_name) method_body = <<-EOV def #{attr_name}=(time) diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 9b6183fc02..cfc6a5693a 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -2,11 +2,11 @@ require 'yaml' require 'set' module ActiveRecord #:nodoc: - # Generic ActiveRecord exception class. + # Generic Active Record exception class. class ActiveRecordError < StandardError end - # Raised when the single-table inheritance mechanism failes to locate the subclass + # Raised when the single-table inheritance mechanism fails to locate the subclass # (for example due to improper usage of column that +inheritance_column+ points to). class SubclassNotFound < ActiveRecordError #:nodoc: end @@ -30,19 +30,19 @@ module ActiveRecord #:nodoc: class SerializationTypeMismatch < ActiveRecordError end - # Raised when adapter not specified on connection (or configuration file config/database.yml misses adapter field). + # Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt> misses adapter field). class AdapterNotSpecified < ActiveRecordError end - # Raised when ActiveRecord cannot find database adapter specified in config/database.yml or programmatically. + # Raised when Active Record cannot find database adapter specified in <tt>config/database.yml</tt> or programmatically. class AdapterNotFound < ActiveRecordError end - # Raised when connection to the database could not been established (for example when connection= is given a nil object). + # Raised when connection to the database could not been established (for example when <tt>connection=</tt> is given a nil object). class ConnectionNotEstablished < ActiveRecordError end - # Raised when ActiveRecord cannot find record by given id or set of ids. + # Raised when Active Record cannot find record by given id or set of ids. class RecordNotFound < ActiveRecordError end @@ -70,7 +70,7 @@ module ActiveRecord #:nodoc: # instantiation, for example, when two users edit the same wiki page and one starts editing and saves # the page before the other. # - # Read more about optimistic locking in +ActiveRecord::Locking+ module RDoc. + # Read more about optimistic locking in ActiveRecord::Locking module RDoc. class StaleObjectError < ActiveRecordError end @@ -83,12 +83,12 @@ module ActiveRecord #:nodoc: class ReadOnlyRecord < ActiveRecordError end - # Used by ActiveRecord transaction mechanism to distinguish rollback from other exceptional situations. + # Used by Active Record transaction mechanism to distinguish rollback from other exceptional situations. # You can use it to roll your transaction back explicitly in the block passed to +transaction+ method. class Rollback < ActiveRecordError end - # Raised when attribute has a name reserved by ActiveRecord (when attribute has name of one of ActiveRecord instance methods). + # Raised when attribute has a name reserved by Active Record (when attribute has name of one of Active Record instance methods). class DangerousAttributeError < ActiveRecordError end @@ -97,7 +97,7 @@ module ActiveRecord #:nodoc: class MissingAttributeError < NoMethodError end - # Raised when an error occured while doing a mass assignment to an attribute through the + # Raised when an error occurred while doing a mass assignment to an attribute through the # <tt>attributes=</tt> method. The exception has an +attribute+ property that is the name of the # offending attribute. class AttributeAssignmentError < ActiveRecordError @@ -200,7 +200,7 @@ module ActiveRecord #:nodoc: # # All column values are automatically available through basic accessors on the Active Record object, but sometimes you # want to specialize this behavior. This can be done by overwriting the default accessors (using the same - # name as the attribute) and calling read_attribute(attr_name) and write_attribute(attr_name, value) to actually change things. + # name as the attribute) and calling <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually change things. # Example: # # class Song < ActiveRecord::Base @@ -215,8 +215,8 @@ module ActiveRecord #:nodoc: # end # end # - # You can alternatively use self[:attribute]=(value) and self[:attribute] instead of write_attribute(:attribute, value) and - # read_attribute(:attribute) as a shorter form. + # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt> instead of <tt>write_attribute(:attribute, value)</tt> and + # <tt>read_attribute(:attribute)</tt> as a shorter form. # # == Attribute query methods # @@ -236,7 +236,7 @@ module ActiveRecord #:nodoc: # # Sometimes you want to be able to read the raw attribute data without having the column-determined typecast run its course first. # That can be done by using the <tt><attribute>_before_type_cast</tt> accessors that all attributes have. For example, if your Account model - # has a balance attribute, you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>. + # has a <tt>balance</tt> attribute, you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>. # # This is especially useful in validation situations where the user might supply a string for an integer field and you want to display # the original string back in an error message. Accessing the attribute normally would typecast the string to 0, which isn't what you @@ -245,8 +245,8 @@ module ActiveRecord #:nodoc: # == Dynamic attribute-based finders # # Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects by simple queries without turning to SQL. They work by - # appending the name of an attribute to <tt>find_by_</tt> or <tt>find_all_by_</tt>, so you get finders like Person.find_by_user_name, - # Person.find_all_by_last_name, Payment.find_by_transaction_id. So instead of writing + # appending the name of an attribute to <tt>find_by_</tt> or <tt>find_all_by_</tt>, so you get finders like <tt>Person.find_by_user_name</tt>, + # <tt>Person.find_all_by_last_name</tt>, and <tt>Payment.find_by_transaction_id</tt>. So instead of writing # <tt>Person.find(:first, :conditions => ["user_name = ?", user_name])</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>. # And instead of writing <tt>Person.find(:all, :conditions => ["last_name = ?", last_name])</tt>, you just do <tt>Person.find_all_by_last_name(last_name)</tt>. # @@ -255,8 +255,8 @@ module ActiveRecord #:nodoc: # <tt>Person.find(:first, :conditions => ["user_name = ? AND password = ?", user_name, password])</tt>, you just do # <tt>Person.find_by_user_name_and_password(user_name, password)</tt>. # - # It's even possible to use all the additional parameters to find. For example, the full interface for Payment.find_all_by_amount - # is actually Payment.find_all_by_amount(amount, options). And the full interface to Person.find_by_user_name is + # It's even possible to use all the additional parameters to find. For example, the full interface for <tt>Payment.find_all_by_amount</tt> + # is actually <tt>Payment.find_all_by_amount(amount, options)</tt>. And the full interface to <tt>Person.find_by_user_name</tt> is # actually <tt>Person.find_by_user_name(user_name, options)</tt>. So you could call <tt>Payment.find_all_by_amount(50, :order => "created_on")</tt>. # # The same dynamic finder style can be used to create the object if it doesn't already exist. This dynamic finder is called with @@ -271,7 +271,7 @@ module ActiveRecord #:nodoc: # # Now 'Bob' exist and is an 'admin' # User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true } # - # Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without saving it first. Protected attributes won't be setted unless they are given in a block. For example: + # Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without saving it first. Protected attributes won't be set unless they are given in a block. For example: # # # No 'Winter' tag exists # winter = Tag.find_or_initialize_by_name("Winter") @@ -316,8 +316,8 @@ module ActiveRecord #:nodoc: # class Client < Company; end # class PriorityClient < Client; end # - # When you do Firm.create(:name => "37signals"), this record will be saved in the companies table with type = "Firm". You can then - # fetch this row again using Company.find(:first, "name = '37signals'") and it will return a Firm object. + # When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in the companies table with type = "Firm". You can then + # fetch this row again using <tt>Company.find(:first, "name = '37signals'")</tt> and it will return a Firm object. # # If you don't have a type column defined in your table, single-table inheritance won't be triggered. In that case, it'll work just # like normal subclasses with no special magic for differentiating between them or reloading the right type with find. @@ -329,8 +329,8 @@ module ActiveRecord #:nodoc: # # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection. # All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection. - # For example, if Course is an ActiveRecord::Base, but resides in a different database, you can just say Course.establish_connection - # and Course *and all its subclasses* will use this connection instead. + # For example, if Course is an ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt> + # and Course and all of its subclasses will use this connection instead. # # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is # requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool. @@ -407,7 +407,7 @@ module ActiveRecord #:nodoc: @@table_name_suffix = "" # Indicates whether table names should be the pluralized versions of the corresponding class names. - # If true, the default table name for a +Product+ class will be +products+. If false, it would just be +product+. + # If true, the default table name for a Product class will be +products+. If false, it would just be +product+. # See table_name for the full rules on table/class naming. This is true, by default. cattr_accessor :pluralize_table_names, :instance_writer => false @@pluralize_table_names = true @@ -446,36 +446,44 @@ module ActiveRecord #:nodoc: class << self # Class methods # Find operates with four different retrieval approaches: # - # * Find by id: This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]). + # * Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]). # If no record can be found for all of the listed ids, then RecordNotFound will be raised. - # * Find first: This will return the first record matched by the options used. These options can either be specific - # conditions or merely an order. If no record can be matched, nil is returned. - # * Find last: This will return the last record matched by the options used. These options can either be specific - # conditions or merely an order. If no record can be matched, nil is returned. - # * Find all: This will return all the records matched by the options used. If no records are found, an empty array is returned. - # - # All approaches accept an options hash as their last parameter. The options are: - # - # * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro. - # * <tt>:order</tt>: An SQL fragment like "created_at DESC, name". - # * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause. - # * <tt>:limit</tt>: An integer determining the limit on the number of rows that should be returned. - # * <tt>:offset</tt>: An integer determining the offset from where the rows should be fetched. So at 5, it would skip rows 0 through 4. - # * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed) - # or named associations in the same form used for the <tt>:include</tt> option, which will perform an INNER JOIN on the associated table(s). + # * Find first - This will return the first record matched by the options used. These options can either be specific + # conditions or merely an order. If no record can be matched, +nil+ is returned. Use + # <tt>Model.find(:first, *args)</tt> or its shortcut <tt>Model.first(*args)</tt>. + # * Find last - This will return the last record matched by the options used. These options can either be specific + # conditions or merely an order. If no record can be matched, +nil+ is returned. Use + # <tt>Model.find(:last, *args)</tt> or its shortcut <tt>Model.last(*args)</tt>. + # * Find all - This will return all the records matched by the options used. + # If no records are found, an empty array is returned. Use + # <tt>Model.find(:all, *args)</tt> or its shortcut <tt>Model.all(*args)</tt>. + # + # All approaches accept an options hash as their last parameter. + # + # ==== Attributes + # + # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1" or <tt>[ "user_name = ?", username ]</tt>. See conditions in the intro. + # * <tt>:order</tt> - An SQL fragment like "created_at DESC, name". + # * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause. + # * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned. + # * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5, it would skip rows 0 through 4. + # * <tt>:joins</tt> - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed) + # or named associations in the same form used for the <tt>:include</tt> option, which will perform an <tt>INNER JOIN</tt> on the associated table(s). # If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns. # Pass <tt>:readonly => false</tt> to override. - # * <tt>:include</tt>: Names associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer + # * <tt>:include</tt> - Names associations that should be loaded alongside. The symbols named refer # to already defined associations. See eager loading under Associations. - # * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example, want to do a join but not + # * <tt>:select</tt> - By default, this is "*" as in "SELECT * FROM", but can be changed if you, for example, want to do a join but not # include the joined columns. - # * <tt>:from</tt>: By default, this is the table name of the class, but can be changed to an alternate table name (or even the name + # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name # of a database view). - # * <tt>:readonly</tt>: Mark the returned records read-only so they cannot be saved or updated. - # * <tt>:lock</tt>: An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE". + # * <tt>:readonly</tt> - Mark the returned records read-only so they cannot be saved or updated. + # * <tt>:lock</tt> - An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE". # <tt>:lock => true</tt> gives connection's default exclusive lock, usually "FOR UPDATE". # - # Examples for find by id: + # ==== Examples + # + # # find by id # Person.find(1) # returns the object for ID = 1 # Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6) # Person.find([7, 17]) # returns an array for objects with IDs in (7, 17) @@ -486,17 +494,19 @@ module ActiveRecord #:nodoc: # provide since database rows are unordered. Give an explicit <tt>:order</tt> # to ensure the results are sorted. # - # Examples for find first: + # ==== Examples + # + # # find first # Person.find(:first) # returns the first object fetched by SELECT * FROM people # Person.find(:first, :conditions => [ "user_name = ?", user_name]) # Person.find(:first, :order => "created_on DESC", :offset => 5) # - # Examples for find last: + # # find last # Person.find(:last) # returns the last object fetched by SELECT * FROM people # Person.find(:last, :conditions => [ "user_name = ?", user_name]) # Person.find(:last, :order => "created_on DESC", :offset => 5) # - # Examples for find all: + # # find all # Person.find(:all) # returns an array of objects for all the rows fetched by SELECT * FROM people # Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50) # Person.find(:all, :conditions => { :friends => ["Bob", "Steve", "Fred"] } @@ -504,11 +514,12 @@ module ActiveRecord #:nodoc: # Person.find(:all, :include => [ :account, :friends ]) # Person.find(:all, :group => "category") # - # Example for find with a lock. Imagine two concurrent transactions: - # each will read person.visits == 2, add 1 to it, and save, resulting - # in two saves of person.visits = 3. By locking the row, the second + # Example for find with a lock: Imagine two concurrent transactions: + # each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting + # in two saves of <tt>person.visits = 3</tt>. By locking the row, the second # transaction has to wait until the first is finished; we get the - # expected person.visits == 4. + # expected <tt>person.visits == 4</tt>. + # # Person.transaction do # person = Person.find(1, :lock => true) # person.visits += 1 @@ -527,14 +538,14 @@ module ActiveRecord #:nodoc: end end - # This is an alias for find(:first). You can pass in all the same arguments to this method as you can - # to find(:first) + # A convenience wrapper for <tt>find(:first, *args)</tt>. You can pass in all the + # same arguments to this method as you can to <tt>find(:first)</tt>. def first(*args) find(:first, *args) end - # This is an alias for find(:last). You can pass in all the same arguments to this method as you can - # to find(:last) + # A convenience wrapper for <tt>find(:last, *args)</tt>. You can pass in all the + # same arguments to this method as you can to <tt>find(:last)</tt>. def last(*args) find(:last, *args) end @@ -545,8 +556,7 @@ module ActiveRecord #:nodoc: find(:all, *args) end - # - # Executes a custom sql query against your database and returns all the results. The results will + # Executes a custom SQL query against your database and returns all the results. The results will # be returned as an array with columns requested encapsulated as attributes of the model you call # this method from. If you call +Product.find_by_sql+ then the results will be returned in a Product # object with the attributes you specified in the SQL query. @@ -555,13 +565,13 @@ module ActiveRecord #:nodoc: # SELECT will be attributes of the model, whether or not they are columns of the corresponding # table. # - # The +sql+ parameter is a full sql query as a string. It will be called as is, there will be + # The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be # no database agnostic conversions performed. This should be a last resort because using, for example, # MySQL specific terms will lock you to using that particular database engine or require you to # change your call if you switch engines # # ==== Examples - # # A simple sql query spanning multiple tables + # # A simple SQL query spanning multiple tables # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id" # > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...] # @@ -859,9 +869,15 @@ module ActiveRecord #:nodoc: end - # Attributes named in this macro are protected from mass-assignment, such as <tt>new(attributes)</tt> and - # <tt>attributes=(attributes)</tt>. Their assignment will simply be ignored. Instead, you can use the direct writer - # methods to do assignment. This is meant to protect sensitive attributes from being overwritten by URL/form hackers. Example: + # Attributes named in this macro are protected from mass-assignment, + # such as <tt>new(attributes)</tt>, + # <tt>update_attributes(attributes)</tt>, or + # <tt>attributes=(attributes)</tt>. + # + # Mass-assignment to these attributes will simply be ignored, to assign + # to them you can use direct writer methods. This is meant to protect + # sensitive attributes from being overwritten by malicious users + # tampering with URLs or forms. # # class Customer < ActiveRecord::Base # attr_protected :credit_rating @@ -875,7 +891,8 @@ module ActiveRecord #:nodoc: # customer.credit_rating = "Average" # customer.credit_rating # => "Average" # - # To start from an all-closed default and enable attributes as needed, have a look at attr_accessible. + # To start from an all-closed default and enable attributes as needed, + # have a look at +attr_accessible+. def attr_protected(*attributes) write_inheritable_attribute("attr_protected", Set.new(attributes.map(&:to_s)) + (protected_attributes || [])) end @@ -885,19 +902,18 @@ module ActiveRecord #:nodoc: read_inheritable_attribute("attr_protected") end - # Similar to the attr_protected macro, this protects attributes of your model from mass-assignment, - # such as <tt>new(attributes)</tt> and <tt>attributes=(attributes)</tt> - # however, it does it in the opposite way. This locks all attributes and only allows access to the - # attributes specified. Assignment to attributes not in this list will be ignored and need to be set - # using the direct writer methods instead. This is meant to protect sensitive attributes from being - # overwritten by URL/form hackers. If you'd rather start from an all-open default and restrict - # attributes as needed, have a look at attr_protected. - # - # ==== Attributes - # - # * <tt>*attributes</tt> A comma separated list of symbols that represent columns _not_ to be protected + # Specifies a white list of model attributes that can be set via + # mass-assignment, such as <tt>new(attributes)</tt>, + # <tt>update_attributes(attributes)</tt>, or + # <tt>attributes=(attributes)</tt> # - # ==== Examples + # This is the opposite of the +attr_protected+ macro: Mass-assignment + # will only set attributes in this list, to assign to the rest of + # attributes you can use direct writer methods. This is meant to protect + # sensitive attributes from being overwritten by malicious users + # tampering with URLs or forms. If you'd rather start from an all-open + # default and restrict attributes as needed, have a look at + # +attr_protected+. # # class Customer < ActiveRecord::Base # attr_accessible :name, :nickname @@ -932,7 +948,7 @@ module ActiveRecord #:nodoc: # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object, # then specify the name of that attribute using this method and it will be handled automatically. # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that - # class on retrieval or +SerializationTypeMismatch+ will be raised. + # class on retrieval or SerializationTypeMismatch will be raised. # # ==== Attributes # @@ -955,12 +971,14 @@ module ActiveRecord #:nodoc: # Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending - # directly from ActiveRecord. So if the hierarchy looks like: Reply < Message < ActiveRecord, then Message is used + # directly from ActiveRecord::Base. So if the hierarchy looks like: Reply < Message < ActiveRecord::Base, then Message is used # to guess the table name even when called on Reply. The rules used to do the guess are handled by the Inflector class # in Active Support, which knows almost all common English inflections. You can add new inflections in config/initializers/inflections.rb. # # Nested classes are given table names prefixed by the singular form of - # the parent's table name. Enclosing modules are not considered. Examples: + # the parent's table name. Enclosing modules are not considered. + # + # ==== Examples # # class Invoice < ActiveRecord::Base; end; # file class table_name @@ -974,8 +992,8 @@ module ActiveRecord #:nodoc: # file class table_name # invoice/lineitem.rb Invoice::Lineitem lineitems # - # Additionally, the class-level table_name_prefix is prepended and the - # table_name_suffix is appended. So if you have "myapp_" as a prefix, + # Additionally, the class-level +table_name_prefix+ is prepended and the + # +table_name_suffix+ is appended. So if you have "myapp_" as a prefix, # the table name guess for an Invoice class becomes "myapp_invoices". # Invoice::Lineitem becomes "myapp_invoice_lineitems". # @@ -1054,8 +1072,6 @@ module ActiveRecord #:nodoc: # Sets the table name to use to the given value, or (if the value # is nil or false) to the value returned by the given block. # - # Example: - # # class Project < ActiveRecord::Base # set_table_name "project" # end @@ -1068,8 +1084,6 @@ module ActiveRecord #:nodoc: # or (if the value is nil or false) to the value returned by the given # block. # - # Example: - # # class Project < ActiveRecord::Base # set_primary_key "sysid" # end @@ -1082,8 +1096,6 @@ module ActiveRecord #:nodoc: # or (if the value # is nil or false) to the value returned by the # given block. # - # Example: - # # class Project < ActiveRecord::Base # set_inheritance_column do # original_inheritance_column + "_id" @@ -1105,8 +1117,6 @@ module ActiveRecord #:nodoc: # If a sequence name is not explicitly set when using PostgreSQL, it # will discover the sequence corresponding to your primary key for you. # - # Example: - # # class Project < ActiveRecord::Base # set_sequence_name "projectseq" # default would have been "project_seq" # end @@ -1266,7 +1276,7 @@ module ActiveRecord #:nodoc: class_of_active_record_descendant(self) end - # Set this to true if this is an abstract class (see #abstract_class?). + # Set this to true if this is an abstract class (see <tt>abstract_class?</tt>). attr_accessor :abstract_class # Returns whether this class is a base AR class. If A is a base class and @@ -1282,6 +1292,10 @@ module ActiveRecord #:nodoc: super end + def sti_name + store_full_sti_class ? name : name.demodulize + end + private def find_initial(options) options.update(:limit => 1) @@ -1441,12 +1455,16 @@ module ActiveRecord #:nodoc: # Nest the type name in the same module as this class. # Bar is "MyApp::Business::Bar" relative to MyApp::Business::Foo def type_name_with_module(type_name) - (/^::/ =~ type_name) ? type_name : "#{parent.name}::#{type_name}" + if store_full_sti_class + type_name + else + (/^::/ =~ type_name) ? type_name : "#{parent.name}::#{type_name}" + end end def construct_finder_sql(options) scope = scope(:find) - sql = "SELECT #{(scope && scope[:select]) || options[:select] || (options[:joins] && quoted_table_name + '.*') || '*'} " + sql = "SELECT #{options[:select] || (scope && scope[:select]) || (options[:joins] && quoted_table_name + '.*') || '*'} " sql << "FROM #{(scope && scope[:from]) || options[:from] || quoted_table_name} " add_joins!(sql, options, scope) @@ -1560,8 +1578,8 @@ module ActiveRecord #:nodoc: def type_condition quoted_inheritance_column = connection.quote_column_name(inheritance_column) - type_condition = subclasses.inject("#{quoted_table_name}.#{quoted_inheritance_column} = '#{store_full_sti_class ? name : name.demodulize}' ") do |condition, subclass| - condition << "OR #{quoted_table_name}.#{quoted_inheritance_column} = '#{store_full_sti_class ? subclass.name : subclass.name.demodulize}' " + type_condition = subclasses.inject("#{quoted_table_name}.#{quoted_inheritance_column} = '#{sti_name}' ") do |condition, subclass| + condition << "OR #{quoted_table_name}.#{quoted_inheritance_column} = '#{subclass.sti_name}' " end " (#{type_condition}) " @@ -1713,8 +1731,8 @@ module ActiveRecord #:nodoc: end - # Defines an "attribute" method (like #inheritance_column or - # #table_name). A new (class) method will be created with the + # Defines an "attribute" method (like +inheritance_column+ or + # +table_name+). A new (class) method will be created with the # given name. If a value is specified, the new method will # return that value (as a string). Otherwise, the given block # will be used to compute the value of the method. @@ -1891,7 +1909,7 @@ module ActiveRecord #:nodoc: end end - # Returns the class descending directly from ActiveRecord in the inheritance hierarchy. + # Returns the class descending directly from Active Record in the inheritance hierarchy. def class_of_active_record_descendant(klass) if klass.superclass == Base || klass.superclass.abstract_class? klass @@ -1902,12 +1920,12 @@ module ActiveRecord #:nodoc: end end - # Returns the name of the class descending directly from ActiveRecord in the inheritance hierarchy. + # Returns the name of the class descending directly from Active Record in the inheritance hierarchy. def class_name_of_active_record_descendant(klass) #:nodoc: klass.base_class.name end - # Accepts an array, hash, or string of sql conditions and sanitizes + # Accepts an array, hash, or string of SQL conditions and sanitizes # them into a valid SQL fragment for a WHERE clause. # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'" # { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id='4'" @@ -1923,7 +1941,7 @@ module ActiveRecord #:nodoc: end alias_method :sanitize_sql, :sanitize_sql_for_conditions - # Accepts an array, hash, or string of sql conditions and sanitizes + # Accepts an array, hash, or string of SQL conditions and sanitizes # them into a valid SQL fragment for a SET clause. # { :name => nil, :group_id => 4 } returns "name = NULL , group_id='4'" def sanitize_sql_for_assignment(assignments) @@ -1939,7 +1957,7 @@ module ActiveRecord #:nodoc: mapping.first.is_a?(Array) ? mapping : [mapping] end - # Accepts a hash of sql conditions and replaces those attributes + # Accepts a hash of SQL conditions and replaces those attributes # that correspond to a +composed_of+ relationship with their expanded # aggregate attribute values. # Given: @@ -2012,7 +2030,7 @@ module ActiveRecord #:nodoc: end # Accepts an array of conditions. The array has each value - # sanitized and interpolated into the sql statement. + # sanitized and interpolated into the SQL statement. # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'" def sanitize_sql_array(ary) statement, *values = ary @@ -2133,7 +2151,9 @@ module ActiveRecord #:nodoc: (id = self.id) ? id.to_s : nil # Be sure to stringify the id for routes end - # Returns a cache key that can be used to identify this record. Examples: + # Returns a cache key that can be used to identify this record. + # + # ==== Examples # # Product.new.cache_key # => "products/new" # Product.find(5).cache_key # => "products/5" (updated_at not available) @@ -2489,13 +2509,13 @@ module ActiveRecord #:nodoc: id end - # Sets the attribute used for single table inheritance to this class name if this is not the ActiveRecord descendent. - # Considering the hierarchy Reply < Message < ActiveRecord, this makes it possible to do Reply.new without having to - # set Reply[Reply.inheritance_column] = "Reply" yourself. No such attribute would be set for objects of the + # Sets the attribute used for single table inheritance to this class name if this is not the ActiveRecord::Base descendent. + # Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to do Reply.new without having to + # set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself. No such attribute would be set for objects of the # Message class in that example. def ensure_proper_type unless self.class.descends_from_active_record? - write_attribute(self.class.inheritance_column, store_full_sti_class ? self.class.name : self.class.name.demodulize) + write_attribute(self.class.inheritance_column, self.class.sti_name) end end @@ -2563,7 +2583,7 @@ module ActiveRecord #:nodoc: self.class.connection.quote(value, column) end - # Interpolate custom sql string in instance context. + # Interpolate custom SQL string in instance context. # Optional record argument is meant for custom insert_sql. def interpolate_sql(sql, record = nil) instance_eval("%@#{sql.gsub('@', '\@')}@") diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb index 3c5caefe3b..10e8330d1c 100644 --- a/activerecord/lib/active_record/calculations.rb +++ b/activerecord/lib/active_record/calculations.rb @@ -46,28 +46,28 @@ module ActiveRecord calculate(:count, *construct_count_options_from_args(*args)) end - # Calculates the average value on a given column. The value is returned as a float. See #calculate for examples with options. + # Calculates the average value on a given column. The value is returned as a float. See +calculate+ for examples with options. # # Person.average('age') def average(column_name, options = {}) calculate(:avg, column_name, options) end - # Calculates the minimum value on a given column. The value is returned with the same data type of the column. See #calculate for examples with options. + # Calculates the minimum value on a given column. The value is returned with the same data type of the column. See +calculate+ for examples with options. # # Person.minimum('age') def minimum(column_name, options = {}) calculate(:min, column_name, options) end - # Calculates the maximum value on a given column. The value is returned with the same data type of the column. See #calculate for examples with options. + # Calculates the maximum value on a given column. The value is returned with the same data type of the column. See +calculate+ for examples with options. # # Person.maximum('age') def maximum(column_name, options = {}) calculate(:max, column_name, options) end - # Calculates the sum of values on a given column. The value is returned with the same data type of the column. See #calculate for examples with options. + # Calculates the sum of values on a given column. The value is returned with the same data type of the column. See +calculate+ for examples with options. # # Person.sum('age') def sum(column_name, options = {}) @@ -245,12 +245,14 @@ module ActiveRecord options.assert_valid_keys(CALCULATIONS_OPTIONS) end - # Converts a given key to the value that the database adapter returns as - # a usable column name. - # users.id #=> users_id - # sum(id) #=> sum_id - # count(distinct users.id) #=> count_distinct_users_id - # count(*) #=> count_all + # Converts the given keys to the value that the database adapter returns as + # a usable column name: + # + # column_alias_for("users.id") # => "users_id" + # column_alias_for("sum(id)") # => "sum_id" + # column_alias_for("count(distinct users.id)") # => "count_distinct_users_id" + # column_alias_for("count(*)") # => "count_all" + # column_alias_for("count", "id") # => "count_id" def column_alias_for(*keys) connection.table_alias_for(keys.join(' ').downcase.gsub(/\*/, 'all').gsub(/\W+/, ' ').strip.gsub(/ +/, '_')) end diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb index a469af682b..6c2f65df05 100755 --- a/activerecord/lib/active_record/callbacks.rb +++ b/activerecord/lib/active_record/callbacks.rb @@ -50,7 +50,7 @@ module ActiveRecord # # == Inheritable callback queues # - # Besides the overwriteable callback methods, it's also possible to register callbacks through the use of the callback macros. + # Besides the overwritable callback methods, it's also possible to register callbacks through the use of the callback macros. # Their main advantage is that the macros add behavior into a callback queue that is kept intact down through an inheritance # hierarchy. Example: # @@ -161,7 +161,7 @@ module ActiveRecord # == <tt>before_validation*</tt> returning statements # # If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be aborted and <tt>Base#save</tt> will return +false+. - # If <tt>Base#save!</tt> is called it will raise a +RecordNotSaved+ exception. + # If Base#save! is called it will raise a RecordNotSaved exception. # Nothing will be appended to the errors object. # # == Canceling callbacks diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb index 34627dfaf9..2a8807fb78 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb @@ -193,7 +193,7 @@ module ActiveRecord # :database => "path/to/dbfile" # ) # - # Also accepts keys as strings (for parsing from yaml for example): + # Also accepts keys as strings (for parsing from YAML for example): # # ActiveRecord::Base.establish_connection( # "adapter" => "sqlite", diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb index 589acd3945..5358491cde 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb @@ -29,7 +29,7 @@ module ActiveRecord end # Returns an array of arrays containing the field values. - # Order is the same as that returned by #columns. + # Order is the same as that returned by +columns+. def select_rows(sql, name = nil) raise NotImplementedError, "select_rows is an abstract method" end @@ -93,7 +93,7 @@ module ActiveRecord # done if the transaction block raises an exception or returns false. def rollback_db_transaction() end - # Alias for #add_limit_offset!. + # Alias for <tt>add_limit_offset!</tt>. def add_limit!(sql, options) add_limit_offset!(sql, options) if options end @@ -106,11 +106,16 @@ module ActiveRecord # SELECT * FROM suppliers LIMIT 10 OFFSET 50 def add_limit_offset!(sql, options) if limit = options[:limit] - sql << " LIMIT #{limit}" + sql << " LIMIT #{sanitize_limit(limit)}" if offset = options[:offset] - sql << " OFFSET #{offset}" + sql << " OFFSET #{offset.to_i}" end end + sql + end + + def sanitize_limit(limit) + limit.to_s[/,/] ? limit.split(',').map{ |i| i.to_i }.join(',') : limit.to_i end # Appends a locking clause to an SQL statement. diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb index fdb18b234c..f968b9b173 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -16,9 +16,9 @@ module ActiveRecord # Instantiates a new column in the table. # - # +name+ is the column's name, as in <tt><b>supplier_id</b> int(11)</tt>. - # +default+ is the type-casted default value, such as <tt>sales_stage varchar(20) default <b>'new'</b></tt>. - # +sql_type+ is only used to extract the column's length, if necessary. For example, <tt>company_name varchar(<b>60</b>)</tt>. + # +name+ is the column's name, such as <tt>supplier_id</tt> in <tt>supplier_id int(11)</tt>. + # +default+ is the type-casted default value, such as +new+ in <tt>sales_stage varchar(20) default 'new'</tt>. + # +sql_type+ is only used to extract the column's length, if necessary. For example +60+ in <tt>company_name varchar(60)</tt>. # +null+ determines if this column allows +NULL+ values. def initialize(name, default, sql_type = nil, null = true) @name, @sql_type, @null = name, sql_type, null @@ -92,7 +92,7 @@ module ActiveRecord # Returns the human name of the column name. # # ===== Examples - # Column.new('sales_stage', ...).human_name #=> 'Sales stage' + # Column.new('sales_stage', ...).human_name # => 'Sales stage' def human_name Base.human_attribute_name(@name) end @@ -270,7 +270,7 @@ module ActiveRecord end # Represents a SQL table in an abstract way. - # Columns are stored as a ColumnDefinition in the #columns attribute. + # Columns are stored as a ColumnDefinition in the +columns+ attribute. class TableDefinition attr_accessor :columns @@ -350,28 +350,28 @@ module ActiveRecord # == Examples # # Assuming td is an instance of TableDefinition # td.column(:granted, :boolean) - # #=> granted BOOLEAN + # # granted BOOLEAN # # td.column(:picture, :binary, :limit => 2.megabytes) - # #=> picture BLOB(2097152) + # # => picture BLOB(2097152) # # td.column(:sales_stage, :string, :limit => 20, :default => 'new', :null => false) - # #=> sales_stage VARCHAR(20) DEFAULT 'new' NOT NULL + # # => sales_stage VARCHAR(20) DEFAULT 'new' NOT NULL # - # def.column(:bill_gates_money, :decimal, :precision => 15, :scale => 2) - # #=> bill_gates_money DECIMAL(15,2) + # td.column(:bill_gates_money, :decimal, :precision => 15, :scale => 2) + # # => bill_gates_money DECIMAL(15,2) # - # def.column(:sensor_reading, :decimal, :precision => 30, :scale => 20) - # #=> sensor_reading DECIMAL(30,20) + # td.column(:sensor_reading, :decimal, :precision => 30, :scale => 20) + # # => sensor_reading DECIMAL(30,20) # # # While <tt>:scale</tt> defaults to zero on most databases, it # # probably wouldn't hurt to include it. - # def.column(:huge_integer, :decimal, :precision => 30) - # #=> huge_integer DECIMAL(30) + # td.column(:huge_integer, :decimal, :precision => 30) + # # => huge_integer DECIMAL(30) # # == Short-hand examples # - # Instead of calling column directly, you can also work with the short-hand definitions for the default types. + # Instead of calling +column+ directly, you can also work with the short-hand definitions for the default types. # They use the type as the method name instead of as a parameter and allow for multiple columns to be defined # in a single statement. # @@ -395,7 +395,7 @@ module ActiveRecord # end # # There's a short-hand method for each of the type values declared at the top. And then there's - # TableDefinition#timestamps that'll add created_at and updated_at as datetimes. + # TableDefinition#timestamps that'll add created_at and +updated_at+ as datetimes. # # TableDefinition#references will add an appropriately-named _id column, plus a corresponding _type # column if the <tt>:polymorphic</tt> option is supplied. If <tt>:polymorphic</tt> is a hash of options, these will be diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb index ac24e920fe..a2a1bb8c82 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -32,7 +32,7 @@ module ActiveRecord def columns(table_name, name = nil) end # Creates a new table - # There are two ways to work with #create_table. You can use the block + # There are two ways to work with +create_table+. You can use the block # form or the regular form, like this: # # === Block form @@ -302,7 +302,7 @@ module ActiveRecord def dump_schema_information #:nodoc: sm_table = ActiveRecord::Migrator.schema_migrations_table_name migrated = select_values("SELECT version FROM #{sm_table}") - migrated.map { |v| "INSERT INTO #{sm_table} (version) VALUES ('#{v}');" }.join("\n") + migrated.map { |v| "INSERT INTO #{sm_table} (version) VALUES ('#{v}');" }.join("\n\n") end # Should not be called normally, but this operation is non-destructive. @@ -372,7 +372,7 @@ module ActiveRecord def add_column_options!(sql, options) #:nodoc: sql << " DEFAULT #{quote(options[:default], options[:column])}" if options_include_default?(options) - # must explcitly check for :null to allow change_column to work on migrations + # must explicitly check for :null to allow change_column to work on migrations if options.has_key? :null if options[:null] == false sql << " NOT NULL" diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index 8c286f64db..f48b107a2a 100755 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -128,15 +128,11 @@ module ActiveRecord protected def log(sql, name) if block_given? - if @logger and @logger.debug? - result = nil - seconds = Benchmark.realtime { result = yield } - @runtime += seconds - log_info(sql, name, seconds) - result - else - yield - end + result = nil + seconds = Benchmark.realtime { result = yield } + @runtime += seconds + log_info(sql, name, seconds) + result else log_info(sql, name, 0) nil diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index f00a2c8950..653b45021d 100755 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -336,10 +336,11 @@ module ActiveRecord def add_limit_offset!(sql, options) #:nodoc: if limit = options[:limit] + limit = sanitize_limit(limit) unless offset = options[:offset] sql << " LIMIT #{limit}" else - sql << " LIMIT #{offset}, #{limit}" + sql << " LIMIT #{offset.to_i}, #{limit}" end end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 2ec2d80af4..7dc7398b0a 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -776,7 +776,7 @@ module ActiveRecord # Returns an ORDER BY clause for the passed order option. # # PostgreSQL does not allow arbitrary ordering when using DISTINCT ON, so we work around this - # by wrapping the sql as a sub-select and ordering in that query. + # by wrapping the +sql+ string as a sub-select and ordering in that query. def add_order_by_for_association_limiting!(sql, options) #:nodoc: return sql if options[:order].blank? @@ -805,7 +805,7 @@ module ActiveRecord end private - # The internal PostgreSQL identifer of the money data type. + # The internal PostgreSQL identifier of the money data type. MONEY_COLUMN_TYPE_OID = 790 #:nodoc: # Connects to a PostgreSQL server and sets up the adapter depending on the diff --git a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb index 8abbc6d0a4..51cfd10e5c 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb @@ -214,6 +214,10 @@ module ActiveRecord end def add_column(table_name, column_name, type, options = {}) #:nodoc: + if @connection.respond_to?(:transaction_active?) && @connection.transaction_active? + raise StatementInvalid, 'Cannot add columns to a SQLite database while inside a transaction' + end + super(table_name, column_name, type, options) # See last paragraph on http://www.sqlite.org/lang_altertable.html execute "VACUUM" diff --git a/activerecord/lib/active_record/dirty.rb b/activerecord/lib/active_record/dirty.rb index 6034963811..2917f24c20 100644 --- a/activerecord/lib/active_record/dirty.rb +++ b/activerecord/lib/active_record/dirty.rb @@ -40,9 +40,10 @@ module ActiveRecord base.alias_method_chain :save, :dirty base.alias_method_chain :save!, :dirty base.alias_method_chain :update, :dirty + base.alias_method_chain :reload, :dirty base.superclass_delegating_accessor :partial_updates - base.partial_updates = false + base.partial_updates = true end # Do any attributes have unsaved changes? @@ -61,7 +62,7 @@ module ActiveRecord changed_attributes.keys end - # Map of changed attrs => [original value, new value] + # Map of changed attrs => [original value, new value]. # person.changes # => {} # person.name = 'bob' # person.changes # => { 'name' => ['bill', 'bob'] } @@ -84,28 +85,35 @@ module ActiveRecord status end + # <tt>reload</tt> the record and clears changed attributes. + def reload_with_dirty(*args) #:nodoc: + record = reload_without_dirty(*args) + changed_attributes.clear + record + end + private - # Map of change attr => original value. + # Map of change <tt>attr => original value</tt>. def changed_attributes @changed_attributes ||= {} end - # Handle *_changed? for method_missing. + # Handle <tt>*_changed?</tt> for +method_missing+. def attribute_changed?(attr) changed_attributes.include?(attr) end - # Handle *_change for method_missing. + # Handle <tt>*_change</tt> for +method_missing+. def attribute_change(attr) [changed_attributes[attr], __send__(attr)] if attribute_changed?(attr) end - # Handle *_was for method_missing. + # Handle <tt>*_was</tt> for +method_missing+. def attribute_was(attr) attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr) end - # Handle *_will_change! for method_missing. + # Handle <tt>*_will_change!</tt> for +method_missing+. def attribute_will_change!(attr) changed_attributes[attr] = clone_attribute_value(:read_attribute, attr) end @@ -117,14 +125,7 @@ module ActiveRecord # The attribute already has an unsaved change. unless changed_attributes.include?(attr) old = clone_attribute_value(:read_attribute, attr) - - # Remember the original value if it's different. - typecasted = if column = column_for_attribute(attr) - column.type_cast(value) - else - value - end - changed_attributes[attr] = old unless old == typecasted + changed_attributes[attr] = old if field_changed?(attr, old, value) end # Carry on. @@ -138,5 +139,20 @@ module ActiveRecord update_without_dirty end end + + def field_changed?(attr, old, value) + if column = column_for_attribute(attr) + if column.type == :integer && column.null && old.nil? + # For nullable integer columns, NULL gets stored in database for blank (i.e. '') values. + # Hence we don't record it as a change if the value changes from nil to ''. + value = nil if value.blank? + else + value = column.type_cast(value) + end + end + + old != value + end + end end diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index ac06cdbe43..c4cbe5d52f 100755 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -33,8 +33,8 @@ end # # Unlike single-file fixtures, YAML fixtures are stored in a single file per model, which are placed in the directory appointed # by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is automatically configured for Rails, so you can just -# put your files in <your-rails-app>/test/fixtures/). The fixture file ends with the .yml file extension (Rails example: -# "<your-rails-app>/test/fixtures/web_sites.yml"). The format of a YAML fixture file looks like this: +# put your files in <tt><your-rails-app>/test/fixtures/</tt>). The fixture file ends with the <tt>.yml</tt> file extension (Rails example: +# <tt><your-rails-app>/test/fixtures/web_sites.yml</tt>). The format of a YAML fixture file looks like this: # # rubyonrails: # id: 1 @@ -67,7 +67,8 @@ end # = CSV fixtures # # Fixtures can also be kept in the Comma Separated Value format. Akin to YAML fixtures, CSV fixtures are stored -# in a single file, but instead end with the .csv file extension (Rails example: "<your-rails-app>/test/fixtures/web_sites.csv") +# in a single file, but instead end with the <tt>.csv</tt> file extension +# (Rails example: <tt><your-rails-app>/test/fixtures/web_sites.csv</tt>). # # The format of this type of fixture file is much more compact than the others, but also a little harder to read by us # humans. The first line of the CSV file is a comma-separated list of field names. The rest of the file is then comprised @@ -93,11 +94,11 @@ end # This type of fixture was the original format for Active Record that has since been deprecated in favor of the YAML and CSV formats. # Fixtures for this format are created by placing text files in a sub-directory (with the name of the model) to the directory # appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is automatically configured for Rails, so you can just -# put your files in <your-rails-app>/test/fixtures/<your-model-name>/ -- like <your-rails-app>/test/fixtures/web_sites/ for the WebSite -# model). +# put your files in <tt><your-rails-app>/test/fixtures/<your-model-name>/</tt> -- +# like <tt><your-rails-app>/test/fixtures/web_sites/</tt> for the WebSite model). # # Each text file placed in this directory represents a "record". Usually these types of fixtures are named without -# extensions, but if you are on a Windows machine, you might consider adding .txt as the extension. Here's what the +# extensions, but if you are on a Windows machine, you might consider adding <tt>.txt</tt> as the extension. Here's what the # above example might look like: # # web_sites/google @@ -138,20 +139,20 @@ end # # In addition to being available in the database, the fixtures are also loaded into a hash stored in an instance variable # of the test case. It is named after the symbol... so, in our example, there would be a hash available called -# @web_sites. This is where the "fixture name" comes into play. +# <tt>@web_sites</tt>. This is where the "fixture name" comes into play. # -# On top of that, each record is automatically "found" (using Model.find(id)) and placed in the instance variable of its name. -# So for the YAML fixtures, we'd get @rubyonrails and @google, which could be interrogated using regular Active Record semantics: +# On top of that, each record is automatically "found" (using <tt>Model.find(id)</tt>) and placed in the instance variable of its name. +# So for the YAML fixtures, we'd get <tt>@rubyonrails</tt> and <tt>@google</tt>, which could be interrogated using regular Active Record semantics: # # # test if the object created from the fixture data has the same attributes as the data itself # def test_find # assert_equal @web_sites["rubyonrails"]["name"], @rubyonrails.name # end # -# As seen above, the data hash created from the YAML fixtures would have @web_sites["rubyonrails"]["url"] return -# "http://www.rubyonrails.org" and @web_sites["google"]["name"] would return "Google". The same fixtures, but loaded -# from a CSV fixture file, would be accessible via @web_sites["web_site_1"]["name"] == "Ruby on Rails" and have the individual -# fixtures available as instance variables @web_site_1 and @web_site_2. +# As seen above, the data hash created from the YAML fixtures would have <tt>@web_sites["rubyonrails"]["url"]</tt> return +# "http://www.rubyonrails.org" and <tt>@web_sites["google"]["name"]</tt> would return "Google". The same fixtures, but loaded +# from a CSV fixture file, would be accessible via <tt>@web_sites["web_site_1"]["name"] == "Ruby on Rails"</tt> and have the individual +# fixtures available as instance variables <tt>@web_site_1</tt> and <tt>@web_site_2</tt>. # # If you do not wish to use instantiated fixtures (usually for performance reasons) there are two options. # @@ -184,7 +185,7 @@ end # # This will create 1000 very simple YAML fixtures. # -# Using ERb, you can also inject dynamic values into your fixtures with inserts like <%= Date.today.strftime("%Y-%m-%d") %>. +# Using ERb, you can also inject dynamic values into your fixtures with inserts like <tt><%= Date.today.strftime("%Y-%m-%d") %></tt>. # This is however a feature to be used with some caution. The point of fixtures are that they're stable units of predictable # sample data. If you feel that you need to inject dynamic values, then perhaps you should reexamine whether your application # is properly testable. Hence, dynamic values in fixtures are to be considered a code smell. @@ -257,7 +258,7 @@ end # reginald: # generated id: 324201669 # name: Reginald the Pirate # -# ActiveRecord looks at the fixture's model class, discovers the correct +# Active Record looks at the fixture's model class, discovers the correct # primary key, and generates it right before inserting the fixture # into the database. # @@ -267,7 +268,7 @@ end # == Label references for associations (belongs_to, has_one, has_many) # # Specifying foreign keys in fixtures can be very fragile, not to -# mention difficult to read. Since ActiveRecord can figure out the ID of +# mention difficult to read. Since Active Record can figure out the ID of # any fixture from its label, you can specify FK's by label instead of ID. # # === belongs_to @@ -304,15 +305,15 @@ end # name: George the Monkey # pirate: reginald # -# Pow! All is made clear. ActiveRecord reflects on the fixture's model class, +# Pow! All is made clear. Active Record reflects on the fixture's model class, # finds all the +belongs_to+ associations, and allows you to specify # a target *label* for the *association* (monkey: george) rather than -# a target *id* for the *FK* (monkey_id: 1). +# a target *id* for the *FK* (<tt>monkey_id: 1</tt>). # # ==== Polymorphic belongs_to # # Supporting polymorphic relationships is a little bit more complicated, since -# ActiveRecord needs to know what type your association is pointing at. Something +# Active Record needs to know what type your association is pointing at. Something # like this should look familiar: # # ### in fruit.rb @@ -332,7 +333,7 @@ end # apple: # eater: george (Monkey) # -# Just provide the polymorphic target type and ActiveRecord will take care of the rest. +# Just provide the polymorphic target type and Active Record will take care of the rest. # # === has_and_belongs_to_many # @@ -395,15 +396,15 @@ end # # Zap! No more fruits_monkeys.yml file. We've specified the list of fruits # on George's fixture, but we could've just as easily specified a list -# of monkeys on each fruit. As with +belongs_to+, ActiveRecord reflects on +# of monkeys on each fruit. As with +belongs_to+, Active Record reflects on # the fixture's model class and discovers the +has_and_belongs_to_many+ # associations. # # == Autofilled timestamp columns # -# If your table/model specifies any of ActiveRecord's -# standard timestamp columns (created_at, created_on, updated_at, updated_on), -# they will automatically be set to Time.now. +# If your table/model specifies any of Active Record's +# standard timestamp columns (+created_at+, +created_on+, +updated_at+, +updated_on+), +# they will automatically be set to <tt>Time.now</tt>. # # If you've set specific values, they'll be left alone. # diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb index 65f88cfdc7..c66034d18b 100644 --- a/activerecord/lib/active_record/locking/optimistic.rb +++ b/activerecord/lib/active_record/locking/optimistic.rb @@ -107,20 +107,20 @@ module ActiveRecord end # Is optimistic locking enabled for this table? Returns true if the - # #lock_optimistically flag is set to true (which it is, by default) - # and the table includes the #locking_column column (defaults to - # lock_version). + # +lock_optimistically+ flag is set to true (which it is, by default) + # and the table includes the +locking_column+ column (defaults to + # +lock_version+). def locking_enabled? lock_optimistically && columns_hash[locking_column] end - # Set the column to use for optimistic locking. Defaults to lock_version. + # Set the column to use for optimistic locking. Defaults to +lock_version+. def set_locking_column(value = nil, &block) define_attr_method :locking_column, value, &block value end - # The version column used for optimistic locking. Defaults to lock_version. + # The version column used for optimistic locking. Defaults to +lock_version+. def locking_column reset_locking_column end @@ -130,12 +130,12 @@ module ActiveRecord connection.quote_column_name(locking_column) end - # Reset the column used for optimistic locking back to the lock_version default. + # Reset the column used for optimistic locking back to the +lock_version+ default. def reset_locking_column set_locking_column DEFAULT_LOCKING_COLUMN end - # make sure the lock version column gets updated when counters are + # Make sure the lock version column gets updated when counters are # updated. def update_counters_with_lock(id, counters) counters = counters.merge(locking_column => 1) if locking_enabled? diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index 5cc9f4e197..b47b01e99a 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -208,7 +208,7 @@ module ActiveRecord # # You can quiet them down by setting ActiveRecord::Migration.verbose = false. # - # You can also insert your own messages and benchmarks by using the #say_with_time + # You can also insert your own messages and benchmarks by using the +say_with_time+ # method: # # def self.up @@ -377,7 +377,7 @@ module ActiveRecord end def proper_table_name(name) - # Use the ActiveRecord objects own table_name, or pre/suffix from ActiveRecord::Base if name is a symbol/string + # Use the Active Record objects own table_name, or pre/suffix from ActiveRecord::Base if name is a symbol/string name.table_name rescue "#{ActiveRecord::Base.table_name_prefix}#{name}#{ActiveRecord::Base.table_name_suffix}" end end diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb index d43ebefc3b..b0c8a8b815 100644 --- a/activerecord/lib/active_record/named_scope.rb +++ b/activerecord/lib/active_record/named_scope.rb @@ -2,9 +2,7 @@ module ActiveRecord module NamedScope # All subclasses of ActiveRecord::Base have two named_scopes: # * <tt>all</tt>, which is similar to a <tt>find(:all)</tt> query, and - # * <tt>scoped</tt>, which allows for the creation of anonymous scopes, on the fly: - # - # Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions) + # * <tt>scoped</tt>, which allows for the creation of anonymous scopes, on the fly: <tt>Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions)</tt> # # These anonymous scopes tend to be useful when procedurally generating complex queries, where passing # intermediate values (scopes) around as first-class objects is convenient. @@ -41,7 +39,7 @@ module ActiveRecord # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> returns the number of garments # for which these criteria obtain. Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>. # - # All scopes are available as class methods on the ActiveRecord descendent upon which the scopes were defined. But they are also available to + # All scopes are available as class methods on the ActiveRecord::Base descendent upon which the scopes were defined. But they are also available to # <tt>has_many</tt> associations. If, # # class Person < ActiveRecord::Base @@ -102,7 +100,13 @@ module ActiveRecord class Scope attr_reader :proxy_scope, :proxy_options - [].methods.each { |m| delegate m, :to => :proxy_found unless m =~ /(^__|^nil\?|^send|class|extend|find|count|sum|average|maximum|minimum|paginate)/ } + + [].methods.each do |m| + unless m =~ /(^__|^nil\?|^send|^object_id$|class|extend|find|count|sum|average|maximum|minimum|paginate|first|last|empty?)/ + delegate m, :to => :proxy_found + end + end + delegate :scopes, :with_scope, :to => :proxy_scope def initialize(proxy_scope, options, &block) @@ -115,6 +119,26 @@ module ActiveRecord load_found; self end + def first(*args) + if args.first.kind_of?(Integer) || (@found && !args.first.kind_of?(Hash)) + proxy_found.first(*args) + else + find(:first, *args) + end + end + + def last(*args) + if args.first.kind_of?(Integer) || (@found && !args.first.kind_of?(Hash)) + proxy_found.last(*args) + else + find(:last, *args) + end + end + + def empty? + @found ? @found.empty? : count.zero? + end + protected def proxy_found @found || load_found @@ -136,4 +160,4 @@ module ActiveRecord end end end -end
\ No newline at end of file +end diff --git a/activerecord/lib/active_record/observer.rb b/activerecord/lib/active_record/observer.rb index 2b0728fc25..6e55e36b7d 100644 --- a/activerecord/lib/active_record/observer.rb +++ b/activerecord/lib/active_record/observer.rb @@ -19,7 +19,7 @@ module ActiveRecord # # Same as above, just using explicit class references # ActiveRecord::Base.observers = Cacher, GarbageCollector # - # Note: Setting this does not instantiate the observers yet. #instantiate_observers is + # Note: Setting this does not instantiate the observers yet. +instantiate_observers+ is # called during startup, and before each development request. def observers=(*observers) @observers = observers.flatten @@ -30,7 +30,7 @@ module ActiveRecord @observers ||= [] end - # Instantiate the global ActiveRecord observers + # Instantiate the global Active Record observers. def instantiate_observers return if @observers.blank? @observers.each do |observer| diff --git a/activerecord/lib/active_record/schema.rb b/activerecord/lib/active_record/schema.rb index d6b254fcf9..8a32cf1ca2 100644 --- a/activerecord/lib/active_record/schema.rb +++ b/activerecord/lib/active_record/schema.rb @@ -30,8 +30,8 @@ module ActiveRecord # Eval the given block. All methods available to the current connection # adapter are available within the block, so you can easily use the - # database definition DSL to build up your schema (#create_table, - # #add_index, etc.). + # database definition DSL to build up your schema (+create_table+, + # +add_index+, etc.). # # The +info+ hash is optional, and if given is used to define metadata # about the current schema (currently, only the schema's version): diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb index 826662d3ee..b90ed88c6b 100644 --- a/activerecord/lib/active_record/schema_dumper.rb +++ b/activerecord/lib/active_record/schema_dumper.rb @@ -38,7 +38,7 @@ module ActiveRecord stream.puts <<HEADER # This file is auto-generated from the current state of the database. Instead of editing this file, -# please use the migrations feature of ActiveRecord to incrementally modify your database, and +# please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need diff --git a/activerecord/lib/active_record/serializers/xml_serializer.rb b/activerecord/lib/active_record/serializers/xml_serializer.rb index 2d0887ecf0..d171b742f5 100644 --- a/activerecord/lib/active_record/serializers/xml_serializer.rb +++ b/activerecord/lib/active_record/serializers/xml_serializer.rb @@ -273,14 +273,14 @@ module ActiveRecord #:nodoc: end # There is a significant speed improvement if the value - # does not need to be escaped, as #tag! escapes all values + # does not need to be escaped, as <tt>tag!</tt> escapes all values # to ensure that valid XML is generated. For known binary # values, it is at least an order of magnitude faster to # Base64 encode binary values and directly put them in the # output XML than to pass the original value or the Base64 - # encoded value to the #tag! method. It definitely makes + # encoded value to the <tt>tag!</tt> method. It definitely makes # no sense to Base64 encode the value and then give it to - # #tag!, since that just adds additional overhead. + # <tt>tag!</tt>, since that just adds additional overhead. def needs_encoding? ![ :binary, :date, :datetime, :boolean, :float, :integer ].include?(type) end diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb index 13cb5f3f48..3b6835762c 100644 --- a/activerecord/lib/active_record/transactions.rb +++ b/activerecord/lib/active_record/transactions.rb @@ -30,9 +30,9 @@ module ActiveRecord # Exceptions will force a ROLLBACK that returns the database to the state before the transaction was begun. Be aware, though, # that the objects will _not_ have their instance data returned to their pre-transactional state. # - # == Different ActiveRecord classes in a single transaction + # == Different Active Record classes in a single transaction # - # Though the transaction class method is called on some ActiveRecord class, + # Though the transaction class method is called on some Active Record class, # the objects within the transaction block need not all be instances of # that class. # In this example a <tt>Balance</tt> record is transactionally saved even diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index b3a75121ed..52805ea851 100755 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -1,5 +1,5 @@ module ActiveRecord - # Raised by save! and create! when the record is invalid. Use the + # Raised by <tt>save!</tt> and <tt>create!</tt> when the record is invalid. Use the # +record+ method to retrieve the record which did not validate. # begin # complex_operation_that_calls_save!_internally @@ -52,7 +52,7 @@ module ActiveRecord # Adds an error to the base object instead of any particular attribute. This is used # to report errors that don't tie to any specific attribute, but rather to the object # as a whole. These error messages don't get prepended with any field name when iterating - # with each_full, so they should be complete sentences. + # with +each_full+, so they should be complete sentences. def add_to_base(msg) add(:base, msg) end @@ -97,7 +97,7 @@ module ActiveRecord !@errors[attribute.to_s].nil? end - # Returns nil, if no errors are associated with the specified +attribute+. + # Returns +nil+, if no errors are associated with the specified +attribute+. # Returns the error message, if one error is associated with the specified +attribute+. # Returns an array of error messages, if more than one error is associated with the specified +attribute+. # @@ -118,7 +118,7 @@ module ActiveRecord alias :[] :on - # Returns errors assigned to the base object through add_to_base according to the normal rules of on(attribute). + # Returns errors assigned to the base object through +add_to_base+ according to the normal rules of <tt>on(attribute)</tt>. def on_base on(:base) end @@ -131,15 +131,15 @@ module ActiveRecord # end # # company = Company.create(:address => '123 First St.') - # company.errors.each{|attr,msg| puts "#{attr} - #{msg}" } # => - # name - is too short (minimum is 5 characters) - # name - can't be blank - # address - can't be blank + # company.errors.each{|attr,msg| puts "#{attr} - #{msg}" } + # # => name - is too short (minimum is 5 characters) + # # name - can't be blank + # # address - can't be blank def each @errors.each_key { |attr| @errors[attr].each { |msg| yield attr, msg } } end - # Yields each full error message added. So Person.errors.add("first_name", "can't be empty") will be returned + # Yields each full error message added. So <tt>Person.errors.add("first_name", "can't be empty")</tt> will be returned # through iteration as "First name can't be empty". # # class Company < ActiveRecord::Base @@ -148,10 +148,10 @@ module ActiveRecord # end # # company = Company.create(:address => '123 First St.') - # company.errors.each_full{|msg| puts msg } # => - # Name is too short (minimum is 5 characters) - # Name can't be blank - # Address can't be blank + # company.errors.each_full{|msg| puts msg } + # # => Name is too short (minimum is 5 characters) + # # Name can't be blank + # # Address can't be blank def each_full full_messages.each { |msg| yield msg } end @@ -164,8 +164,8 @@ module ActiveRecord # end # # company = Company.create(:address => '123 First St.') - # company.errors.full_messages # => - # ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"] + # company.errors.full_messages + # # => ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"] def full_messages full_messages = [] @@ -209,13 +209,13 @@ module ActiveRecord # end # # company = Company.create(:address => '123 First St.') - # company.errors.to_xml # => - # <?xml version="1.0" encoding="UTF-8"?> - # <errors> - # <error>Name is too short (minimum is 5 characters)</error> - # <error>Name can't be blank</error> - # <error>Address can't be blank</error> - # </errors> + # company.errors.to_xml + # # => <?xml version="1.0" encoding="UTF-8"?> + # # <errors> + # # <error>Name is too short (minimum is 5 characters)</error> + # # <error>Name can't be blank</error> + # # <error>Address can't be blank</error> + # # </errors> def to_xml(options={}) options[:root] ||= "errors" options[:indent] ||= 2 @@ -261,7 +261,7 @@ module ActiveRecord # person.errors.on "phone_number" # => "has invalid format" # person.errors.each_full { |msg| puts msg } # # => "Last name can't be empty\n" + - # "Phone number has invalid format" + # # "Phone number has invalid format" # # person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" } # person.save # => true (and person is now saved in the database) @@ -301,7 +301,7 @@ module ActiveRecord :odd => 'odd?', :even => 'even?' }.freeze # Adds a validation method or block to the class. This is useful when - # overriding the #validate instance method becomes too unwieldly and + # overriding the +validate+ instance method becomes too unwieldy and # you're looking for more descriptive declaration of your validations. # # This can be done with a symbol pointing to a method: @@ -326,7 +326,7 @@ module ActiveRecord # end # end # - # This usage applies to #validate_on_create and #validate_on_update as well. + # This usage applies to +validate_on_create+ and +validate_on_update+ as well. # Validates each attribute against a block. # @@ -692,7 +692,7 @@ module ActiveRecord raise(ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash") unless configuration[:with].is_a?(Regexp) validates_each(attr_names, configuration) do |record, attr_name, value| - record.errors.add(attr_name, configuration[:message]) unless value.to_s =~ configuration[:with] + record.errors.add(attr_name, configuration[:message] % value) unless value.to_s =~ configuration[:with] end end diff --git a/activerecord/lib/active_record/version.rb b/activerecord/lib/active_record/version.rb index 1463e84764..aaadef9979 100644 --- a/activerecord/lib/active_record/version.rb +++ b/activerecord/lib/active_record/version.rb @@ -1,8 +1,8 @@ module ActiveRecord module VERSION #:nodoc: MAJOR = 2 - MINOR = 0 - TINY = 991 + MINOR = 1 + TINY = 0 STRING = [MAJOR, MINOR, TINY].join('.') end diff --git a/activerecord/test/cases/active_schema_test_mysql.rb b/activerecord/test/cases/active_schema_test_mysql.rb index ddf3e82162..2a42dc3517 100644 --- a/activerecord/test/cases/active_schema_test_mysql.rb +++ b/activerecord/test/cases/active_schema_test_mysql.rb @@ -40,47 +40,56 @@ class ActiveSchemaTest < ActiveRecord::TestCase end def test_add_timestamps - #we need to actually modify some data, so we make execute to point to the original method - ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do - alias_method :execute_with_stub, :execute - alias_method :execute, :execute_without_stub - end - ActiveRecord::Base.connection.create_table :delete_me do |t| - end - ActiveRecord::Base.connection.add_timestamps :delete_me - assert_equal ActiveRecord::Base.connection.execute("SHOW FIELDS FROM delete_me where FIELD='updated_at' AND TYPE='datetime'").num_rows, 1 - assert_equal ActiveRecord::Base.connection.execute("SHOW FIELDS FROM delete_me where FIELD='created_at' AND TYPE='datetime'").num_rows, 1 - ensure - ActiveRecord::Base.connection.drop_table :delete_me rescue nil - #before finishing, we restore the alias to the mock-up method - ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do - alias_method :execute, :execute_with_stub + with_real_execute do + begin + ActiveRecord::Base.connection.create_table :delete_me do |t| + end + ActiveRecord::Base.connection.add_timestamps :delete_me + assert column_present?('delete_me', 'updated_at', 'datetime') + assert column_present?('delete_me', 'created_at', 'datetime') + ensure + ActiveRecord::Base.connection.drop_table :delete_me rescue nil + end end end def test_remove_timestamps - #we need to actually modify some data, so we make execute to point to the original method - ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do - alias_method :execute_with_stub, :execute - alias_method :execute, :execute_without_stub - end - ActiveRecord::Base.connection.create_table :delete_me do |t| - t.timestamps - end - ActiveRecord::Base.connection.remove_timestamps :delete_me - assert_equal ActiveRecord::Base.connection.execute("SHOW FIELDS FROM delete_me where FIELD='updated_at' AND TYPE='datetime'").num_rows, 0 - assert_equal ActiveRecord::Base.connection.execute("SHOW FIELDS FROM delete_me where FIELD='created_at' AND TYPE='datetime'").num_rows, 0 - ensure - ActiveRecord::Base.connection.drop_table :delete_me rescue nil - #before finishing, we restore the alias to the mock-up method - ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do - alias_method :execute, :execute_with_stub + with_real_execute do + begin + ActiveRecord::Base.connection.create_table :delete_me do |t| + t.timestamps + end + ActiveRecord::Base.connection.remove_timestamps :delete_me + assert !column_present?('delete_me', 'updated_at', 'datetime') + assert !column_present?('delete_me', 'created_at', 'datetime') + ensure + ActiveRecord::Base.connection.drop_table :delete_me rescue nil + end end end - private + def with_real_execute + #we need to actually modify some data, so we make execute point to the original method + ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do + alias_method :execute_with_stub, :execute + alias_method :execute, :execute_without_stub + end + yield + ensure + #before finishing, we restore the alias to the mock-up method + ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do + alias_method :execute, :execute_with_stub + end + end + + def method_missing(method_symbol, *arguments) ActiveRecord::Base.connection.send(method_symbol, *arguments) end + + def column_present?(table_name, column_name, type) + results = ActiveRecord::Base.connection.select_all("SHOW FIELDS FROM #{table_name} LIKE '#{column_name}'") + results.first && results.first['Type'] == type + end end diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb index 91504af901..11f9870534 100644 --- a/activerecord/test/cases/adapter_test.rb +++ b/activerecord/test/cases/adapter_test.rb @@ -104,4 +104,24 @@ class AdapterTest < ActiveRecord::TestCase end end + def test_add_limit_offset_should_sanitize_sql_injection_for_limit_without_comas + sql_inject = "1 select * from schema" + assert_equal " LIMIT 1", @connection.add_limit_offset!("", :limit=>sql_inject) + if current_adapter?(:MysqlAdapter) + assert_equal " LIMIT 7, 1", @connection.add_limit_offset!("", :limit=>sql_inject, :offset=>7) + else + assert_equal " LIMIT 1 OFFSET 7", @connection.add_limit_offset!("", :limit=>sql_inject, :offset=>7) + end + end + + def test_add_limit_offset_should_sanitize_sql_injection_for_limit_with_comas + sql_inject = "1, 7 procedure help()" + if current_adapter?(:MysqlAdapter) + assert_equal " LIMIT 1,7", @connection.add_limit_offset!("", :limit=>sql_inject) + assert_equal " LIMIT 7, 1", @connection.add_limit_offset!("", :limit=> '1 ; DROP TABLE USERS', :offset=>7) + else + assert_equal " LIMIT 1,7", @connection.add_limit_offset!("", :limit=>sql_inject) + assert_equal " LIMIT 1,7 OFFSET 7", @connection.add_limit_offset!("", :limit=>sql_inject, :offset=>7) + end + end end diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index b8ec9117af..e0da8bfb7a 100644..100755 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -12,6 +12,8 @@ require 'models/author' require 'models/tag' require 'models/tagging' require 'models/comment' +require 'models/sponsor' +require 'models/member' class BelongsToAssociationsTest < ActiveRecord::TestCase fixtures :accounts, :companies, :developers, :projects, :topics, @@ -54,8 +56,8 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase original_proxy = citibank.firm citibank.firm = another_firm - assert_equal first_firm.object_id, original_proxy.object_id - assert_equal another_firm.object_id, citibank.firm.object_id + assert_equal first_firm.object_id, original_proxy.target.object_id + assert_equal another_firm.object_id, citibank.firm.target.object_id end def test_creating_the_belonging_object @@ -92,6 +94,11 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_not_nil Company.find(3).firm_with_condition, "Microsoft should have a firm" end + def test_with_select + assert_equal Company.find(2).firm_with_select.attributes.size, 1 + assert_equal Company.find(2, :include => :firm_with_select ).firm_with_select.attributes.size, 1 + end + def test_belongs_to_counter debate = Topic.create("title" => "debate") assert_equal 0, debate.send(:read_attribute, "replies_count"), "No replies yet" @@ -376,5 +383,30 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_raise(ActiveRecord::ReadOnlyRecord) { companies(:first_client).readonly_firm.save! } assert companies(:first_client).readonly_firm.readonly? end - + + def test_polymorphic_assignment_foreign_type_field_updating + # should update when assigning a saved record + sponsor = Sponsor.new + member = Member.create + sponsor.sponsorable = member + assert_equal "Member", sponsor.sponsorable_type + + # should update when assigning a new record + sponsor = Sponsor.new + member = Member.new + sponsor.sponsorable = member + assert_equal "Member", sponsor.sponsorable_type + end + + def test_polymorphic_assignment_updates_foreign_id_field_for_new_and_saved_records + sponsor = Sponsor.new + saved_member = Member.create + new_member = Member.new + + sponsor.sponsorable = saved_member + assert_equal saved_member.id, sponsor.sponsorable_id + + sponsor.sponsorable = new_member + assert_equal nil, sponsor.sponsorable_id + end end diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index 64565141f9..294b993c55 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -401,6 +401,8 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase def test_include_uses_array_include_after_loaded project = projects(:active_record) + project.developers.class # force load target + developer = project.developers.first assert_no_queries do diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 9e26e2ad58..dbfa025efb 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -32,6 +32,10 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal 2, Firm.find(:first).plain_clients.count end + def test_counting_with_empty_hash_conditions + assert_equal 2, Firm.find(:first).plain_clients.count(:conditions => {}) + end + def test_counting_with_single_conditions assert_equal 2, Firm.find(:first).plain_clients.count(:conditions => '1=1') end @@ -346,6 +350,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal "Another Client", new_client.name assert new_client.new_record? assert_equal new_client, company.clients_of_firm.last + company.name += '-changed' assert_queries(2) { assert company.save } assert !new_client.new_record? assert_equal 2, company.clients_of_firm(true).size @@ -356,6 +361,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase new_clients = assert_no_queries { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) } assert_equal 2, new_clients.size + company.name += '-changed' assert_queries(3) { assert company.save } assert_equal 3, company.clients_of_firm(true).size end @@ -818,6 +824,8 @@ class HasManyAssociationsTest < ActiveRecord::TestCase def test_include_uses_array_include_after_loaded firm = companies(:first_firm) + firm.clients.class # force load target + client = firm.clients.first assert_no_queries do @@ -857,4 +865,68 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert ! firm.clients.include?(client) end + def test_calling_first_or_last_on_association_should_not_load_association + firm = companies(:first_firm) + firm.clients.first + firm.clients.last + assert !firm.clients.loaded? + end + + def test_calling_first_or_last_on_loaded_association_should_not_fetch_with_query + firm = companies(:first_firm) + firm.clients.class # force load target + assert firm.clients.loaded? + + assert_no_queries do + firm.clients.first + assert_equal 2, firm.clients.first(2).size + firm.clients.last + assert_equal 2, firm.clients.last(2).size + end + end + + def test_calling_first_or_last_on_existing_record_with_build_should_load_association + firm = companies(:first_firm) + firm.clients.build(:name => 'Foo') + assert !firm.clients.loaded? + + assert_queries 1 do + firm.clients.first + firm.clients.last + end + + assert firm.clients.loaded? + end + + def test_calling_first_or_last_on_new_record_should_not_run_queries + firm = Firm.new + + assert_no_queries do + firm.clients.first + firm.clients.last + end + end + + def test_calling_first_or_last_with_find_options_on_loaded_association_should_fetch_with_query + firm = companies(:first_firm) + firm.clients.class # force load target + + assert_queries 2 do + assert firm.clients.loaded? + firm.clients.first(:order => 'name') + firm.clients.last(:order => 'name') + end + end + + def test_calling_first_or_last_with_integer_on_association_should_load_association + firm = companies(:first_firm) + + assert_queries 1 do + firm.clients.first(2) + firm.clients.last(2) + end + + assert firm.clients.loaded? + end + end diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 5561361bca..05155f6303 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -59,6 +59,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase # * 2 new records = 4 # + 1 query to save the actual post = 5 assert_queries(5) do + posts(:thinking).body += '-changed' posts(:thinking).save end diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index 9e99caa7b7..abc7ee7e9d 100644..100755 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -24,6 +24,11 @@ class HasOneAssociationsTest < ActiveRecord::TestCase assert_queries(0) { firms.each(&:account) } end + def test_with_select + assert_equal Firm.find(1).account_with_select.attributes.size, 2 + assert_equal Firm.find(1, :include => :account_with_select).account_with_select.attributes.size, 2 + end + def test_can_marshal_has_one_association_with_nil_target firm = Firm.new assert_nothing_raised do diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index 952ea63706..9e79d9c8a1 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -664,6 +664,8 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase def test_has_many_through_include_uses_array_include_after_loaded david = authors(:david) + david.categories.class # force load target + category = david.categories.first assert_no_queries do diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb index d8fe98bf57..59349dd7cf 100755 --- a/activerecord/test/cases/associations_test.rb +++ b/activerecord/test/cases/associations_test.rb @@ -99,12 +99,12 @@ class AssociationProxyTest < ActiveRecord::TestCase david = authors(:david) assert_equal david, david.posts.proxy_owner assert_equal david.class.reflect_on_association(:posts), david.posts.proxy_reflection - david.posts.first # force load target + david.posts.class # force load target assert_equal david.posts, david.posts.proxy_target assert_equal david, david.posts_with_extension.testing_proxy_owner assert_equal david.class.reflect_on_association(:posts_with_extension), david.posts_with_extension.testing_proxy_reflection - david.posts_with_extension.first # force load target + david.posts_with_extension.class # force load target assert_equal david.posts_with_extension, david.posts_with_extension.testing_proxy_target end @@ -160,6 +160,18 @@ class AssociationProxyTest < ActiveRecord::TestCase assert_equal 1, developer.reload.audit_logs.size end + def test_create_via_association_with_block + post = authors(:david).posts.create(:title => "New on Edge") {|p| p.body = "More cool stuff!"} + assert_equal post.title, "New on Edge" + assert_equal post.body, "More cool stuff!" + end + + def test_create_with_bang_via_association_with_block + post = authors(:david).posts.create!(:title => "New on Edge") {|p| p.body = "More cool stuff!"} + assert_equal post.title, "New on Edge" + assert_equal post.body, "More cool stuff!" + end + def test_failed_reload_returns_nil p = setup_dangling_association assert_nil p.author.reload diff --git a/activerecord/test/cases/datatype_test_postgresql.rb b/activerecord/test/cases/datatype_test_postgresql.rb index 41726ce518..bff092b5d7 100644 --- a/activerecord/test/cases/datatype_test_postgresql.rb +++ b/activerecord/test/cases/datatype_test_postgresql.rb @@ -30,8 +30,8 @@ class PostgresqlDataTypeTest < ActiveRecord::TestCase @connection.execute("INSERT INTO postgresql_arrays (commission_by_quarter, nicknames) VALUES ( '{35000,21000,18000,17000}', '{foo,bar,baz}' )") @first_array = PostgresqlArray.find(1) - @connection.execute("INSERT INTO postgresql_moneys (wealth) VALUES ('$567.89')") - @connection.execute("INSERT INTO postgresql_moneys (wealth) VALUES ('-$567.89')") + @connection.execute("INSERT INTO postgresql_moneys (wealth) VALUES ('567.89'::money)") + @connection.execute("INSERT INTO postgresql_moneys (wealth) VALUES ('-567.89'::money)") @first_money = PostgresqlMoney.find(1) @second_money = PostgresqlMoney.find(2) @@ -143,11 +143,11 @@ class PostgresqlDataTypeTest < ActiveRecord::TestCase end def test_update_money - new_value = 123.45 + new_value = BigDecimal.new('123.45') assert @first_money.wealth = new_value assert @first_money.save assert @first_money.reload - assert_equal @first_money.wealth, new_value + assert_equal new_value, @first_money.wealth end def test_update_number diff --git a/activerecord/test/cases/defaults_test.rb b/activerecord/test/cases/defaults_test.rb index bd19ffcc29..2ea85417da 100644 --- a/activerecord/test/cases/defaults_test.rb +++ b/activerecord/test/cases/defaults_test.rb @@ -5,7 +5,7 @@ require 'models/entrant' class DefaultTest < ActiveRecord::TestCase def test_nil_defaults_for_not_null_columns column_defaults = - if current_adapter?(:MysqlAdapter) + if current_adapter?(:MysqlAdapter) && Mysql.client_version < 50051 { 'id' => nil, 'name' => '', 'course_id' => nil } else { 'id' => nil, 'name' => nil, 'course_id' => nil } diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb index 1266eb5036..c011ffaf57 100644 --- a/activerecord/test/cases/dirty_test.rb +++ b/activerecord/test/cases/dirty_test.rb @@ -44,6 +44,16 @@ class DirtyTest < ActiveRecord::TestCase assert_nil pirate.catchphrase_change end + def test_nullable_integer_not_marked_as_changed_if_new_value_is_blank + pirate = Pirate.new + + ["", nil].each do |value| + pirate.parrot_id = value + assert !pirate.parrot_id_changed? + assert_nil pirate.parrot_id_change + end + end + def test_object_should_be_changed_if_any_attribute_is_changed pirate = Pirate.new assert !pirate.changed? @@ -127,6 +137,14 @@ class DirtyTest < ActiveRecord::TestCase check_pirate_after_save_failure(pirate) end + def test_reload_should_clear_changed_attributes + pirate = Pirate.create!(:catchphrase => "shiver me timbers") + pirate.catchphrase = "*hic*" + assert pirate.changed? + pirate.reload + assert !pirate.changed? + end + private def with_partial_updates(klass, on = true) old = klass.partial_updates? diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 5c0f0e2ef1..80936d51f3 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -867,7 +867,7 @@ class FinderTest < ActiveRecord::TestCase end def test_with_limiting_with_custom_select - posts = Post.find(:all, :include => :author, :select => ' posts.*, authors.id as "author_id"', :limit => 3) + posts = Post.find(:all, :include => :author, :select => ' posts.*, authors.id as "author_id"', :limit => 3, :order => 'posts.id') assert_equal 3, posts.size assert_equal [0, 1, 1], posts.map(&:author_id).sort end diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb index 27394924a1..f09b617e6d 100755 --- a/activerecord/test/cases/inheritance_test.rb +++ b/activerecord/test/cases/inheritance_test.rb @@ -5,7 +5,23 @@ require 'models/subscriber' class InheritanceTest < ActiveRecord::TestCase fixtures :companies, :projects, :subscribers, :accounts - + + def test_class_with_store_full_sti_class_returns_full_name + old = ActiveRecord::Base.store_full_sti_class + ActiveRecord::Base.store_full_sti_class = true + assert_equal 'Namespaced::Company', Namespaced::Company.sti_name + ensure + ActiveRecord::Base.store_full_sti_class = old + end + + def test_class_without_store_full_sti_class_returns_demodulized_name + old = ActiveRecord::Base.store_full_sti_class + ActiveRecord::Base.store_full_sti_class = false + assert_equal 'Company', Namespaced::Company.sti_name + ensure + ActiveRecord::Base.store_full_sti_class = old + end + def test_should_store_demodulized_class_name_with_store_full_sti_class_option_disabled old = ActiveRecord::Base.store_full_sti_class ActiveRecord::Base.store_full_sti_class = false diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb index 4b5bd6c951..1a9a875730 100644 --- a/activerecord/test/cases/method_scoping_test.rb +++ b/activerecord/test/cases/method_scoping_test.rb @@ -50,6 +50,22 @@ class MethodScopingTest < ActiveRecord::TestCase end end + def test_scoped_find_select + Developer.with_scope(:find => { :select => "id, name" }) do + developer = Developer.find(:first, :conditions => "name = 'David'") + assert_equal "David", developer.name + assert !developer.has_attribute?(:salary) + end + end + + def test_options_select_replaces_scope_select + Developer.with_scope(:find => { :select => "id, name" }) do + developer = Developer.find(:first, :select => 'id, salary', :conditions => "name = 'David'") + assert_equal 80000, developer.salary + assert !developer.has_attribute?(:name) + end + end + def test_scoped_count Developer.with_scope(:find => { :conditions => "name = 'David'" }) do assert_equal 1, Developer.count diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index 527856b4c0..f36255e209 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -281,7 +281,7 @@ if ActiveRecord::Base.connection.supports_migrations? # Do a manual insertion if current_adapter?(:OracleAdapter) Person.connection.execute "insert into people (id, wealth) values (people_seq.nextval, 12345678901234567890.0123456789)" - elsif current_adapter?(:OpenBaseAdapter) + elsif current_adapter?(:OpenBaseAdapter) || (current_adapter?(:MysqlAdapter) && Mysql.client_version < 50003) #before mysql 5.0.3 decimals stored as strings Person.connection.execute "insert into people (wealth) values ('12345678901234567890.0123456789')" else Person.connection.execute "insert into people (wealth) values (12345678901234567890.0123456789)" @@ -384,7 +384,7 @@ if ActiveRecord::Base.connection.supports_migrations? assert_not_equal "Z", bob.moment_of_truth.zone # US/Eastern is -5 hours from GMT assert_equal Rational(-5, 24), bob.moment_of_truth.offset - assert_equal "-05:00", bob.moment_of_truth.zone + assert_match /\A-05:?00\Z/, bob.moment_of_truth.zone #ruby 1.8.6 uses HH:MM, prior versions use HHMM assert_equal DateTime::ITALY, bob.moment_of_truth.start end end diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb index 30c074c9d8..d890cf7936 100644 --- a/activerecord/test/cases/named_scope_test.rb +++ b/activerecord/test/cases/named_scope_test.rb @@ -6,7 +6,7 @@ require 'models/reply' require 'models/author' class NamedScopeTest < ActiveRecord::TestCase - fixtures :posts, :authors, :topics + fixtures :posts, :authors, :topics, :comments def test_implements_enumerable assert !Topic.find(:all).empty? @@ -95,7 +95,7 @@ class NamedScopeTest < ActiveRecord::TestCase end def test_has_many_through_associations_have_access_to_named_scopes - assert_not_equal Comment.containing_the_letter_e, authors(:david).posts + assert_not_equal Comment.containing_the_letter_e, authors(:david).comments assert !Comment.containing_the_letter_e.empty? assert_equal authors(:david).comments & Comment.containing_the_letter_e, authors(:david).comments.containing_the_letter_e @@ -118,4 +118,40 @@ class NamedScopeTest < ActiveRecord::TestCase assert_equal expected_proxy_options, Topic.approved.proxy_options end + def test_first_and_last_should_support_find_options + assert_equal Topic.base.first(:order => 'title'), Topic.base.find(:first, :order => 'title') + assert_equal Topic.base.last(:order => 'title'), Topic.base.find(:last, :order => 'title') + end + + def test_first_and_last_should_allow_integers_for_limit + assert_equal Topic.base.first(2), Topic.base.to_a.first(2) + assert_equal Topic.base.last(2), Topic.base.to_a.last(2) + end + + def test_first_and_last_should_not_use_query_when_results_are_loaded + topics = Topic.base + topics.reload # force load + assert_no_queries do + topics.first + topics.last + end + end + + def test_first_and_last_find_options_should_use_query_when_results_are_loaded + topics = Topic.base + topics.reload # force load + assert_queries(2) do + topics.first(:order => 'title') + topics.last(:order => 'title') + end + end + + def test_empty_should_not_load_results + topics = Topic.base + assert_queries(2) do + topics.empty? # use count query + topics.collect # force load + topics.empty? # use loaded (no query) + end + end end diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index c8ee40ea09..8b4d232554 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -159,9 +159,10 @@ class ReflectionTest < ActiveRecord::TestCase end def test_reflection_of_all_associations - assert_equal 19, Firm.reflect_on_all_associations.size + # FIXME these assertions bust a lot + assert_equal 20, Firm.reflect_on_all_associations.size assert_equal 16, Firm.reflect_on_all_associations(:has_many).size - assert_equal 3, Firm.reflect_on_all_associations(:has_one).size + assert_equal 4, Firm.reflect_on_all_associations(:has_one).size assert_equal 0, Firm.reflect_on_all_associations(:belongs_to).size end diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index 63f04e3014..06a76eacc3 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -179,6 +179,32 @@ class TransactionTest < ActiveRecord::TestCase end end + def test_sqlite_add_column_in_transaction_raises_statement_invalid + return true unless current_adapter?(:SQLite3Adapter, :SQLiteAdapter) + + # Test first if column creation/deletion works correctly when no + # transaction is in place. + # + # We go back to the connection for the column queries because + # Topic.columns is cached and won't report changes to the DB + + assert_nothing_raised do + Topic.reset_column_information + Topic.connection.add_column('topics', 'stuff', :string) + assert Topic.column_names.include?('stuff') + + Topic.reset_column_information + Topic.connection.remove_column('topics', 'stuff') + assert !Topic.column_names.include?('stuff') + end + + # Test now inside a transaction: add_column should raise a StatementInvalid + Topic.transaction do + assert_raises(ActiveRecord::StatementInvalid) { Topic.connection.add_column('topics', 'stuff', :string) } + raise ActiveRecord::Rollback + end + end + private def add_exception_raising_after_save_callback_to_topic Topic.class_eval { def after_save() raise "Make the transaction rollback" end } diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb index a4d9da4806..7b71647d25 100755 --- a/activerecord/test/cases/validations_test.rb +++ b/activerecord/test/cases/validations_test.rb @@ -583,6 +583,12 @@ class ValidationsTest < ActiveRecord::TestCase assert_nil t.errors.on(:title) end + def test_validate_format_with_formatted_message + Topic.validates_format_of(:title, :with => /^Valid Title$/, :message => "can't be %s") + t = Topic.create(:title => 'Invalid title') + assert_equal "can't be Invalid title", t.errors.on(:title) + end + def test_validates_inclusion_of Topic.validates_inclusion_of( :title, :in => %w( a b c d e f g ) ) diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb index f637490c59..70f83fa8e6 100755 --- a/activerecord/test/models/company.rb +++ b/activerecord/test/models/company.rb @@ -47,6 +47,7 @@ class Firm < Company has_many :readonly_clients, :class_name => 'Client', :readonly => true has_one :account, :foreign_key => "firm_id", :dependent => :destroy + has_one :account_with_select, :foreign_key => "firm_id", :select => "id, firm_id", :class_name=>'Account' has_one :readonly_account, :foreign_key => "firm_id", :class_name => "Account", :readonly => true end @@ -64,6 +65,7 @@ end class Client < Company belongs_to :firm, :foreign_key => "client_of" belongs_to :firm_with_basic_id, :class_name => "Firm", :foreign_key => "firm_id" + belongs_to :firm_with_select, :class_name => "Firm", :foreign_key => "firm_id", :select => "id" belongs_to :firm_with_other_name, :class_name => "Firm", :foreign_key => "client_of" belongs_to :firm_with_condition, :class_name => "Firm", :foreign_key => "client_of", :conditions => ["1 = ?", 1] belongs_to :readonly_firm, :class_name => "Firm", :foreign_key => "firm_id", :readonly => true diff --git a/activeresource/CHANGELOG b/activeresource/CHANGELOG index 9aa7d455a2..e124e40dd1 100644 --- a/activeresource/CHANGELOG +++ b/activeresource/CHANGELOG @@ -1,4 +1,4 @@ -*2.1.0 RC1 (May 11th, 2008)* +*2.1.0 (May 31st, 2008)* * Fixed response logging to use length instead of the entire thing (seangeo) [#27] diff --git a/activeresource/Rakefile b/activeresource/Rakefile index 75fe52aea8..9fd0ec4921 100644 --- a/activeresource/Rakefile +++ b/activeresource/Rakefile @@ -64,7 +64,7 @@ spec = Gem::Specification.new do |s| s.files = s.files + Dir.glob( "#{dir}/**/*" ).delete_if { |item| item.include?( "\.svn" ) } end - s.add_dependency('activesupport', '= 2.0.991' + PKG_BUILD) + s.add_dependency('activesupport', '= 2.1.0' + PKG_BUILD) s.require_path = 'lib' s.autorequire = 'active_resource' diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index 08fd0123f6..59e0888c2b 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -34,18 +34,18 @@ module ActiveResource # from REST web services. # # ryan = Person.new(:first => 'Ryan', :last => 'Daigle') - # ryan.save #=> true - # ryan.id #=> 2 - # Person.exists?(ryan.id) #=> true - # ryan.exists? #=> true + # ryan.save # => true + # ryan.id # => 2 + # Person.exists?(ryan.id) # => true + # ryan.exists? # => true # # ryan = Person.find(1) - # # => Resource holding our newly created Person object + # # Resource holding our newly created Person object # # ryan.first = 'Rizzle' - # ryan.save #=> true + # ryan.save # => true # - # ryan.destroy #=> true + # ryan.destroy # => true # # As you can see, these are very similar to Active Record's lifecycle methods for database records. # You can read more about each of these methods in their respective documentation. @@ -111,7 +111,7 @@ module ActiveResource # over HTTPS. # # Note: Some values cannot be provided in the URL passed to site. e.g. email addresses - # as usernames. In those situations you should use the seperate user and password option. + # as usernames. In those situations you should use the separate user and password option. # == Errors & Validation # # Error handling and validation is handled in much the same manner as you're used to seeing in @@ -127,7 +127,7 @@ module ActiveResource # # GET http://api.people.com:3000/people/999.xml # ryan = Person.find(999) # 404, raises ActiveResource::ResourceNotFound # - # <tt>404</tt> is just one of the HTTP error response codes that ActiveResource will handle with its own exception. The + # <tt>404</tt> is just one of the HTTP error response codes that Active Resource will handle with its own exception. The # following HTTP response codes will also result in these exceptions: # # * 200..399 - Valid response, no exception @@ -156,8 +156,8 @@ module ActiveResource # then fail (with a <tt>false</tt> return value) and the validation errors can be accessed on the resource in question. # # ryan = Person.find(1) - # ryan.first #=> '' - # ryan.save #=> false + # ryan.first # => '' + # ryan.save # => false # # # When # # PUT http://api.people.com:3000/people/1.xml @@ -167,8 +167,8 @@ module ActiveResource # # <errors type="array"><error>First cannot be empty</error></errors> # # # - # ryan.errors.invalid?(:first) #=> true - # ryan.errors.full_messages #=> ['First cannot be empty'] + # ryan.errors.invalid?(:first) # => true + # ryan.errors.full_messages # => ['First cannot be empty'] # # Learn more about Active Resource's validation features in the ActiveResource::Validations documentation. # @@ -200,8 +200,8 @@ module ActiveResource cattr_accessor :logger class << self - # Gets the URI of the REST resources to map for this class. The site variable is required - # ActiveResource's mapping to work. + # Gets the URI of the REST resources to map for this class. The site variable is required for + # Active Resource's mapping to work. def site # Not using superclass_delegating_reader because don't want subclasses to modify superclass instance # @@ -226,7 +226,7 @@ module ActiveResource end # Sets the URI of the REST resources to map for this class to the value in the +site+ argument. - # The site variable is required ActiveResource's mapping to work. + # The site variable is required for Active Resource's mapping to work. def site=(site) @connection = nil if site.nil? @@ -288,7 +288,7 @@ module ActiveResource end # Returns the current format, default is ActiveResource::Formats::XmlFormat. - def format # :nodoc: + def format read_inheritable_attribute("format") || ActiveResource::Formats[:xml] end @@ -298,7 +298,7 @@ module ActiveResource @timeout = timeout end - # Gets tthe number of seconds after which requests to the REST API should time out. + # Gets the number of seconds after which requests to the REST API should time out. def timeout if defined?(@timeout) @timeout @@ -426,16 +426,16 @@ module ActiveResource alias_method :set_primary_key, :primary_key= #:nodoc: - # Create a new resource instance and request to the remote service + # Creates a new resource instance and makes a request to the remote service # that it be saved, making it equivalent to the following simultaneous calls: # # ryan = Person.new(:first => 'ryan') # ryan.save # - # The newly created resource is returned. If a failure has occurred an - # exception will be raised (see save). If the resource is invalid and - # has not been saved then valid? will return <tt>false</tt>, - # while new? will still return <tt>true</tt>. + # Returns the newly created resource. If a failure has occurred an + # exception will be raised (see <tt>save</tt>). If the resource is invalid and + # has not been saved then <tt>valid?</tt> will return <tt>false</tt>, + # while <tt>new?</tt> will still return <tt>true</tt>. # # ==== Examples # Person.create(:name => 'Jeremy', :email => 'myname@nospam.com', :enabled => true) @@ -701,7 +701,7 @@ module ActiveResource attributes[self.class.primary_key] = id end - # Allows ActiveResource objects to be used as parameters in ActionPack URL generation. + # Allows Active Resource objects to be used as parameters in Action Pack URL generation. def to_param id && id.to_s end @@ -812,7 +812,7 @@ module ActiveResource # Person.delete(guys_id) # that_guy.exists? # => false def exists? - !new? && self.class.exists?(to_param, :params => prefix_options) + !new? && self.class.exists?(to_param, :params => prefix_options) end # A method to convert the the resource to an XML string. @@ -820,7 +820,7 @@ module ActiveResource # ==== Options # The +options+ parameter is handed off to the +to_xml+ method on each # attribute, so it has the same options as the +to_xml+ methods in - # ActiveSupport. + # Active Support. # # * <tt>:indent</tt> - Set the indent level for the XML output (default is +2+). # * <tt>:dasherize</tt> - Boolean option to determine whether or not element names should diff --git a/activeresource/lib/active_resource/custom_methods.rb b/activeresource/lib/active_resource/custom_methods.rb index 52a4a4f10b..770116ceb7 100644 --- a/activeresource/lib/active_resource/custom_methods.rb +++ b/activeresource/lib/active_resource/custom_methods.rb @@ -7,12 +7,12 @@ module ActiveResource # :member => { :promote => :put, :deactivate => :delete } # :collection => { :active => :get } # - # This route set creates routes for the following http requests: + # This route set creates routes for the following HTTP requests: # - # POST /people/new/register.xml #=> PeopleController.register - # PUT /people/1/promote.xml #=> PeopleController.promote with :id => 1 - # DELETE /people/1/deactivate.xml #=> PeopleController.deactivate with :id => 1 - # GET /people/active.xml #=> PeopleController.active + # POST /people/new/register.xml # PeopleController.register + # PUT /people/1/promote.xml # PeopleController.promote with :id => 1 + # DELETE /people/1/deactivate.xml # PeopleController.deactivate with :id => 1 + # GET /people/active.xml # PeopleController.active # # Using this module, Active Resource can use these custom REST methods just like the # standard methods. @@ -48,8 +48,8 @@ module ActiveResource # # => [{:id => 1, :name => 'Ryan'}] # # Note: the objects returned from this method are not automatically converted - # into ActiveResource instances - they are ordinary Hashes. If you are expecting - # ActiveResource instances, use the <tt>find</tt> class method with the + # into ActiveResource::Base instances - they are ordinary Hashes. If you are expecting + # ActiveResource::Base instances, use the <tt>find</tt> class method with the # <tt>:from</tt> option. For example: # # Person.find(:all, :from => :active) diff --git a/activeresource/lib/active_resource/formats/xml_format.rb b/activeresource/lib/active_resource/formats/xml_format.rb index 01c28dcee6..5e97ffa776 100644 --- a/activeresource/lib/active_resource/formats/xml_format.rb +++ b/activeresource/lib/active_resource/formats/xml_format.rb @@ -21,7 +21,7 @@ module ActiveResource private # Manipulate from_xml Hash, because xml_simple is not exactly what we - # want for ActiveResource. + # want for Active Resource. def from_xml_data(data) if data.is_a?(Hash) && data.keys.size == 1 data.values.first diff --git a/activeresource/lib/active_resource/http_mock.rb b/activeresource/lib/active_resource/http_mock.rb index d1c1412575..554fc3bcfc 100644 --- a/activeresource/lib/active_resource/http_mock.rb +++ b/activeresource/lib/active_resource/http_mock.rb @@ -3,8 +3,52 @@ require 'active_resource/connection' module ActiveResource class InvalidRequestError < StandardError; end #:nodoc: + # One thing that has always been a pain with remote web services is testing. The HttpMock + # class makes it easy to test your Active Resource models by creating a set of mock responses to specific + # requests. + # + # To test your Active Resource model, you simply call the ActiveResource::HttpMock.respond_to + # method with an attached block. The block declares a set of URIs with expected input, and the output + # each request should return. The passed in block has any number of entries in the following generalized + # format: + # + # mock.http_method(path, request_headers = {}, body = nil, status = 200, response_headers = {}) + # + # * <tt>http_method</tt> - The HTTP method to listen for. This can be +get+, +post+, +put+, +delete+ or + # +head+. + # * <tt>path</tt> - A string, starting with a "/", defining the URI that is expected to be + # called. + # * <tt>request_headers</tt> - Headers that are expected along with the request. This argument uses a + # hash format, such as <tt>{ "Content-Type" => "application/xml" }</tt>. This mock will only trigger + # if your tests sends a request with identical headers. + # * <tt>body</tt> - The data to be returned. This should be a string of Active Resource parseable content, + # such as XML. + # * <tt>status</tt> - The HTTP response code, as an integer, to return with the response. + # * <tt>response_headers</tt> - Headers to be returned with the response. Uses the same hash format as + # <tt>request_headers</tt> listed above. + # + # In order for a mock to deliver its content, the incoming request must match by the <tt>http_method</tt>, + # +path+ and <tt>request_headers</tt>. If no match is found an InvalidRequestError exception + # will be raised letting you know you need to create a new mock for that request. + # + # ==== Example + # def setup + # @matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person") + # ActiveResource::HttpMock.respond_to do |mock| + # mock.post "/people.xml", {}, @matz, 201, "Location" => "/people/1.xml" + # mock.get "/people/1.xml", {}, @matz + # mock.put "/people/1.xml", {}, nil, 204 + # mock.delete "/people/1.xml", {}, nil, 200 + # end + # end + # + # def test_get_matz + # person = Person.find(1) + # assert_equal "Matz", person.name + # end + # class HttpMock - class Responder + class Responder #:nodoc: def initialize(responses) @responses = responses end @@ -19,15 +63,41 @@ module ActiveResource end class << self + + # Returns an array of all request objects that have been sent to the mock. You can use this to check + # if your model actually sent an HTTP request. + # + # ==== Example + # def setup + # @matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person") + # ActiveResource::HttpMock.respond_to do |mock| + # mock.get "/people/1.xml", {}, @matz + # end + # end + # + # def test_should_request_remote_service + # person = Person.find(1) # Call the remote service + # + # # This request object has the same HTTP method and path as declared by the mock + # expected_request = ActiveResource::Request.new(:get, "/people/1.xml") + # + # # Assert that the mock received, and responded to, the expected request from the model + # assert ActiveResource::HttpMock.requests.include?(expected_request) + # end def requests @@requests ||= [] end + # Returns a hash of <tt>request => response</tt> pairs for all all responses this mock has delivered, where +request+ + # is an instance of ActiveResource::Request and the response is, naturally, an instance of + # ActiveResource::Response. def responses @@responses ||= {} end - def respond_to(pairs = {}) + # Accepts a block which declares a set of requests and responses for the HttpMock to respond to. See the main + # ActiveResource::HttpMock description for a more detailed explanation. + def respond_to(pairs = {}) #:yields: mock reset! pairs.each do |(path, response)| responses[path] = response @@ -40,6 +110,7 @@ module ActiveResource end end + # Deletes all logged requests and responses. def reset! requests.clear responses.clear @@ -66,7 +137,7 @@ module ActiveResource EOE end - def initialize(site) + def initialize(site) #:nodoc: @site = site end end diff --git a/activeresource/lib/active_resource/validations.rb b/activeresource/lib/active_resource/validations.rb index 57d2ae559d..a7c624f309 100644 --- a/activeresource/lib/active_resource/validations.rb +++ b/activeresource/lib/active_resource/validations.rb @@ -216,8 +216,8 @@ module ActiveResource end end - # Module to allow validation of ActiveResource objects, which creates an Errors instance for every resource. - # Methods are implemented by overriding +Base#validate+ or its variants Each of these methods can inspect + # Module to allow validation of Active Resource objects, which creates an Errors instance for every resource. + # Methods are implemented by overriding Base#validate or its variants Each of these methods can inspect # the state of the object, which usually means ensuring that a number of attributes have a certain value # (such as not empty, within a given range, matching a certain regular expression and so on). # diff --git a/activeresource/lib/active_resource/version.rb b/activeresource/lib/active_resource/version.rb index 34fb05b703..88798ea1c1 100644 --- a/activeresource/lib/active_resource/version.rb +++ b/activeresource/lib/active_resource/version.rb @@ -1,8 +1,8 @@ module ActiveResource module VERSION #:nodoc: MAJOR = 2 - MINOR = 0 - TINY = 991 + MINOR = 1 + TINY = 0 STRING = [MAJOR, MINOR, TINY].join('.') end diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index e8821060f9..690bb987dc 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,4 +1,12 @@ -*2.1.0 RC1 (May 11th, 2008)* +*2.1.0 (May 31st, 2008)* + +* TimeZone#to_s shows offset as GMT instead of UTC, because GMT will be more familiar to end users (see time zone selects used by Windows OS, google.com and yahoo.com.) Reverts [8370] [Geoff Buesing] + +* Hash.from_xml: datetime xml types overflow to Ruby DateTime class when out of range of Time. Adding tests for utc offsets [Geoff Buesing] + +* TimeWithZone #+ and #- : ensure overflow to DateTime with Numeric arg [Geoff Buesing] + +* Time#to_json: don't convert to utc before encoding. References #175 [Geoff Buesing] * Remove unused JSON::RESERVED_WORDS, JSON.valid_identifier? and JSON.reserved_word? methods. Resolves #164. [Cheah Chu Yeow] diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb index b3c9c23d9f..2f1143e610 100644 --- a/activesupport/lib/active_support/cache.rb +++ b/activesupport/lib/active_support/cache.rb @@ -87,8 +87,12 @@ module ActiveSupport def delete_matched(matcher, options = nil) log("delete matched", matcher.inspect, options) - end - + end + + def exist?(key, options = nil) + log("exist?", key, options) + end + def increment(key, amount = 1) log("incrementing", key, amount) if num = read(key) diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb index 16a2509ce2..5b771b1da0 100644 --- a/activesupport/lib/active_support/cache/file_store.rb +++ b/activesupport/lib/active_support/cache/file_store.rb @@ -40,13 +40,18 @@ module ActiveSupport end end + def exist?(name, options = nil) + super + File.exist?(real_file_path(name)) + end + private def real_file_path(name) '%s/%s.cache' % [@cache_path, name.gsub('?', '.').gsub(':', '.')] end def ensure_cache_path(path) - FileUtils.makedirs(path) unless File.exists?(path) + FileUtils.makedirs(path) unless File.exist?(path) end def search_dir(dir, &callback) diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb index bfe7e2ccf3..b3769b812f 100644 --- a/activesupport/lib/active_support/cache/mem_cache_store.rb +++ b/activesupport/lib/active_support/cache/mem_cache_store.rb @@ -48,7 +48,13 @@ module ActiveSupport rescue MemCache::MemCacheError => e logger.error("MemCacheError (#{e}): #{e.message}") false - end + end + + def exist?(key, options = nil) + # Doesn't call super, cause exist? in memcache is in fact a read + # But who cares? Reading is very fast anyway + !read(key, options).nil? + end def increment(key, amount = 1) log("incrementing", key, amount) diff --git a/activesupport/lib/active_support/cache/memory_store.rb b/activesupport/lib/active_support/cache/memory_store.rb index 4872e025cd..6f114273e4 100644 --- a/activesupport/lib/active_support/cache/memory_store.rb +++ b/activesupport/lib/active_support/cache/memory_store.rb @@ -24,7 +24,12 @@ module ActiveSupport super @data.delete_if { |k,v| k =~ matcher } end - + + def exist?(name,options = nil) + super + @data.has_key?(name) + end + def clear @data.clear end diff --git a/activesupport/lib/active_support/core_ext/bigdecimal/conversions.rb b/activesupport/lib/active_support/core_ext/bigdecimal/conversions.rb index d2b01b1b8d..94c7c779f7 100644 --- a/activesupport/lib/active_support/core_ext/bigdecimal/conversions.rb +++ b/activesupport/lib/active_support/core_ext/bigdecimal/conversions.rb @@ -21,7 +21,7 @@ module ActiveSupport #:nodoc: # This emits the number without any scientific notation. # I prefer it to using self.to_f.to_s, which would lose precision. # - # Note that YAML allows that when reconsituting floats + # Note that YAML allows that when reconstituting floats # to native types, some precision may get lost. # There is no full precision real YAML tag that I am aware of. str = self.to_s diff --git a/activesupport/lib/active_support/core_ext/hash/conversions.rb b/activesupport/lib/active_support/core_ext/hash/conversions.rb index 3d6a8d8588..2c606b401b 100644 --- a/activesupport/lib/active_support/core_ext/hash/conversions.rb +++ b/activesupport/lib/active_support/core_ext/hash/conversions.rb @@ -70,7 +70,7 @@ module ActiveSupport #:nodoc: XML_PARSING = { "symbol" => Proc.new { |symbol| symbol.to_sym }, "date" => Proc.new { |date| ::Date.parse(date) }, - "datetime" => Proc.new { |time| ::Time.parse(time).utc }, + "datetime" => Proc.new { |time| ::Time.parse(time).utc rescue ::DateTime.parse(time).utc }, "integer" => Proc.new { |integer| integer.to_i }, "float" => Proc.new { |float| float.to_f }, "decimal" => Proc.new { |number| BigDecimal(number) }, @@ -212,7 +212,7 @@ module ActiveSupport #:nodoc: nil # If the type is the only element which makes it then # this still makes the value nil, except if type is - # a xml node(where type['value'] is a Hash) + # a XML node(where type['value'] is a Hash) elsif value['type'] && value.size == 1 && !value['type'].is_a?(::Hash) nil else diff --git a/activesupport/lib/active_support/core_ext/hash/except.rb b/activesupport/lib/active_support/core_ext/hash/except.rb index 8362cd880e..64d690965a 100644 --- a/activesupport/lib/active_support/core_ext/hash/except.rb +++ b/activesupport/lib/active_support/core_ext/hash/except.rb @@ -14,7 +14,7 @@ module ActiveSupport #:nodoc: reject { |key,| rejected.include?(key) } end - # Replaces the hash without only the given keys. + # Replaces the hash without the given keys. def except!(*keys) replace(except(*keys)) end diff --git a/activesupport/lib/active_support/core_ext/integer/even_odd.rb b/activesupport/lib/active_support/core_ext/integer/even_odd.rb index cfc6b4c6d6..b1d1e28062 100644 --- a/activesupport/lib/active_support/core_ext/integer/even_odd.rb +++ b/activesupport/lib/active_support/core_ext/integer/even_odd.rb @@ -3,10 +3,14 @@ module ActiveSupport #:nodoc: module Integer #:nodoc: # For checking if a fixnum is even or odd. # - # 1.even? # => false - # 1.odd? # => true - # 2.even? # => true - # 2.odd? # => false + # 2.even? # => true + # 2.odd? # => false + # 1.even? # => false + # 1.odd? # => true + # 0.even? # => true + # 0.odd? # => false + # -1.even? # => false + # -1.odd? # => true module EvenOdd def multiple_of?(number) self % number == 0 diff --git a/activesupport/lib/active_support/core_ext/object/misc.rb b/activesupport/lib/active_support/core_ext/object/misc.rb index a3637d7a8a..8384a12327 100644 --- a/activesupport/lib/active_support/core_ext/object/misc.rb +++ b/activesupport/lib/active_support/core_ext/object/misc.rb @@ -48,7 +48,7 @@ class Object yield ActiveSupport::OptionMerger.new(self, options) end - # A duck-type assistant method. For example, ActiveSupport extends Date + # A duck-type assistant method. For example, Active Support extends Date # to define an acts_like_date? method, and extends Time to define # acts_like_time?. As a result, we can do "x.acts_like?(:time)" and # "x.acts_like?(:date)" to do duck-type-safe comparisons, since classes that diff --git a/activesupport/lib/active_support/core_ext/string/inflections.rb b/activesupport/lib/active_support/core_ext/string/inflections.rb index a009d7c085..3bbad7dad8 100644 --- a/activesupport/lib/active_support/core_ext/string/inflections.rb +++ b/activesupport/lib/active_support/core_ext/string/inflections.rb @@ -24,8 +24,8 @@ module ActiveSupport #:nodoc: # # "posts".singularize # => "post" # "octopi".singularize # => "octopus" - # "sheep".singluarize # => "sheep" - # "word".singluarize # => "word" + # "sheep".singularize # => "sheep" + # "word".singularize # => "word" # "the blue mailmen".singularize # => "the blue mailman" # "CamelOctopi".singularize # => "CamelOctopus" def singularize diff --git a/activesupport/lib/active_support/core_ext/string/unicode.rb b/activesupport/lib/active_support/core_ext/string/unicode.rb index ba16d4d866..5e20534d1d 100644 --- a/activesupport/lib/active_support/core_ext/string/unicode.rb +++ b/activesupport/lib/active_support/core_ext/string/unicode.rb @@ -17,17 +17,17 @@ module ActiveSupport #:nodoc: # string overrides can also be called through the +chars+ proxy. # # name = 'Claus Müller' - # name.reverse #=> "rell??M sualC" - # name.length #=> 13 + # name.reverse # => "rell??M sualC" + # name.length # => 13 # - # name.chars.reverse.to_s #=> "rellüM sualC" - # name.chars.length #=> 12 + # name.chars.reverse.to_s # => "rellüM sualC" + # name.chars.length # => 12 # # # All the methods on the chars proxy which normally return a string will return a Chars object. This allows # method chaining on the result of any of these methods. # - # name.chars.reverse.length #=> 12 + # name.chars.reverse.length # => 12 # # The Char object tries to be as interchangeable with String objects as possible: sorting and comparing between # String and Char work like expected. The bang! methods change the internal string representation in the Chars diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb index 2cce782676..cd234c9b89 100644 --- a/activesupport/lib/active_support/core_ext/time/calculations.rb +++ b/activesupport/lib/active_support/core_ext/time/calculations.rb @@ -261,7 +261,7 @@ module ActiveSupport #:nodoc: # Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances # can be chronologically compared with a Time def compare_with_coercion(other) - # if other is an ActiveSupport::TimeWithZone, coerce a Time instance from it so we can do <=> comparision + # if other is an ActiveSupport::TimeWithZone, coerce a Time instance from it so we can do <=> comparison other = other.comparable_time if other.respond_to?(:comparable_time) if other.acts_like?(:date) # other is a Date/DateTime, so coerce self #to_datetime and hand off to DateTime#<=> diff --git a/activesupport/lib/active_support/core_ext/time/conversions.rb b/activesupport/lib/active_support/core_ext/time/conversions.rb index edca5b8a98..9054008309 100644 --- a/activesupport/lib/active_support/core_ext/time/conversions.rb +++ b/activesupport/lib/active_support/core_ext/time/conversions.rb @@ -59,7 +59,7 @@ module ActiveSupport #:nodoc: # Converts a Time object to a Date, dropping hour, minute, and second precision. # # my_time = Time.now # => Mon Nov 12 22:59:51 -0500 2007 - # my_time.to_date #=> Mon, 12 Nov 2007 + # my_time.to_date # => Mon, 12 Nov 2007 # # your_time = Time.parse("1/13/2009 1:13:03 P.M.") # => Tue Jan 13 13:13:03 -0500 2009 # your_time.to_date # => Tue, 13 Jan 2009 diff --git a/activesupport/lib/active_support/core_ext/time/zones.rb b/activesupport/lib/active_support/core_ext/time/zones.rb index 3ffc71407c..079ecdd48e 100644 --- a/activesupport/lib/active_support/core_ext/time/zones.rb +++ b/activesupport/lib/active_support/core_ext/time/zones.rb @@ -1,9 +1,7 @@ module ActiveSupport #:nodoc: module CoreExtensions #:nodoc: module Time #:nodoc: - # Methods for creating TimeWithZone objects from Time instances module Zones - def self.included(base) #:nodoc: base.extend(ClassMethods) if base == ::Time # i.e., don't include class methods in DateTime end @@ -11,23 +9,36 @@ module ActiveSupport #:nodoc: module ClassMethods attr_accessor :zone_default + # Returns the TimeZone for the current request, if this has been set (via Time.zone=). + # If <tt>Time.zone</tt> has not been set for the current request, returns the TimeZone specified in <tt>config.time_zone</tt>. def zone Thread.current[:time_zone] || zone_default end - # Sets a global default time zone, separate from the system time zone in ENV['TZ']. - # Accepts either a Rails TimeZone object, a string that identifies a - # Rails TimeZone object (e.g., "Central Time (US & Canada)"), or a TZInfo::Timezone object. + # Sets <tt>Time.zone</tt> to a TimeZone object for the current request/thread. + # + # This method accepts any of the following: + # + # * A Rails TimeZone object. + # * An identifier for a Rails TimeZone object (e.g., "Eastern Time (US & Canada)", <tt>-5.hours</tt>). + # * A TZInfo::Timezone object. + # * An identifier for a TZInfo::Timezone object (e.g., "America/New_York"). + # + # Here's an example of how you might set <tt>Time.zone</tt> on a per request basis -- <tt>current_user.time_zone</tt> + # just needs to return a string identifying the user's preferred TimeZone: # - # Any Time or DateTime object can use this default time zone, via <tt>in_time_zone</tt>. + # class ApplicationController < ActionController::Base + # before_filter :set_time_zone # - # Time.zone = 'Hawaii' # => 'Hawaii' - # Time.utc(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00 + # def set_time_zone + # Time.zone = current_user.time_zone + # end + # end def zone=(time_zone) Thread.current[:time_zone] = get_zone(time_zone) end - # Allows override of Time.zone locally inside supplied block; resets Time.zone to existing value when done + # Allows override of <tt>Time.zone</tt> locally inside supplied block; resets <tt>Time.zone</tt> to existing value when done. def use_zone(time_zone) old_zone, ::Time.zone = ::Time.zone, get_zone(time_zone) yield @@ -35,7 +46,7 @@ module ActiveSupport #:nodoc: ::Time.zone = old_zone end - # Returns Time.zone.now when config.time_zone is set, otherwise just returns Time.now. + # Returns <tt>Time.zone.now</tt> when <tt>config.time_zone</tt> is set, otherwise just returns <tt>Time.now</tt>. def current ::Time.zone_default ? ::Time.zone.now : ::Time.now end @@ -54,16 +65,16 @@ module ActiveSupport #:nodoc: end end - # Returns the simultaneous time in Time.zone. + # Returns the simultaneous time in <tt>Time.zone</tt>. # # Time.zone = 'Hawaii' # => 'Hawaii' # Time.utc(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00 # - # This method is similar to Time#localtime, except that it uses Time.zone as the local zone + # This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt> as the local zone # instead of the operating system's time zone. # # You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument, - # and the conversion will be based on that zone instead of Time.zone. + # and the conversion will be based on that zone instead of <tt>Time.zone</tt>. # # Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00 def in_time_zone(zone = ::Time.zone) diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index eaba46dd9c..8f3aa4f848 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -82,9 +82,10 @@ module Dependencies #:nodoc: # infinite loop with mutual dependencies. loaded << expanded - if load? - log "loading #{file_name}" - begin + begin + if load? + log "loading #{file_name}" + # Enable warnings iff this file has not been loaded before and # warnings_on_first_load is set. load_args = ["#{file_name}.rb"] @@ -95,13 +96,13 @@ module Dependencies #:nodoc: else enable_warnings { result = load_file(*load_args) } end - rescue Exception - loaded.delete expanded - raise + else + log "requiring #{file_name}" + result = require file_name end - else - log "requiring #{file_name}" - result = require file_name + rescue Exception + loaded.delete expanded + raise end # Record history *after* loading so first load gets warnings. @@ -128,7 +129,7 @@ module Dependencies #:nodoc: if Module.method(:const_defined?).arity == 1 # Does this module define this constant? - # Wrapper to accomodate changing Module#const_defined? in Ruby 1.9 + # Wrapper to accommodate changing Module#const_defined? in Ruby 1.9 def uninherited_const_defined?(mod, const) mod.const_defined?(const) end @@ -384,7 +385,7 @@ module Dependencies #:nodoc: return new_constants ensure # Remove the stack frames that we added. - if defined?(watch_frames) && ! watch_frames.empty? + if defined?(watch_frames) && ! watch_frames.blank? frame_ids = watch_frames.collect(&:object_id) constant_watch_stack.delete_if do |watch_frame| frame_ids.include? watch_frame.object_id diff --git a/activesupport/lib/active_support/deprecation.rb b/activesupport/lib/active_support/deprecation.rb index 6aa379b550..758aef5445 100644 --- a/activesupport/lib/active_support/deprecation.rb +++ b/activesupport/lib/active_support/deprecation.rb @@ -144,8 +144,8 @@ module ActiveSupport end end - # Stand-in for @request, @attributes, @params, etc which emits deprecation - # warnings on any method call (except #inspect). + # Stand-in for <tt>@request</tt>, <tt>@attributes</tt>, <tt>@params</tt>, etc. + # which emits deprecation warnings on any method call (except +inspect+). class DeprecatedInstanceVariableProxy #:nodoc: silence_warnings do instance_methods.each { |m| undef_method m unless m =~ /^__/ } diff --git a/activesupport/lib/active_support/inflector.rb b/activesupport/lib/active_support/inflector.rb index 0fd44324bb..d7f44cb2b9 100644 --- a/activesupport/lib/active_support/inflector.rb +++ b/activesupport/lib/active_support/inflector.rb @@ -109,13 +109,13 @@ module Inflector # Returns the plural form of the word in the string. # - # Examples - # "post".pluralize #=> "posts" - # "octopus".pluralize #=> "octopi" - # "sheep".pluralize #=> "sheep" - # "words".pluralize #=> "words" - # "the blue mailman".pluralize #=> "the blue mailmen" - # "CamelOctopus".pluralize #=> "CamelOctopi" + # Examples: + # "post".pluralize # => "posts" + # "octopus".pluralize # => "octopi" + # "sheep".pluralize # => "sheep" + # "words".pluralize # => "words" + # "the blue mailman".pluralize # => "the blue mailmen" + # "CamelOctopus".pluralize # => "CamelOctopi" def pluralize(word) result = word.to_s.dup @@ -127,15 +127,15 @@ module Inflector end end - # The reverse of pluralize, returns the singular form of a word in a string. + # The reverse of +pluralize+, returns the singular form of a word in a string. # - # Examples - # "posts".singularize #=> "post" - # "octopi".singularize #=> "octopus" - # "sheep".singluarize #=> "sheep" - # "word".singluarize #=> "word" - # "the blue mailmen".singularize #=> "the blue mailman" - # "CamelOctopi".singularize #=> "CamelOctopus" + # Examples: + # "posts".singularize # => "post" + # "octopi".singularize # => "octopus" + # "sheep".singularize # => "sheep" + # "word".singularize # => "word" + # "the blue mailmen".singularize # => "the blue mailman" + # "CamelOctopi".singularize # => "CamelOctopus" def singularize(word) result = word.to_s.dup @@ -147,16 +147,16 @@ module Inflector end end - # By default, camelize converts strings to UpperCamelCase. If the argument to camelize - # is set to ":lower" then camelize produces lowerCamelCase. + # By default, +camelize+ converts strings to UpperCamelCase. If the argument to +camelize+ + # is set to <tt>:lower</tt> then +camelize+ produces lowerCamelCase. # - # camelize will also convert '/' to '::' which is useful for converting paths to namespaces + # +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces. # - # Examples - # "active_record".camelize #=> "ActiveRecord" - # "active_record".camelize(:lower) #=> "activeRecord" - # "active_record/errors".camelize #=> "ActiveRecord::Errors" - # "active_record/errors".camelize(:lower) #=> "activeRecord::Errors" + # Examples: + # "active_record".camelize # => "ActiveRecord" + # "active_record".camelize(:lower) # => "activeRecord" + # "active_record/errors".camelize # => "ActiveRecord::Errors" + # "active_record/errors".camelize(:lower) # => "activeRecord::Errors" def camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true) if first_letter_in_uppercase lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } @@ -166,14 +166,14 @@ module Inflector end # Capitalizes all the words and replaces some characters in the string to create - # a nicer looking title. Titleize is meant for creating pretty output. It is not + # a nicer looking title. +titleize+ is meant for creating pretty output. It is not # used in the Rails internals. # - # titleize is also aliased as as titlecase + # +titleize+ is also aliased as as +titlecase+. # - # Examples - # "man from the boondocks".titleize #=> "Man From The Boondocks" - # "x-men: the last stand".titleize #=> "X Men: The Last Stand" + # Examples: + # "man from the boondocks".titleize # => "Man From The Boondocks" + # "x-men: the last stand".titleize # => "X Men: The Last Stand" def titleize(word) humanize(underscore(word)).gsub(/\b('?[a-z])/) { $1.capitalize } end @@ -182,9 +182,9 @@ module Inflector # # Changes '::' to '/' to convert namespaces to paths. # - # Examples - # "ActiveRecord".underscore #=> "active_record" - # "ActiveRecord::Errors".underscore #=> active_record/errors + # Examples: + # "ActiveRecord".underscore # => "active_record" + # "ActiveRecord::Errors".underscore # => active_record/errors def underscore(camel_cased_word) camel_cased_word.to_s.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). @@ -195,52 +195,52 @@ module Inflector # Replaces underscores with dashes in the string. # - # Example - # "puni_puni" #=> "puni-puni" + # Example: + # "puni_puni" # => "puni-puni" def dasherize(underscored_word) underscored_word.gsub(/_/, '-') end - # Capitalizes the first word and turns underscores into spaces and strips _id. - # Like titleize, this is meant for creating pretty output. + # Capitalizes the first word and turns underscores into spaces and strips a + # trailing "_id", if any. Like +titleize+, this is meant for creating pretty output. # - # Examples - # "employee_salary" #=> "Employee salary" - # "author_id" #=> "Author" + # Examples: + # "employee_salary" # => "Employee salary" + # "author_id" # => "Author" def humanize(lower_case_and_underscored_word) lower_case_and_underscored_word.to_s.gsub(/_id$/, "").gsub(/_/, " ").capitalize end - # Removes the module part from the expression in the string + # Removes the module part from the expression in the string. # - # Examples - # "ActiveRecord::CoreExtensions::String::Inflections".demodulize #=> "Inflections" - # "Inflections".demodulize #=> "Inflections" + # Examples: + # "ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections" + # "Inflections".demodulize # => "Inflections" def demodulize(class_name_in_module) class_name_in_module.to_s.gsub(/^.*::/, '') end # Create the name of a table like Rails does for models to table names. This method - # uses the pluralize method on the last word in the string. + # uses the +pluralize+ method on the last word in the string. # # Examples - # "RawScaledScorer".tableize #=> "raw_scaled_scorers" - # "egg_and_ham".tableize #=> "egg_and_hams" - # "fancyCategory".tableize #=> "fancy_categories" + # "RawScaledScorer".tableize # => "raw_scaled_scorers" + # "egg_and_ham".tableize # => "egg_and_hams" + # "fancyCategory".tableize # => "fancy_categories" def tableize(class_name) pluralize(underscore(class_name)) end # Create a class name from a plural table name like Rails does for table names to models. # Note that this returns a string and not a Class. (To convert to an actual class - # follow classify with constantize.) + # follow +classify+ with +constantize+.) # - # Examples - # "egg_and_hams".classify #=> "EggAndHam" - # "posts".classify #=> "Post" + # Examples: + # "egg_and_hams".classify # => "EggAndHam" + # "posts".classify # => "Post" # - # Singular names are not handled correctly - # "business".classify #=> "Busines" + # Singular names are not handled correctly: + # "business".classify # => "Busines" def classify(table_name) # strip out any leading schema name camelize(singularize(table_name.to_s.sub(/.*\./, ''))) @@ -250,10 +250,10 @@ module Inflector # +separate_class_name_and_id_with_underscore+ sets whether # the method should put '_' between the name and 'id'. # - # Examples - # "Message".foreign_key #=> "message_id" - # "Message".foreign_key(false) #=> "messageid" - # "Admin::Post".foreign_key #=> "post_id" + # Examples: + # "Message".foreign_key # => "message_id" + # "Message".foreign_key(false) # => "messageid" + # "Admin::Post".foreign_key # => "post_id" def foreign_key(class_name, separate_class_name_and_id_with_underscore = true) underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id") end @@ -283,10 +283,10 @@ module Inflector Object.module_eval("::#{$1}", __FILE__, __LINE__) end - # Ordinalize turns a number into an ordinal string used to denote the - # position in an ordered sequence such as 1st, 2nd, 3rd, 4th. + # Turns a number into an ordinal string used to denote the position in an + # ordered sequence such as 1st, 2nd, 3rd, 4th. # - # Examples + # Examples: # ordinalize(1) # => "1st" # ordinalize(2) # => "2nd" # ordinalize(1002) # => "1002nd" diff --git a/activesupport/lib/active_support/json.rb b/activesupport/lib/active_support/json.rb index bbda2c9fa3..2bdb4a7b11 100644 --- a/activesupport/lib/active_support/json.rb +++ b/activesupport/lib/active_support/json.rb @@ -1,5 +1,5 @@ module ActiveSupport - # If true, use ISO 8601 format for dates and times. Otherwise, fall back to the ActiveSupport legacy format. + # If true, use ISO 8601 format for dates and times. Otherwise, fall back to the Active Support legacy format. mattr_accessor :use_standard_json_time_format class << self diff --git a/activesupport/lib/active_support/json/decoding.rb b/activesupport/lib/active_support/json/decoding.rb index c58001f49f..fdb219dbf7 100644 --- a/activesupport/lib/active_support/json/decoding.rb +++ b/activesupport/lib/active_support/json/decoding.rb @@ -31,7 +31,7 @@ module ActiveSupport if json[pos..scanner.pos-2] =~ DATE_REGEX # found a date, track the exact positions of the quotes so we can remove them later. # oh, and increment them for each current mark, each one is an extra padded space that bumps - # the position in the final yaml output + # the position in the final YAML output total_marks = marks.size times << pos+total_marks << scanner.pos+total_marks end diff --git a/activesupport/lib/active_support/json/encoders/date.rb b/activesupport/lib/active_support/json/encoders/date.rb index cb9419d29d..1fc99c466f 100644 --- a/activesupport/lib/active_support/json/encoders/date.rb +++ b/activesupport/lib/active_support/json/encoders/date.rb @@ -1,7 +1,14 @@ class Date - # Returns a JSON string representing the date. + # Returns a JSON string representing the date. If ActiveSupport.use_standard_json_time_format is set to true, the + # ISO 8601 format is used. # - # ==== Example: + # ==== Examples: + # + # # With ActiveSupport.use_standard_json_time_format = true + # Date.new(2005,2,1).to_json + # # => "2005-02-01" + # + # # With ActiveSupport.use_standard_json_time_format = false # Date.new(2005,2,1).to_json # # => "2005/02/01" def to_json(options = nil) diff --git a/activesupport/lib/active_support/json/encoders/date_time.rb b/activesupport/lib/active_support/json/encoders/date_time.rb index d41c3e9786..cd96cda1f7 100644 --- a/activesupport/lib/active_support/json/encoders/date_time.rb +++ b/activesupport/lib/active_support/json/encoders/date_time.rb @@ -1,7 +1,14 @@ class DateTime - # Returns a JSON string representing the datetime. + # Returns a JSON string representing the datetime. If ActiveSupport.use_standard_json_time_format is set to true, the + # ISO 8601 format is used. # - # ==== Example: + # ==== Examples: + # + # # With ActiveSupport.use_standard_json_time_format = true + # DateTime.civil(2005,2,1,15,15,10).to_json + # # => "2005-02-01T15:15:10+00:00" + # + # # With ActiveSupport.use_standard_json_time_format = false # DateTime.civil(2005,2,1,15,15,10).to_json # # => "2005/02/01 15:15:10 +0000" def to_json(options = nil) diff --git a/activesupport/lib/active_support/json/encoders/time.rb b/activesupport/lib/active_support/json/encoders/time.rb index 3660d87c82..09fc614889 100644 --- a/activesupport/lib/active_support/json/encoders/time.rb +++ b/activesupport/lib/active_support/json/encoders/time.rb @@ -1,12 +1,19 @@ class Time - # Returns a JSON string representing the time. + # Returns a JSON string representing the time. If ActiveSupport.use_standard_json_time_format is set to true, the + # ISO 8601 format is used. # - # ==== Example: + # ==== Examples: + # + # # With ActiveSupport.use_standard_json_time_format = true + # Time.utc(2005,2,1,15,15,10).to_json + # # => "2005-02-01T15:15:10Z" + # + # # With ActiveSupport.use_standard_json_time_format = false # Time.utc(2005,2,1,15,15,10).to_json - # # => 2005/02/01 15:15:10 +0000" + # # => "2005/02/01 15:15:10 +0000" def to_json(options = nil) if ActiveSupport.use_standard_json_time_format - utc.xmlschema.inspect + xmlschema.inspect else %("#{strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}") end diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb index 65114415eb..185d03020c 100644 --- a/activesupport/lib/active_support/multibyte/chars.rb +++ b/activesupport/lib/active_support/multibyte/chars.rb @@ -10,7 +10,7 @@ module ActiveSupport::Multibyte #:nodoc: # String methods are proxied through the Chars object, and can be accessed through the +chars+ method. Methods # which would normally return a String object now return a Chars object so methods can be chained. # - # "The Perfect String ".chars.downcase.strip.normalize #=> "the perfect string" + # "The Perfect String ".chars.downcase.strip.normalize # => "the perfect string" # # Chars objects are perfectly interchangeable with String objects as long as no explicit class checks are made. # If certain methods do explicitly check the class, call +to_s+ before you pass chars objects to them. @@ -40,13 +40,15 @@ module ActiveSupport::Multibyte #:nodoc: # core dumps. Don't go there. @string end - + # Make duck-typing with String possible - def respond_to?(method) - super || @string.respond_to?(method) || handler.respond_to?(method) || - (method.to_s =~ /(.*)!/ && handler.respond_to?($1)) || false + def respond_to?(method, include_priv = false) + super || @string.respond_to?(method, include_priv) || + handler.respond_to?(method, include_priv) || + (method.to_s =~ /(.*)!/ && handler.respond_to?($1, include_priv)) || + false end - + # Create a new Chars instance. def initialize(str) @string = str.respond_to?(:string) ? str.string : str diff --git a/activesupport/lib/active_support/multibyte/handlers/utf8_handler.rb b/activesupport/lib/active_support/multibyte/handlers/utf8_handler.rb index 0166b69ac3..aa9c16f575 100644 --- a/activesupport/lib/active_support/multibyte/handlers/utf8_handler.rb +++ b/activesupport/lib/active_support/multibyte/handlers/utf8_handler.rb @@ -147,13 +147,11 @@ module ActiveSupport::Multibyte::Handlers #:nodoc: # # s = "Müller" # s.chars[2] = "e" # Replace character with offset 2 - # s - # #=> "Müeler" + # s # => "Müeler" # # s = "Müller" # s.chars[1, 2] = "ö" # Replace 2 characters at character offset 1 - # s - # #=> "Möler" + # s # => "Möler" def []=(str, *args) replace_by = args.pop # Indexed replace with regular expressions already works @@ -183,10 +181,10 @@ module ActiveSupport::Multibyte::Handlers #:nodoc: # Example: # # "¾ cup".chars.rjust(8).to_s - # #=> " ¾ cup" + # # => " ¾ cup" # # "¾ cup".chars.rjust(8, " ").to_s # Use non-breaking whitespace - # #=> " ¾ cup" + # # => " ¾ cup" def rjust(str, integer, padstr=' ') justify(str, integer, :right, padstr) end @@ -196,10 +194,10 @@ module ActiveSupport::Multibyte::Handlers #:nodoc: # Example: # # "¾ cup".chars.rjust(8).to_s - # #=> "¾ cup " + # # => "¾ cup " # # "¾ cup".chars.rjust(8, " ").to_s # Use non-breaking whitespace - # #=> "¾ cup " + # # => "¾ cup " def ljust(str, integer, padstr=' ') justify(str, integer, :left, padstr) end @@ -209,10 +207,10 @@ module ActiveSupport::Multibyte::Handlers #:nodoc: # Example: # # "¾ cup".chars.center(8).to_s - # #=> " ¾ cup " + # # => " ¾ cup " # # "¾ cup".chars.center(8, " ").to_s # Use non-breaking whitespace - # #=> " ¾ cup " + # # => " ¾ cup " def center(str, integer, padstr=' ') justify(str, integer, :center, padstr) end diff --git a/activesupport/lib/active_support/testing/setup_and_teardown.rb b/activesupport/lib/active_support/testing/setup_and_teardown.rb index b2a937edd0..ed8e34510a 100644 --- a/activesupport/lib/active_support/testing/setup_and_teardown.rb +++ b/activesupport/lib/active_support/testing/setup_and_teardown.rb @@ -1,6 +1,14 @@ module ActiveSupport module Testing module SetupAndTeardown + # For compatibility with Ruby < 1.8.6 + PASSTHROUGH_EXCEPTIONS = + if defined?(Test::Unit::TestCase::PASSTHROUGH_EXCEPTIONS) + Test::Unit::TestCase::PASSTHROUGH_EXCEPTIONS + else + [NoMemoryError, SignalException, Interrupt, SystemExit] + end + def self.included(base) base.send :include, ActiveSupport::Callbacks base.define_callbacks :setup, :teardown @@ -25,7 +33,7 @@ module ActiveSupport __send__(@method_name) rescue Test::Unit::AssertionFailedError => e add_failure(e.message, e.backtrace) - rescue *Test::Unit::TestCase::PASSTHROUGH_EXCEPTIONS + rescue *PASSTHROUGH_EXCEPTIONS raise rescue Exception add_error($!) @@ -35,7 +43,7 @@ module ActiveSupport run_callbacks :teardown, :enumerator => :reverse_each rescue Test::Unit::AssertionFailedError => e add_failure(e.message, e.backtrace) - rescue *Test::Unit::TestCase::PASSTHROUGH_EXCEPTIONS + rescue *PASSTHROUGH_EXCEPTIONS raise rescue Exception add_error($!) diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb index 48606dbcff..4218ed5928 100644 --- a/activesupport/lib/active_support/time_with_zone.rb +++ b/activesupport/lib/active_support/time_with_zone.rb @@ -1,7 +1,34 @@ require 'tzinfo' module ActiveSupport # A Time-like class that can represent a time in any time zone. Necessary because standard Ruby Time instances are - # limited to UTC and the system's ENV['TZ'] zone + # limited to UTC and the system's <tt>ENV['TZ']</tt> zone. + # + # You shouldn't ever need to create a TimeWithZone instance directly via <tt>new</tt> -- instead, Rails provides the methods + # +local+, +parse+, +at+ and +now+ on TimeZone instances, and +in_time_zone+ on Time and DateTime instances, for a more + # user-friendly syntax. Examples: + # + # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' + # Time.zone.local(2007, 2, 10, 15, 30, 45) # => Sat, 10 Feb 2007 15:30:45 EST -05:00 + # Time.zone.parse('2007-02-01 15:30:45') # => Sat, 10 Feb 2007 15:30:45 EST -05:00 + # Time.zone.at(1170361845) # => Sat, 10 Feb 2007 15:30:45 EST -05:00 + # Time.zone.now # => Sun, 18 May 2008 13:07:55 EDT -04:00 + # Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone # => Sat, 10 Feb 2007 15:30:45 EST -05:00 + # + # See TimeZone and ActiveSupport::CoreExtensions::Time::Zones for further documentation for these methods. + # + # TimeWithZone instances implement the same API as Ruby Time instances, so that Time and TimeWithZone instances are interchangable. Examples: + # + # t = Time.zone.now # => Sun, 18 May 2008 13:27:25 EDT -04:00 + # t.hour # => 13 + # t.dst? # => true + # t.utc_offset # => -14400 + # t.zone # => "EDT" + # t.to_s(:rfc822) # => "Sun, 18 May 2008 13:27:25 -0400" + # t + 1.day # => Mon, 19 May 2008 13:27:25 EDT -04:00 + # t.beginning_of_year # => Tue, 01 Jan 2008 00:00:00 EST -05:00 + # t > Time.utc(1999) # => true + # t.is_a?(Time) # => true + # t.is_a?(ActiveSupport::TimeWithZone) # => true class TimeWithZone include Comparable attr_reader :time_zone @@ -11,12 +38,12 @@ module ActiveSupport @period = @utc ? period : get_period_and_ensure_valid_local_time end - # Returns a Time or DateTime instance that represents the time in time_zone + # Returns a Time or DateTime instance that represents the time in +time_zone+. def time @time ||= period.to_local(@utc) end - # Returns a Time or DateTime instance that represents the time in UTC + # Returns a Time or DateTime instance that represents the time in UTC. def utc @utc ||= period.to_utc(@time) end @@ -25,18 +52,18 @@ module ActiveSupport alias_method :getutc, :utc alias_method :gmtime, :utc - # Returns the underlying TZInfo::TimezonePeriod + # Returns the underlying TZInfo::TimezonePeriod. def period @period ||= time_zone.period_for_utc(@utc) end - # Returns the simultaneous time in Time.zone, or the specified zone + # Returns the simultaneous time in <tt>Time.zone</tt>, or the specified zone. def in_time_zone(new_zone = ::Time.zone) return self if time_zone == new_zone utc.in_time_zone(new_zone) end - # Returns a Time.local() instance of the simultaneous time in your system's ENV['TZ'] zone + # Returns a <tt>Time.local()</tt> instance of the simultaneous time in your system's <tt>ENV['TZ']</tt> zone def localtime utc.getlocal end @@ -62,7 +89,7 @@ module ActiveSupport utc? && alternate_utc_string || utc_offset.to_utc_offset_s(colon) end - # Time uses #zone to display the time zone abbreviation, so we're duck-typing it + # Time uses +zone+ to display the time zone abbreviation, so we're duck-typing it. def zone period.zone_identifier.to_s end @@ -75,7 +102,19 @@ module ActiveSupport "#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{formatted_offset(true, 'Z')}" end alias_method :iso8601, :xmlschema - + + # Returns a JSON string representing the TimeWithZone. If ActiveSupport.use_standard_json_time_format is set to + # true, the ISO 8601 format is used. + # + # ==== Examples: + # + # # With ActiveSupport.use_standard_json_time_format = true + # Time.utc(2005,2,1,15,15,10).in_time_zone.to_json + # # => "2005-02-01T15:15:10Z" + # + # # With ActiveSupport.use_standard_json_time_format = false + # Time.utc(2005,2,1,15,15,10).in_time_zone.to_json + # # => "2005/02/01 15:15:10 +0000" def to_json(options = nil) if ActiveSupport.use_standard_json_time_format xmlschema.inspect @@ -119,7 +158,7 @@ module ActiveSupport time.strftime(format) end - # Use the time in UTC for comparisons + # Use the time in UTC for comparisons. def <=>(other) utc <=> other end @@ -132,10 +171,10 @@ module ActiveSupport utc == other end - # If wrapped #time is a DateTime, use DateTime#since instead of #+ - # Otherwise, just pass on to #method_missing + # If wrapped +time+ is a DateTime, use DateTime#since instead of <tt>+</tt>. + # Otherwise, just pass on to +method_missing+. def +(other) - result = utc.acts_like?(:date) ? utc.since(other) : utc + other + result = utc.acts_like?(:date) ? utc.since(other) : utc + other rescue utc.since(other) result.in_time_zone(time_zone) end @@ -146,7 +185,7 @@ module ActiveSupport if other.acts_like?(:time) utc - other else - result = utc.acts_like?(:date) ? utc.ago(other) : utc - other + result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other) result.in_time_zone(time_zone) end end @@ -198,18 +237,18 @@ module ActiveSupport utc.to_datetime.new_offset(Rational(utc_offset, 86_400)) end - # so that self acts_like?(:time) + # So that +self+ <tt>acts_like?(:time)</tt>. def acts_like_time? true end - # Say we're a Time to thwart type checking + # Say we're a Time to thwart type checking. def is_a?(klass) klass == ::Time || super end alias_method :kind_of?, :is_a? - # Neuter freeze because freezing can cause problems with lazy loading of attributes + # Neuter freeze because freezing can cause problems with lazy loading of attributes. def freeze self end @@ -221,15 +260,15 @@ module ActiveSupport def marshal_load(variables) initialize(variables[0], ::Time.send!(:get_zone, variables[1]), variables[2]) end - - # Ensure proxy class responds to all methods that underlying time instance responds to - def respond_to?(sym) + + # Ensure proxy class responds to all methods that underlying time instance responds to. + def respond_to?(sym, include_priv = false) # consistently respond false to acts_like?(:date), regardless of whether #time is a Time or DateTime return false if sym.to_s == 'acts_like_date?' - super || time.respond_to?(sym) + super || time.respond_to?(sym, include_priv) end - - # Send the missing method to time instance, and wrap result in a new TimeWithZone with the existing time_zone + + # Send the missing method to +time+ instance, and wrap result in a new TimeWithZone with the existing +time_zone+. def method_missing(sym, *args, &block) result = time.__send__(sym, *args, &block) result.acts_like?(:time) ? self.class.new(nil, time_zone, result) : result diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb index f522b64108..64d734f039 100644 --- a/activesupport/lib/active_support/values/time_zone.rb +++ b/activesupport/lib/active_support/values/time_zone.rb @@ -1,3 +1,24 @@ +# The TimeZone class serves as a wrapper around TZInfo::Timezone instances. It allows us to do the following: +# +# * Limit the set of zones provided by TZInfo to a meaningful subset of 142 zones. +# * Retrieve and display zones with a friendlier name (e.g., "Eastern Time (US & Canada)" instead of "America/New_York"). +# * Lazily load TZInfo::Timezone instances only when they're needed. +# * Create ActiveSupport::TimeWithZone instances via TimeZone's +local+, +parse+, +at+ and +now+ methods. +# +# If you set <tt>config.time_zone</tt> in the Rails Initializer, you can access this TimeZone object via <tt>Time.zone</tt>: +# +# # environment.rb: +# Rails::Initializer.run do |config| +# config.time_zone = "Eastern Time (US & Canada)" +# end +# +# Time.zone # => #<TimeZone:0x514834...> +# Time.zone.name # => "Eastern Time (US & Canada)" +# Time.zone.now # => Sun, 18 May 2008 14:30:44 EDT -04:00 +# +# The version of TZInfo bundled with Active Support only includes the definitions necessary to support the zones +# defined by the TimeZone class. If you need to use zones that aren't defined by TimeZone, you'll need to install the TZInfo gem +# (if a recent version of the gem is installed locally, this will be used instead of the bundled version.) class TimeZone unless const_defined?(:MAPPING) # Keys are Rails TimeZone names, values are TZInfo identifiers @@ -171,7 +192,7 @@ class TimeZone utc_offset == 0 && alternate_utc_string || utc_offset.to_utc_offset_s(colon) end - # Compare this time zone to the parameter. The two are comapred first on + # Compare this time zone to the parameter. The two are compared first on # their offsets, and then by name. def <=>(zone) result = (utc_offset <=> zone.utc_offset) @@ -181,7 +202,7 @@ class TimeZone # Returns a textual representation of this time zone. def to_s - "(UTC#{formatted_offset}) #{name}" + "(GMT#{formatted_offset}) #{name}" end # Method for creating new ActiveSupport::TimeWithZone instance in time zone of +self+ from given values. Example: @@ -335,7 +356,7 @@ class TimeZone # Return a TimeZone instance with the given name, or +nil+ if no # such TimeZone instance exists. (This exists to support the use of - # this class with the #composed_of macro.) + # this class with the +composed_of+ macro.) def new(name) self[name] end diff --git a/activesupport/lib/active_support/vendor/builder-2.1.2/builder/xmlevents.rb b/activesupport/lib/active_support/vendor/builder-2.1.2/builder/xmlevents.rb index 91fcd21e13..b373e4da3c 100644 --- a/activesupport/lib/active_support/vendor/builder-2.1.2/builder/xmlevents.rb +++ b/activesupport/lib/active_support/vendor/builder-2.1.2/builder/xmlevents.rb @@ -20,7 +20,7 @@ module Builder # markup. # # Usage: - # xe = Builder::XmlEvents.new(hander) + # xe = Builder::XmlEvents.new(handler) # xe.title("HI") # Sends start_tag/end_tag/text messages to the handler. # # Indentation may also be selected by providing value for the diff --git a/activesupport/lib/active_support/vendor/memcache-client-1.5.0/memcache.rb b/activesupport/lib/active_support/vendor/memcache-client-1.5.0/memcache.rb index dda7f2c30e..30113201a6 100644 --- a/activesupport/lib/active_support/vendor/memcache-client-1.5.0/memcache.rb +++ b/activesupport/lib/active_support/vendor/memcache-client-1.5.0/memcache.rb @@ -119,7 +119,7 @@ class MemCache # Valid options for +opts+ are: # # [:namespace] Prepends this value to all keys added or retrieved. - # [:readonly] Raises an exeception on cache writes when true. + # [:readonly] Raises an exception on cache writes when true. # [:multithread] Wraps cache access in a Mutex for thread safety. # # Other options are ignored. @@ -207,7 +207,7 @@ class MemCache end ## - # Deceremets the value for +key+ by +amount+ and returns the new value. + # Decrements the value for +key+ by +amount+ and returns the new value. # +key+ must already exist. If +key+ is not an integer, it is assumed to be # 0. +key+ can not be decremented below 0. diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/data_timezone.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/data_timezone.rb index 5eccbdf0db..2510e90b5b 100644 --- a/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/data_timezone.rb +++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/data_timezone.rb @@ -38,7 +38,7 @@ module TZInfo # Returns the set of TimezonePeriod instances that are valid for the given # local time as an array. If you just want a single period, use - # period_for_local instead and specify how abiguities should be resolved. + # period_for_local instead and specify how ambiguities should be resolved. # Raises PeriodNotFound if no periods are found for the given time. def periods_for_local(local) info.periods_for_local(local) diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/data_timezone_info.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/data_timezone_info.rb index f34fabc36a..d2a6620dd2 100644 --- a/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/data_timezone_info.rb +++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/data_timezone_info.rb @@ -64,7 +64,7 @@ module TZInfo # ArgumentError will be raised if a transition is added out of order. # offset_id refers to an id defined with offset. ArgumentError will be # raised if the offset_id cannot be found. numerator_or_time and - # denomiator specify the time the transition occurs as. See + # denominator specify the time the transition occurs as. See # TimezoneTransitionInfo for more detail about specifying times. def transition(year, month, offset_id, numerator_or_time, denominator = nil) offset = @offsets[offset_id] diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/linked_timezone.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/linked_timezone.rb index f8ec4fca87..c757485b84 100644 --- a/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/linked_timezone.rb +++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/linked_timezone.rb @@ -36,7 +36,7 @@ module TZInfo # Returns the set of TimezonePeriod instances that are valid for the given # local time as an array. If you just want a single period, use - # period_for_local instead and specify how abiguities should be resolved. + # period_for_local instead and specify how ambiguities should be resolved. # Raises PeriodNotFound if no periods are found for the given time. def periods_for_local(local) @linked_timezone.periods_for_local(local) diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/offset_rationals.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/offset_rationals.rb index 5857de623d..32fa4123f1 100644 --- a/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/offset_rationals.rb +++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/offset_rationals.rb @@ -27,63 +27,63 @@ module TZInfo # -14 and +14 hours to avoid having to call gcd at runtime. module OffsetRationals #:nodoc: @@rational_cache = { - -50400 => Rational.new!(-7,12), - -48600 => Rational.new!(-9,16), - -46800 => Rational.new!(-13,24), - -45000 => Rational.new!(-25,48), - -43200 => Rational.new!(-1,2), - -41400 => Rational.new!(-23,48), - -39600 => Rational.new!(-11,24), - -37800 => Rational.new!(-7,16), - -36000 => Rational.new!(-5,12), - -34200 => Rational.new!(-19,48), - -32400 => Rational.new!(-3,8), - -30600 => Rational.new!(-17,48), - -28800 => Rational.new!(-1,3), - -27000 => Rational.new!(-5,16), - -25200 => Rational.new!(-7,24), - -23400 => Rational.new!(-13,48), - -21600 => Rational.new!(-1,4), - -19800 => Rational.new!(-11,48), - -18000 => Rational.new!(-5,24), - -16200 => Rational.new!(-3,16), - -14400 => Rational.new!(-1,6), - -12600 => Rational.new!(-7,48), - -10800 => Rational.new!(-1,8), - -9000 => Rational.new!(-5,48), - -7200 => Rational.new!(-1,12), - -5400 => Rational.new!(-1,16), - -3600 => Rational.new!(-1,24), - -1800 => Rational.new!(-1,48), - 0 => Rational.new!(0,1), - 1800 => Rational.new!(1,48), - 3600 => Rational.new!(1,24), - 5400 => Rational.new!(1,16), - 7200 => Rational.new!(1,12), - 9000 => Rational.new!(5,48), - 10800 => Rational.new!(1,8), - 12600 => Rational.new!(7,48), - 14400 => Rational.new!(1,6), - 16200 => Rational.new!(3,16), - 18000 => Rational.new!(5,24), - 19800 => Rational.new!(11,48), - 21600 => Rational.new!(1,4), - 23400 => Rational.new!(13,48), - 25200 => Rational.new!(7,24), - 27000 => Rational.new!(5,16), - 28800 => Rational.new!(1,3), - 30600 => Rational.new!(17,48), - 32400 => Rational.new!(3,8), - 34200 => Rational.new!(19,48), - 36000 => Rational.new!(5,12), - 37800 => Rational.new!(7,16), - 39600 => Rational.new!(11,24), - 41400 => Rational.new!(23,48), - 43200 => Rational.new!(1,2), - 45000 => Rational.new!(25,48), - 46800 => Rational.new!(13,24), - 48600 => Rational.new!(9,16), - 50400 => Rational.new!(7,12)} + -50400 => Rational(-7,12), + -48600 => Rational(-9,16), + -46800 => Rational(-13,24), + -45000 => Rational(-25,48), + -43200 => Rational(-1,2), + -41400 => Rational(-23,48), + -39600 => Rational(-11,24), + -37800 => Rational(-7,16), + -36000 => Rational(-5,12), + -34200 => Rational(-19,48), + -32400 => Rational(-3,8), + -30600 => Rational(-17,48), + -28800 => Rational(-1,3), + -27000 => Rational(-5,16), + -25200 => Rational(-7,24), + -23400 => Rational(-13,48), + -21600 => Rational(-1,4), + -19800 => Rational(-11,48), + -18000 => Rational(-5,24), + -16200 => Rational(-3,16), + -14400 => Rational(-1,6), + -12600 => Rational(-7,48), + -10800 => Rational(-1,8), + -9000 => Rational(-5,48), + -7200 => Rational(-1,12), + -5400 => Rational(-1,16), + -3600 => Rational(-1,24), + -1800 => Rational(-1,48), + 0 => Rational(0,1), + 1800 => Rational(1,48), + 3600 => Rational(1,24), + 5400 => Rational(1,16), + 7200 => Rational(1,12), + 9000 => Rational(5,48), + 10800 => Rational(1,8), + 12600 => Rational(7,48), + 14400 => Rational(1,6), + 16200 => Rational(3,16), + 18000 => Rational(5,24), + 19800 => Rational(11,48), + 21600 => Rational(1,4), + 23400 => Rational(13,48), + 25200 => Rational(7,24), + 27000 => Rational(5,16), + 28800 => Rational(1,3), + 30600 => Rational(17,48), + 32400 => Rational(3,8), + 34200 => Rational(19,48), + 36000 => Rational(5,12), + 37800 => Rational(7,16), + 39600 => Rational(11,24), + 41400 => Rational(23,48), + 43200 => Rational(1,2), + 45000 => Rational(25,48), + 46800 => Rational(13,24), + 48600 => Rational(9,16), + 50400 => Rational(7,12)} # Returns a Rational expressing the fraction of a day that offset in # seconds represents (i.e. equivalent to Rational(offset, 86400)). diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/timezone.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/timezone.rb index 04f2f2f0a5..910eefca02 100644 --- a/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/timezone.rb +++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/timezone.rb @@ -121,7 +121,7 @@ module TZInfo TimezoneProxy.new(identifier) end - # If identifier is nil calls super(), otherwise calls get. An identfier + # If identifier is nil calls super(), otherwise calls get. An identifier # should always be passed in when called externally. def self.new(identifier = nil) if identifier diff --git a/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/timezone_transition_info.rb b/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/timezone_transition_info.rb index 6ae1b7df97..146c131708 100644 --- a/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/timezone_transition_info.rb +++ b/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/timezone_transition_info.rb @@ -37,7 +37,7 @@ module TZInfo attr_reader :numerator_or_time protected :numerator_or_time - # Either the denominotor of the DateTime if the transition time is defined + # Either the denominator of the DateTime if the transition time is defined # as a DateTime, otherwise nil. attr_reader :denominator protected :denominator diff --git a/activesupport/lib/active_support/vendor/xml-simple-1.0.11/xmlsimple.rb b/activesupport/lib/active_support/vendor/xml-simple-1.0.11/xmlsimple.rb index 0de24c0eff..ec6dab513f 100644 --- a/activesupport/lib/active_support/vendor/xml-simple-1.0.11/xmlsimple.rb +++ b/activesupport/lib/active_support/vendor/xml-simple-1.0.11/xmlsimple.rb @@ -121,7 +121,7 @@ class XmlSimple # Create a "global" cache. @@cache = Cache.new - # Creates and intializes a new XmlSimple object. + # Creates and initializes a new XmlSimple object. # # defaults:: # Default values for options. @@ -497,7 +497,7 @@ class XmlSimple } end - # Fold Hases containing a single anonymous Array up into just the Array. + # Fold Hashes containing a single anonymous Array up into just the Array. if count == 1 anonymoustag = @options['anonymoustag'] if result.has_key?(anonymoustag) && result[anonymoustag].instance_of?(Array) @@ -907,7 +907,7 @@ class XmlSimple # Thanks to Norbert Gawor for a bugfix. # # value:: - # Value to be checked for emptyness. + # Value to be checked for emptiness. def empty(value) case value when Hash diff --git a/activesupport/lib/active_support/version.rb b/activesupport/lib/active_support/version.rb index f3d141cf72..b346459a9b 100644 --- a/activesupport/lib/active_support/version.rb +++ b/activesupport/lib/active_support/version.rb @@ -1,8 +1,8 @@ module ActiveSupport module VERSION #:nodoc: MAJOR = 2 - MINOR = 0 - TINY = 991 + MINOR = 1 + TINY = 0 STRING = [MAJOR, MINOR, TINY].join('.') end diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index 706e218abc..69028a123f 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -733,6 +733,44 @@ class HashToXmlTest < Test::Unit::TestCase assert_equal hash, Hash.from_xml(hash.to_xml(@xml_options))['person'] end + + def test_datetime_xml_type_with_utc_time + alert_xml = <<-XML + <alert> + <alert_at type="datetime">2008-02-10T15:30:45Z</alert_at> + </alert> + XML + alert_at = Hash.from_xml(alert_xml)['alert']['alert_at'] + assert alert_at.utc? + assert_equal Time.utc(2008, 2, 10, 15, 30, 45), alert_at + end + + def test_datetime_xml_type_with_non_utc_time + alert_xml = <<-XML + <alert> + <alert_at type="datetime">2008-02-10T10:30:45-05:00</alert_at> + </alert> + XML + alert_at = Hash.from_xml(alert_xml)['alert']['alert_at'] + assert alert_at.utc? + assert_equal Time.utc(2008, 2, 10, 15, 30, 45), alert_at + end + + def test_datetime_xml_type_with_far_future_date + alert_xml = <<-XML + <alert> + <alert_at type="datetime">2050-02-10T15:30:45Z</alert_at> + </alert> + XML + alert_at = Hash.from_xml(alert_xml)['alert']['alert_at'] + assert alert_at.utc? + assert_equal 2050, alert_at.year + assert_equal 2, alert_at.month + assert_equal 10, alert_at.day + assert_equal 15, alert_at.hour + assert_equal 30, alert_at.min + assert_equal 45, alert_at.sec + end end class QueryTest < Test::Unit::TestCase diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb index 70c393dd46..c373bca88d 100644 --- a/activesupport/test/core_ext/time_with_zone_test.rb +++ b/activesupport/test/core_ext/time_with_zone_test.rb @@ -170,6 +170,13 @@ class TimeWithZoneTest < Test::Unit::TestCase assert_equal DateTime.civil(1999, 12, 31, 19, 0 ,5), (twz + 5).time end end + + def test_plus_when_crossing_time_class_limit + silence_warnings do # silence warnings raised by tzinfo gem + twz = ActiveSupport::TimeWithZone.new(Time.utc(2038, 1, 19), @time_zone) + assert_equal [0, 0, 19, 19, 1, 2038], (twz + 86_400).to_a[0,6] + end + end def test_plus_with_duration silence_warnings do # silence warnings raised by tzinfo gem diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb index 9e98e764fd..0309ab6858 100644 --- a/activesupport/test/dependencies_test.rb +++ b/activesupport/test/dependencies_test.rb @@ -584,6 +584,12 @@ class DependenciesTest < Test::Unit::TestCase assert_equal [], m end + def test_new_constants_in_with_illegal_module_name_raises_correct_error + assert_raises(NameError) do + Dependencies.new_constants_in("Illegal-Name") {} + end + end + def test_file_with_multiple_constants_and_require_dependency with_loading 'autoloading_fixtures' do assert ! defined?(MultipleConstantFile) @@ -667,7 +673,7 @@ class DependenciesTest < Test::Unit::TestCase assert !defined?(::RaisesNoMethodError), "::RaisesNoMethodError is defined but it should have failed!" end end - + ensure Object.class_eval { remove_const :RaisesNoMethodError if const_defined?(:RaisesNoMethodError) } end @@ -680,11 +686,20 @@ class DependenciesTest < Test::Unit::TestCase assert !defined?(::RaisesNoMethodError), "::RaisesNoMethodError is defined but it should have failed!" end end - + ensure Object.class_eval { remove_const :RaisesNoMethodError if const_defined?(:RaisesNoMethodError) } end + def test_autoload_doesnt_shadow_error_when_mechanism_not_set_to_load + with_loading 'autoloading_fixtures' do + Dependencies.mechanism = :require + 2.times do + assert_raise(NameError) {"RaisesNameError".constantize} + end + end + end + def test_autoload_doesnt_shadow_name_error with_loading 'autoloading_fixtures' do assert !defined?(::RaisesNameError), "::RaisesNameError is defined but it hasn't been referenced yet!" @@ -708,7 +723,7 @@ class DependenciesTest < Test::Unit::TestCase ensure Object.class_eval { remove_const :RaisesNoMethodError if const_defined?(:RaisesNoMethodError) } end - + def test_remove_constant_handles_double_colon_at_start Object.const_set 'DeleteMe', Module.new DeleteMe.const_set 'OrMe', Module.new @@ -718,7 +733,7 @@ class DependenciesTest < Test::Unit::TestCase Dependencies.remove_constant "::DeleteMe" assert ! defined?(DeleteMe) end - + def test_load_once_constants_should_not_be_unloaded with_loading 'autoloading_fixtures' do Dependencies.load_once_paths = Dependencies.load_paths @@ -731,7 +746,7 @@ class DependenciesTest < Test::Unit::TestCase Dependencies.load_once_paths = [] Object.class_eval { remove_const :A if const_defined?(:A) } end - + def test_load_once_paths_should_behave_when_recursively_loading with_loading 'dependencies', 'autoloading_fixtures' do Dependencies.load_once_paths = [Dependencies.load_paths.last] @@ -747,5 +762,4 @@ class DependenciesTest < Test::Unit::TestCase ensure Dependencies.load_once_paths = [] end - end diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb index 7bc8eaf06c..38bb8f3e79 100644 --- a/activesupport/test/json/encoding_test.rb +++ b/activesupport/test/json/encoding_test.rb @@ -90,6 +90,15 @@ class TestJSONEncoding < Test::Unit::TestCase def test_hash_should_allow_key_filtering_with_except assert_equal %({"b": 2}), { 'foo' => 'bar', :b => 2, :c => 3 }.to_json(:except => ['foo', :c]) end + + def test_time_to_json_includes_local_offset + ActiveSupport.use_standard_json_time_format = true + with_env_tz 'US/Eastern' do + assert_equal %("2005-02-01T15:15:10-05:00"), Time.local(2005,2,1,15,15,10).to_json + end + ensure + ActiveSupport.use_standard_json_time_format = false + end protected def with_kcode(code) @@ -108,6 +117,13 @@ class TestJSONEncoding < Test::Unit::TestCase def object_keys(json_object) json_object[1..-2].scan(/([^{}:,\s]+):/).flatten.sort end + + def with_env_tz(new_tz = 'US/Eastern') + old_tz, ENV['TZ'] = ENV['TZ'], new_tz + yield + ensure + old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ') + end end uses_mocha 'JsonOptionsTests' do diff --git a/activesupport/test/time_zone_test.rb b/activesupport/test/time_zone_test.rb index 3757ddcedb..f3069b589b 100644 --- a/activesupport/test/time_zone_test.rb +++ b/activesupport/test/time_zone_test.rb @@ -252,7 +252,7 @@ class TimeZoneTest < Test::Unit::TestCase end def test_to_s - assert_equal "(UTC+03:00) Moscow", TimeZone['Moscow'].to_s + assert_equal "(GMT+03:00) Moscow", TimeZone['Moscow'].to_s end def test_all_sorted diff --git a/railties/CHANGELOG b/railties/CHANGELOG index 11d2926f31..fe517755ef 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,4 +1,4 @@ -*2.1.0 RC1 (May 11th, 2008)* +*2.1.0 (May 31st, 2008)* * script/dbconsole fires up the command-line database client. #102 [Steve Purcell] diff --git a/railties/Rakefile b/railties/Rakefile index 45ba394299..a1d1095c37 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -304,11 +304,11 @@ spec = Gem::Specification.new do |s| EOF s.add_dependency('rake', '>= 0.8.1') - s.add_dependency('activesupport', '= 2.0.991' + PKG_BUILD) - s.add_dependency('activerecord', '= 2.0.991' + PKG_BUILD) - s.add_dependency('actionpack', '= 2.0.991' + PKG_BUILD) - s.add_dependency('actionmailer', '= 2.0.991' + PKG_BUILD) - s.add_dependency('activeresource', '= 2.0.991' + PKG_BUILD) + s.add_dependency('activesupport', '= 2.1.0' + PKG_BUILD) + s.add_dependency('activerecord', '= 2.1.0' + PKG_BUILD) + s.add_dependency('actionpack', '= 2.1.0' + PKG_BUILD) + s.add_dependency('actionmailer', '= 2.1.0' + PKG_BUILD) + s.add_dependency('activeresource', '= 2.1.0' + PKG_BUILD) s.rdoc_options << '--exclude' << '.' s.has_rdoc = false diff --git a/railties/configs/databases/frontbase.yml b/railties/configs/databases/frontbase.yml index 2eed3133a1..c0c3588be1 100644 --- a/railties/configs/databases/frontbase.yml +++ b/railties/configs/databases/frontbase.yml @@ -10,8 +10,8 @@ development: username: <%= app_name %> password: '' -# Warning: The database defined as 'test' will be erased and -# re-generated from your development database when you run 'rake'. +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: adapter: frontbase diff --git a/railties/configs/databases/mysql.yml b/railties/configs/databases/mysql.yml index c5c894c5e1..7fcadcdf2c 100644 --- a/railties/configs/databases/mysql.yml +++ b/railties/configs/databases/mysql.yml @@ -26,8 +26,8 @@ development: host: localhost <% end -%> -# Warning: The database defined as 'test' will be erased and -# re-generated from your development database when you run 'rake'. +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: adapter: mysql diff --git a/railties/configs/databases/oracle.yml b/railties/configs/databases/oracle.yml index c86cbdbaba..a1883f6256 100644 --- a/railties/configs/databases/oracle.yml +++ b/railties/configs/databases/oracle.yml @@ -4,7 +4,7 @@ # http://rubyforge.org/projects/ruby-oci8/ # # Specify your database using any valid connection syntax, such as a -# tnsnames.ora service name, or a sql connect url string of the form: +# tnsnames.ora service name, or a SQL connect url string of the form: # # //host:[port][/service name] # @@ -23,8 +23,8 @@ development: username: <%= app_name %> password: -# Warning: The database defined as 'test' will be erased and -# re-generated from your development database when you run 'rake'. +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: adapter: oracle diff --git a/railties/configs/databases/postgresql.yml b/railties/configs/databases/postgresql.yml index c1b911a9a4..36f6e5ae49 100644 --- a/railties/configs/databases/postgresql.yml +++ b/railties/configs/databases/postgresql.yml @@ -30,8 +30,8 @@ development: # The server defaults to notice. #min_messages: warning -# Warning: The database defined as 'test' will be erased and -# re-generated from your development database when you run 'rake'. +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: adapter: postgresql diff --git a/railties/configs/databases/sqlite2.yml b/railties/configs/databases/sqlite2.yml index 26d3957d79..fc48bd6753 100644 --- a/railties/configs/databases/sqlite2.yml +++ b/railties/configs/databases/sqlite2.yml @@ -4,8 +4,8 @@ development: adapter: sqlite database: db/development.sqlite2 -# Warning: The database defined as 'test' will be erased and -# re-generated from your development database when you run 'rake'. +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: adapter: sqlite diff --git a/railties/configs/databases/sqlite3.yml b/railties/configs/databases/sqlite3.yml index b444b03cd4..fff44a4124 100644 --- a/railties/configs/databases/sqlite3.yml +++ b/railties/configs/databases/sqlite3.yml @@ -5,8 +5,8 @@ development: database: db/development.sqlite3 timeout: 5000 -# Warning: The database defined as 'test' will be erased and -# re-generated from your development database when you run 'rake'. +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: adapter: sqlite3 diff --git a/railties/configs/initializers/new_rails_defaults.rb b/railties/configs/initializers/new_rails_defaults.rb index b8f0e2cac2..5e60c0ade4 100644 --- a/railties/configs/initializers/new_rails_defaults.rb +++ b/railties/configs/initializers/new_rails_defaults.rb @@ -1,18 +1,15 @@ -# These settins change the behavior of Rails 2 apps and will be defaults +# These settings change the behavior of Rails 2 apps and will be defaults # for Rails 3. You can remove this initializer when Rails 3 is released. -# Only save the attributes that have changed since the record was loaded. -ActiveRecord::Base.partial_updates = true - -# Include ActiveRecord class name as root for JSON serialized output. +# Include Active Record class name as root for JSON serialized output. ActiveRecord::Base.include_root_in_json = true -# Store the full class name (including module namespace) in STI type column +# Store the full class name (including module namespace) in STI type column. ActiveRecord::Base.store_full_sti_class = true -# Use ISO 8601 format for JSON serialized times and dates +# Use ISO 8601 format for JSON serialized times and dates. ActiveSupport.use_standard_json_time_format = true -# Don't escape HTML entities in JSON, leave that for the #json_escape helper +# Don't escape HTML entities in JSON, leave that for the #json_escape helper. # if you're including raw json in an HTML page. ActiveSupport.escape_html_entities_in_json = false
\ No newline at end of file diff --git a/railties/doc/guides/actionview/helpers.markdown b/railties/doc/guides/actionview/helpers.markdown new file mode 100644 index 0000000000..c191c5e5ef --- /dev/null +++ b/railties/doc/guides/actionview/helpers.markdown @@ -0,0 +1,91 @@ +Helpers +==================== + +Helper Basics +------------------------ + +Helpers allow you to encapsulate rendering tasks as reusable functions. Helpers are modules, not classes, so their methods execute in the context in which they are called. They get included in a controller (typically the ApplicationController) using the helper function, like so + + Class ApplicationController < ActionController::Base + … + helper :menu + + def … + end + end + +In this way, methods in the menu helper are made available to any view or partial in your application. These methods can accept parameters, for example controller instance variables (eg; records or record collections gathered by you current controller), items from the view or partial’s locals[] hash or items from the params[] hash. You may wish to pass your controller instance variables and items from the params[] hash to the locals hash before rendering (See the section on partials). Helper methods can also accept an executable block of code. + +It is important to remember, though, that helpers are for rendering, and that they become available once a controller method has returned, while Rails is engaged in rendering the contents generated by a controller method. This means that helper methods are not available from within the methods of your controllers. + +Helpers can accomplish a variety of tasks, from formatting a complex tag for embedding content for a browser plugin (eg; Flash), to assembling a menu of options appropriate for the current context of your application, to generating sections of forms that get assembled on-the-fly. + +Helpers are organized around rendering tasks, so it is not necessary (nor necessarily desirable) to organize them around your application’s controllers or models. In fact, one of the benefits of helpers is that they are not connected via a rendering pipeline to specific controllers, like views and partials are. They can and should handle more generalized tasks. + +Here is a very simple, pseudo-example: + + module MenuHelper + def menu(records, menu_options={}) + item_options = menu_options.merge({<some stuff>}) + items = records.collect |record| do + menu_item(record, options) + end + content_tag(“ul”, items, options) + end + + def menu_item(record, item_options={})) + action = item_options[:action] + action ||= “show” + content_tag(“li”, link_to(record.title, :action => action, item_options) + end + end + + +This helper will require that records passed into it have certain fields (notably :title). The helper could be written to use this as a default, allowing the field to be overwritten by an element of item_options. + +Look at the Rails API for examples of helpers included in Rails, eg; [`ActionView::Helpers::ActiveRecordHelper`](http://api.rubyonrails.org/classes/ActionView/Helpers/ActiveRecordHelper.html). + +Passing Blocks to Helper Methods +------------------------ + +We mentioned before that blocks can be passed to helper methods. This allows for an interesting wrinkle: a block passed to a helper method can cause it to render a partial, which can then be wrapped by the helper method’s output. This can make your helper method much more reusable. It doesn’t need to know anything about the internals about what it is rendering, it just contextualizes it for the page. You can also use the helper to modify the locals hash for the partial, based on some configuration information unique to the current controller. You could implement a flexible themes system in this way. + + +Partials vs. Helpers? +------------------------ + +In general, the choice between using a partial vs. using a helper depends on the amount of flexibility you need. If the task is more about reacting to conditions than performing actual rendering, you may likely want a helper method. If you want to be able to call it from a variety of views, again, you may want to use a helper method. You can expect to extract helper methods out of code in views and partials during refactoring. + + +Tutorial -- Calling a Helper [UNFINISHED] +------------------------ + +1. Create a Rails application using `rails helper_test` +Notice the code: + + class ApplicationController < ActionController::Base + helper :all # include all helpers, all the time +For this tutorial, we'll keep this code, but you will likely want to exert more control over loading your helpers. + +2. Configure a database of your choice for the app. + +3. Inside of the `/app/helpers/` directory, create a new file called, `menu_helper.rb`. Write this in the file: + + module MenuHelpers + def menu(records, item_proc=nil) + items = records.collect{ |record| + menu_item(record, item_proc) + } + content_tag("ul", items) + end + + def menu_item(record, item_proc=nil) + item_url = item_proc.call(record) + item_url ||= { :action => :show } + content_tag("li", link_to(record.name, item_url)) + end + end + +4. Create a scaffold for some object in your app, using `./script/generate scaffold widgets`. +5. Create a database table for your widgets, with at least the fields `name` and `id`. Create a few widgets. +6. Call the menu command twice from `index.html.erb`, once using the default action, and once supplying a Proc to generate urls.
\ No newline at end of file diff --git a/railties/doc/guides/actionview/partials.markdown b/railties/doc/guides/actionview/partials.markdown new file mode 100644 index 0000000000..9f387fbafb --- /dev/null +++ b/railties/doc/guides/actionview/partials.markdown @@ -0,0 +1,91 @@ +A Guide to Using Partials +=============================== + +This guide elaborates on the use and function of partials in Ruby on Rails. As your Rails application grows, your view templates can start to contain a lot of duplicate view code. To manage and reduce this complexity, you can by abstract view template code into partials. Partials are reusable snippets of eRB template code stored in separate files with an underscore ('_') prefix. + +Partials can be located anywhere in the `app/views` directory. File extensions for partials work just like other template files, they bear an extension that denotes what kind of code they generate. For example, `_animal.html.erb` and `_animal.xml.erb` are valid filenames for partials. + +Partials can be inserted in eRB template code by calling the `render` method with the `:partial` option. For example: + + <%= render :partial => 'foo' %> + +This inserts the result of evaluating the template `_foo.html.erb` into the parent template file at this location. Note that `render` assumes that the partial will be in the same directory as the calling parent template and have the same file extension. Partials can be located anywhere within the `app/views` directory. To use a partial located in a different directory then it the parent, add a '/' before it: + + <%= render :partial => '/common/foo' %> + +Loads the partial file from the `app/views/common/_foo.html.erb` directory. + +Abstracting views into partials can be approached in a number of different ways, depending on the situation. Sometimes, the code that you are abstracting is a specialized view of an object or a collection of objects. Other times, you can look at partials as a reusable subroutine. We'll explore each of these approaches and when to use them as well as the syntax for calling them. + +Partials as a View Subroutine +----------------------------- + +Using the `:locals` option, you can pass a hash of values which will be treated as local variables within the partial template. + + <%= render :partial => "person", :locals => { :name => "david" } %> + +The variable `name` contains the value `"david"` within the `_person.html.erb` template. Passing variables in this way allows you to create modular, reusable template files. Note that if you want to make local variables that are optional in some use cases, you will have to set them to a sentinel value such as `nil` when they have not been passed. So, in the example above, if the `name` variable is optional in some use cases, you must set: + + <% name ||= nil -%> + +So that you can later check: + + <% if name -%> + <p>Hello, <%= name %>!</p> + <% end -%> + +Otherwise, the if statement will throw an error at runtime. + +Another thing to be aware of is that instance variables that are visible to the parent view template are visible to the partial. So you might be tempted to do this: + + <%= render :partial => "person" %> + +And then within the partial: + + <% if @name -%> + <p>Hello, <%= @name %>!</p> + <% end -%> + +The potential snag here is that if multiple templates start to rely on this partial, you will need to maintain an instance variable with the same name across all of these templates and controllers. This approach can quickly become brittle if overused. + +Partials as a View of an Object +-------------------------------- + +Another way to look at partials is to view them as mini-views of a particular object or instance variable. Use the `:object` option to pass an object assigns that object to an instance variable named after the partial itself. For example: + + # Renders the partial, making @new_person available through + # the local variable 'person' + render :partial => "person", :object => @new_person + +If the instance variable `name` in the parent template matches the name of the partial, you can use a shortcut: + + render :partial => "person" + +Now the value that was in `@person` in the parent template is accessible as `person` in the partial. + +Partials as a View of a Collection +----------------------------------- + +Often it is the case that you need to display not just a single object, but a collection of objects. Rather than having to constantly nest the same partial within the same iterator code, Rails provides a syntactical shortcut using the `:collection` option: + + # 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 + +This calls the `_person.html.erb` partial for each person in the `@winners` collection. This also creates a local variable within the partial called `partial_counter` which contains the index of the current value. So for example: + + <%= partial_counter %>) <%= person -%> + +Where `@winners` contains three people, produces the following output: + + 1) Bill + 2) Jeff + 3) Nick + +One last detail, you can place an arbitrary snippet of code in between the objects using the `:spacer_template` option. + + # 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" + diff --git a/railties/doc/guides/activerecord/basics.markdown b/railties/doc/guides/activerecord/basics.markdown new file mode 100644 index 0000000000..de882b45e6 --- /dev/null +++ b/railties/doc/guides/activerecord/basics.markdown @@ -0,0 +1,56 @@ +Active Record Basics +==================== + + + +The ActiveRecord Pattern +------------------------ + +Active Record (the library) conforms to the active record design pattern. The active record pattern is a design pattern often found in applications that use relational database. The name comes from by Martin Fowler's book *Patterns of Enterprise Application Architecture*, in which he describes an active record object as: + +> An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data. + +So, an object that follows the active record pattern encapsulates both data and behavior; in other words, they are responsible for saving and loading to the database and also for any domain logic that acts on the data. The data structure of the Active Record should exactly match that of the database: one field in the class for each column in the table. + +The Active Record class typically has methods that do the following: + +* Construct an instances of an Active Record class from a SQL result +* Construct a new class instance for insertion into the table +* Get and set column values +* Wrap business logic where appropriate +* Update existing objects and update the related rows in the database + +Mapping Your Database +--------------------- + +### Plural tables, singular classes ### + +### Schema lives in the database ### + +Creating Records +---------------- + +### Using save ### + +### Using create ### + +Retrieving Existing Rows +------------------------ + +### Using find ### + +### Using find_by_* ### + +Editing and Updating Rows +------------------------- + +### Editing an instance + +### Using update_all/update_attributes ### + +Deleting Data +------------- + +### Destroying a record ### + +### Deleting a record ###
\ No newline at end of file diff --git a/railties/doc/guides/creating_plugins/basics.markdown b/railties/doc/guides/creating_plugins/basics.markdown new file mode 100644 index 0000000000..a7b5d53478 --- /dev/null +++ b/railties/doc/guides/creating_plugins/basics.markdown @@ -0,0 +1,862 @@ +Creating Plugin Basics +==================== + +Pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. + +In this tutorial you will learn how to create a plugin that includes: + +Core Extensions - extending String: + + # Anywhere + "hello".squawk # => "squawk! hello! squawk!" + +An `acts_as_yaffle` method for Active Record models that adds a "squawk" method: + + class Hickwall < ActiveRecord::Base + acts_as_yaffle :yaffle_text_field => :last_sang_at + end + + Hickwall.new.squawk("Hello World") + +A view helper that will print out squawking info: + + squawk_info_for(@hickwall) + +A generator that creates a migration to add squawk columns to a model: + + script/generate yaffle hickwall + +A custom generator command: + + class YaffleGenerator < Rails::Generator::NamedBase + def manifest + m.yaffle_definition + end + end + end + +A custom route method: + + ActionController::Routing::Routes.draw do |map| + map.yaffles + end + +In addition you'll learn how to: + +* test your plugins +* work with init.rb, how to store model, views, controllers, helpers and even other plugins in your plugins +* create documentation for your plugin. +* write custom rake tasks in your plugin + +Create the basic app +--------------------- + +In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app: + +> The following instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. + + rails plugin_demo + cd plugin_demo + script/generate scaffold bird name:string + rake db:migrate + script/server + +Then navigate to [http://localhost:3000/birds](http://localhost:3000/birds). Make sure you have a functioning rails app before continuing. + +Create the plugin +----------------------- + +The built-in Rails plugin generator stubs out a new plugin. Pass the plugin name, either CamelCased or under_scored, as an argument. Pass --with-generator to add an example generator also. + +This creates a plugin in vendor/plugins including an init.rb and README as well as standard lib, task, and test directories. + +Examples: + + ./script/generate plugin BrowserFilters + ./script/generate plugin BrowserFilters --with-generator + +Later in the plugin we will create a generator, so go ahead and add the --with-generator option now: + + script/generate plugin yaffle --with-generator + +You should see the following output: + + create vendor/plugins/yaffle/lib + create vendor/plugins/yaffle/tasks + create vendor/plugins/yaffle/test + create vendor/plugins/yaffle/README + create vendor/plugins/yaffle/MIT-LICENSE + create vendor/plugins/yaffle/Rakefile + create vendor/plugins/yaffle/init.rb + create vendor/plugins/yaffle/install.rb + create vendor/plugins/yaffle/uninstall.rb + create vendor/plugins/yaffle/lib/yaffle.rb + create vendor/plugins/yaffle/tasks/yaffle_tasks.rake + create vendor/plugins/yaffle/test/core_ext_test.rb + create vendor/plugins/yaffle/generators + create vendor/plugins/yaffle/generators/yaffle + create vendor/plugins/yaffle/generators/yaffle/templates + create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb + create vendor/plugins/yaffle/generators/yaffle/USAGE + +For this plugin you won't need the file vendor/plugins/yaffle/lib/yaffle.rb so you can delete that. + + rm vendor/plugins/yaffle/lib/yaffle.rb + +> Editor's note: many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be `require "yaffle"` +> If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean + +Setup the plugin for testing +------------------------ + +Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial will not cover how to use fixtures in plugin tests. + +To setup your plugin to allow for easy testing you'll need to add 3 files: + +* A database.yml file with all of your connection strings +* A schema.rb file with your table definitions +* A test helper that sets up the database before your tests + +For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files: + + # File: vendor/plugins/yaffle/test/database.yml + + sqlite: + :adapter: sqlite + :dbfile: yaffle_plugin.sqlite.db + sqlite3: + :adapter: sqlite3 + :dbfile: yaffle_plugin.sqlite3.db + postgresql: + :adapter: postgresql + :username: postgres + :password: postgres + :database: yaffle_plugin_test + :min_messages: ERROR + mysql: + :adapter: mysql + :host: localhost + :username: rails + :password: + :database: yaffle_plugin_test + + # File: vendor/plugins/yaffle/test/test_helper.rb + + ActiveRecord::Schema.define(:version => 0) do + create_table :hickwalls, :force => true do |t| + t.string :name + t.string :last_squawk + t.datetime :last_squawked_at + end + create_table :wickwalls, :force => true do |t| + t.string :name + t.string :last_tweet + t.datetime :last_tweeted_at + end + end + + # File: vendor/plugins/yaffle/test/test_helper.rb + + ENV['RAILS_ENV'] = 'test' + ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' + + require 'test/unit' + require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) + + config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) + ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") + + db_adapter = ENV['DB'] + + # no db passed, try one of these fine config-free DBs before bombing. + db_adapter ||= + begin + require 'rubygems' + require 'sqlite' + 'sqlite' + rescue MissingSourceFile + begin + require 'sqlite3' + 'sqlite3' + rescue MissingSourceFile + end + end + + if db_adapter.nil? + raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." + end + + ActiveRecord::Base.establish_connection(config[db_adapter]) + + load(File.dirname(__FILE__) + "/schema.rb") + + require File.dirname(__FILE__) + '/../init.rb' + + class Hickwall < ActiveRecord::Base + acts_as_yaffle + end + + class Wickwall < ActiveRecord::Base + acts_as_yaffle :yaffle_text_field => :last_tweet, :yaffle_date_field => :last_tweeted_at + end + +Add a `to_squawk` method to String +----------------------- + +To update a core class you will have to: + +* Write tests for the desired functionality +* Create a file for the code you wish to use +* Require that file from your init.rb + +Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from init.rb. The file you are going to add for this tutorial is `lib/core_ext.rb` + +First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this: + + # File: vendor/plugins/yaffle/test/core_ext_test.rb + + require 'test/unit' + + class CoreExtTest < Test::Unit::TestCase + # Replace this with your real tests. + def test_this_plugin + flunk + end + end + +Start off by removing the default test, and adding a require statement for your test helper. + + # File: vendor/plugins/yaffle/test/core_ext_test.rb + + require 'test/unit' + require File.dirname(__FILE__) + '/test_helper.rb' + + class CoreExtTest < Test::Unit::TestCase + end + +Navigate to your plugin directory and run `rake test` + + cd vendor/plugins/yaffle + rake test + +Your test should fail with `no such file to load -- ./test/../lib/core_ext.rb (LoadError)` because we haven't created any file yet. Create the file `lib/core_ext.rb` and re-run the tests. You should see a different error message: + + 1.) Failure ... + No tests were specified + +Great - now you are ready to start development. The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word "squawk! ". The test will look something like this: + + # File: vendor/plugins/yaffle/init.rb + + class CoreExtTest < Test::Unit::TestCase + def test_string_should_respond_to_squawk + assert_equal true, "".respond_to?(:to_squawk) + end + def test_string_prepend_empty_strings_with_the_word_squawk + assert_equal "squawk!", "".to_squawk + end + def test_string_prepend_non_empty_strings_with_the_word_squawk + assert_equal "squawk! Hello World", "Hello World".to_squawk + end + end + + # File: vendor/plugins/yaffle/init.rb + + require "core_ext" + + # File: vendor/plugins/yaffle/lib/core_ext.rb + + String.class_eval do + def to_squawk + "squawk! #{self}".strip + end + end + +When monkey-patching existing classes it's often better to use `class_eval` instead of opening the class directly. + +To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking: + + script/console + >> "Hello World".to_squawk + => "squawk! Hello World" + +If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class. + +Add an `acts_as_yaffle` method to ActiveRecord +----------------------- + +A common pattern in plugins is to add a method called `acts_as_something` to models. In this case, you want to write a method called `acts_as_yaffle` that adds a squawk method to your models. + +To keep things clean, create a new test file called `acts_as_yaffle_test.rb` in your plugin's test directory and require your test helper. + + # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb + + require File.dirname(__FILE__) + '/test_helper.rb' + + class Hickwall < ActiveRecord::Base + acts_as_yaffle + end + + class ActsAsYaffleTest < Test::Unit::TestCase + end + + # File: vendor/plugins/lib/acts_as_yaffle.rb + + module Yaffle + end + +One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so: + + module Yaffle + def self.included(base) + base.send :extend, ClassMethods + end + + module ClassMethods + # any method placed here will apply to classes, like Hickwall + def acts_as_something + send :include, InstanceMethods + end + end + + module InstanceMethods + # any method placed here will apply to instaces, like @hickwall + end + end + +With structure you can easily separate the methods that will be used for the class (like `Hickwall.some_method`) and the instance (like `@hickwell.some_method`). + +Let's add class method named `acts_as_yaffle` - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail. + +Back in your `acts_as_yaffle` file, update ClassMethods like so: + + module ClassMethods + def acts_as_yaffle(options = {}) + send :include, InstanceMethods + end + end + +Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this: + + # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb + + require File.dirname(__FILE__) + '/test_helper.rb' + + class ActsAsYaffleTest < Test::Unit::TestCase + def test_a_hickwalls_yaffle_text_field_should_be_last_squawk + assert_equal "last_squawk", Hickwall.yaffle_text_field + end + def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at + assert_equal "last_squawked_at", Hickwall.yaffle_date_field + end + def test_a_wickwalls_yaffle_text_field_should_be_last_tweet + assert_equal "last_tweet", Wickwall.yaffle_text_field + end + def test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at + assert_equal "last_tweeted_at", Wickwall.yaffle_date_field + end + end + +To make these tests pass, you could modify your `acts_as_yaffle` file like so: + + # File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb + + module Yaffle + def self.included(base) + base.send :extend, ClassMethods + end + + module ClassMethods + def acts_as_yaffle(options = {}) + cattr_accessor :yaffle_text_field, :yaffle_date_field + self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s + self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s + send :include, InstanceMethods + end + end + + module InstanceMethods + end + end + +Now you can add tests for the instance methods, and the instance method itself: + + # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb + + require File.dirname(__FILE__) + '/test_helper.rb' + + class ActsAsYaffleTest < Test::Unit::TestCase + + def test_a_hickwalls_yaffle_text_field_should_be_last_squawk + assert_equal "last_squawk", Hickwall.yaffle_text_field + end + def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at + assert_equal "last_squawked_at", Hickwall.yaffle_date_field + end + + def test_a_wickwalls_yaffle_text_field_should_be_last_squawk + assert_equal "last_tweet", Wickwall.yaffle_text_field + end + def test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at + assert_equal "last_tweeted_at", Wickwall.yaffle_date_field + end + + def test_hickwalls_squawk_should_populate_last_squawk + hickwall = Hickwall.new + hickwall.squawk("Hello World") + assert_equal "squawk! Hello World", hickwall.last_squawk + end + def test_hickwalls_squawk_should_populate_last_squawked_at + hickwall = Hickwall.new + hickwall.squawk("Hello World") + assert_equal Date.today, hickwall.last_squawked_at + end + + def test_wickwalls_squawk_should_populate_last_tweet + wickwall = Wickwall.new + wickwall.squawk("Hello World") + assert_equal "squawk! Hello World", wickwall.last_tweet + end + def test_wickwalls_squawk_should_populate_last_tweeted_at + wickwall = Wickwall.new + wickwall.squawk("Hello World") + assert_equal Date.today, wickwall.last_tweeted_at + end + end + + # File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb + + module Yaffle + def self.included(base) + base.send :extend, ClassMethods + end + + module ClassMethods + def acts_as_yaffle(options = {}) + cattr_accessor :yaffle_text_field, :yaffle_date_field + self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s + self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s + send :include, InstanceMethods + end + end + + module InstanceMethods + def squawk(string) + write_attribute(self.class.yaffle_text_field, string.to_squawk) + write_attribute(self.class.yaffle_date_field, Date.today) + end + end + end + +Note the use of write_attribute to write to the field in model. + +Create a view helper +----------------------- + +Creating a view helper is a 3-step process: + +* Add an appropriately named file to the lib directory +* Require the file and hooks in init.rb +* Write the tests + +First, create the test to define the functionality you want: + + # File: vendor/plugins/yaffle/test/view_helpers_test.rb + + require File.dirname(__FILE__) + '/test_helper.rb' + include YaffleViewHelper + + class ViewHelpersTest < Test::Unit::TestCase + def test_squawk_info_for_should_return_the_text_and_date + time = Time.now + hickwall = Hickwall.new + hickwall.last_squawk = "Hello World" + hickwall.last_squawked_at = time + assert_equal "Hello World, #{time.to_s}", squawk_info_for(hickwall) + end + end + +Then add the following statements to init.rb: + + # File: vendor/plugins/yaffle/init.rb + + require "view_helpers" + ActionView::Base.send :include, YaffleViewHelper + +Then add the view helpers file and + + # File: vendor/plugins/yaffle/lib/view_helpers.rb + + module YaffleViewHelper + def squawk_info_for(yaffle) + returning "" do |result| + result << yaffle.read_attribute(yaffle.class.yaffle_text_field) + result << ", " + result << yaffle.read_attribute(yaffle.class.yaffle_date_field).to_s + end + end + end + +You can also test this in script/console by using the "helper" method: + + script/console + >> helper.squawk_info_for(@some_yaffle_instance) + +Create a migration generator +----------------------- + +When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in your plugin. + +We'll be relying on the built-in rails generate template for this tutorial. Going into the details of generators is beyond the scope of this tutorial. + +Type: + + script/generate + +You should see the line: + + Plugins (vendor/plugins): yaffle + +When you run `script/generate yaffle` you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this: + + Description: + Creates a migration that adds yaffle squawk fields to the given model + + Example: + ./script/generate yaffle hickwall + + This will create: + db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall + +Now you can add code to your generator: + + # File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb + + class YaffleGenerator < Rails::Generator::NamedBase + def manifest + record do |m| + m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns, + :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}" + } + end + end + + private + def custom_file_name + custom_name = class_name.underscore.downcase + custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names + end + + def yaffle_local_assigns + returning(assigns = {}) do + assigns[:migration_action] = "add" + assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}" + assigns[:table_name] = custom_file_name + assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")] + assigns[:attributes] << Rails::Generator::GeneratedAttribute.new("last_squawked_at", "datetime") + end + end + end + +Note that you need to be aware of whether or not table names are pluralized. + +This does a few things: + +* Reuses the built in rails migration_template method +* Reuses the built-in rails migration template + +When you run the generator like + + script/generate yaffle bird + +You will see a new file: + + # File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb + + class AddYaffleFieldsToBirds < ActiveRecord::Migration + def self.up + add_column :birds, :last_squawk, :string + add_column :birds, :last_squawked_at, :datetime + end + + def self.down + remove_column :birds, :last_squawked_at + remove_column :birds, :last_squawk + end + end + +Add a custom generator command +------------------------ + +You may have noticed above that you can used one of the built-in rails migration commands `m.migration_template`. You can create your own commands for these, using the following steps: + +1. Add the require and hook statements to init.rb +2. Create the commands - creating 3 sets, Create, Destroy, List +3. Add the method to your generator + +Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example: + + # File: vendor/plugins/yaffle/init.rb + + require "commands" + Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create + Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy + Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List + + # File: vendor/plugins/yaffle/lib/commands.rb + + require 'rails_generator' + require 'rails_generator/commands' + + module Yaffle #:nodoc: + module Generator #:nodoc: + module Commands #:nodoc: + module Create + def yaffle_definition + file("definition.txt", "definition.txt") + end + end + + module Destroy + def yaffle_definition + file("definition.txt", "definition.txt") + end + end + + module List + def yaffle_definition + file("definition.txt", "definition.txt") + end + end + end + end + end + + # File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt + + Yaffle is a bird + + # File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb + + class YaffleGenerator < Rails::Generator::NamedBase + def manifest + m.yaffle_definition + end + end + end + +This example just uses the built-in "file" method, but you could do anything that ruby allows. + +Add a Custom Route +------------------------ + +Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in [http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2](http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2) + + # File: vendor/plugins/yaffle/test/routing_test.rb + + require "#{File.dirname(__FILE__)}/test_helper" + + class RoutingTest < Test::Unit::TestCase + + def setup + ActionController::Routing::Routes.draw do |map| + map.yaffles + end + end + + def test_yaffles_route + assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index" + end + + private + + # yes, I know about assert_recognizes, but it has proven problematic to + # use in these tests, since it uses RouteSet#recognize (which actually + # tries to instantiate the controller) and because it uses an awkward + # parameter order. + def assert_recognition(method, path, options) + result = ActionController::Routing::Routes.recognize_path(path, :method => method) + assert_equal options, result + end + end + + # File: vendor/plugins/yaffle/init.rb + + require "routing" + ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions + + # File: vendor/plugins/yaffle/lib/routing.rb + + module Yaffle #:nodoc: + module Routing #:nodoc: + module MapperExtensions + def yaffles + @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"}) + end + end + end + end + + # File: config/routes.rb + + ActionController::Routing::Routes.draw do |map| + ... + map.yaffles + end + +You can also see if your routes work by running `rake routes` from your app directory. + +Generate RDoc Documentation +----------------------- + +Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. + +The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are: + +* Your name +* How to install +* How to add the functionality to the app (several examples of common use cases) +* Warning, gotchas or tips that might help save users time + +Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. + +Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users. + +Once your comments are good to go, navigate to your plugin directory and run + + rake rdoc + +Work with init.rb +------------------------ + +The plugin initializer script init.rb is invoked via `eval` (not require) so it has slightly different behavior. + +If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. There are 2 ways around this: + +The first way is to explicitly define the top-level module space for all modules and classes, like ::Hash + + # File: vendor/plugins/yaffle/init.rb + + class ::Hash + def is_a_special_hash? + true + end + end + +OR you can use `module_eval` or `class_eval` + + # File: vendor/plugins/yaffle/init.rb + + Hash.class_eval do + def is_a_special_hash? + true + end + end + +Store models, views, helpers, and controllers in your plugins +------------------------ + +You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path: + + # File: vendor/plugins/yaffle/init.rb + + %w{ models controllers helpers }.each do |dir| + path = File.join(directory, 'lib', dir) + $LOAD_PATH << path + Dependencies.load_paths << path + Dependencies.load_once_paths.delete(path) + end + +Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. + +Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server. + +Write custom rake tasks in your plugin +------------------------- + +When you created the plugin with the built-in rails generator, it generated a rake file for you in `vendor/plugins/yaffle/tasks/yaffle.rake`. Any rake task you add here will be available to the app. + +Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so: + + # File: vendor/plugins/yaffle/tasks/yaffle.rake + + namespace :yaffle do + desc "Prints out the word 'Yaffle'" + task :squawk => :environment do + puts "squawk!" + end + end + +When you run `rake -T` from your plugin you will see + + yaffle:squawk "Prints out..." + +You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up. + +Store plugins in alternate locations +------------------------- + +You can store plugins wherever you want - you just have to add those plugins to the plugins path in environment.rb + +Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now. + +You can even store plugins inside of other plugins for complete plugin madness! + + config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins") + +Create your own Plugin Loaders and Plugin Locators +------------------------ + +If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial. + +Use Custom Plugin Generators +------------------------ + +If you are an RSpec fan, you can install the `rspec_plugin_generator`, which will generate the spec folder and database for you. + +[http://github.com/pat-maddox/rspec-plugin-generator/tree/master](http://github.com/pat-maddox/rspec-plugin-generator/tree/master) + +References +------------------------ + +* [http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i](http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i) +* [http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii](http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii) +* [http://github.com/technoweenie/attachment_fu/tree/master](http://github.com/technoweenie/attachment_fu/tree/master) +* [http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html](http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html) + +Appendices +------------------------ + +The final plugin should have a directory structure that looks something like this: + + |-- MIT-LICENSE + |-- README + |-- Rakefile + |-- generators + | `-- yaffle + | |-- USAGE + | |-- templates + | | `-- definition.txt + | `-- yaffle_generator.rb + |-- init.rb + |-- install.rb + |-- lib + | |-- acts_as_yaffle.rb + | |-- commands.rb + | |-- core_ext.rb + | |-- routing.rb + | `-- view_helpers.rb + |-- tasks + | `-- yaffle_tasks.rake + |-- test + | |-- acts_as_yaffle_test.rb + | |-- core_ext_test.rb + | |-- database.yml + | |-- debug.log + | |-- routing_test.rb + | |-- schema.rb + | |-- test_helper.rb + | `-- view_helpers_test.rb + |-- uninstall.rb + `-- yaffle_plugin.sqlite3.db + diff --git a/railties/environments/environment.rb b/railties/environments/environment.rb index c33b80da4f..a85ade371b 100644 --- a/railties/environments/environment.rb +++ b/railties/environments/environment.rb @@ -21,7 +21,7 @@ Rails::Initializer.run do |config| # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. - # They can then be installed with rake gem:install on new installations. + # They can then be installed with "rake gems:install" on new installations. # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "aws-s3", :lib => "aws/s3" @@ -38,9 +38,9 @@ Rails::Initializer.run do |config| # (by default production uses :info, the others :debug) # config.log_level = :debug - # Make Time.zone default to the specified zone, and make ActiveRecord store time values + # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. - # Run `rake -D time` for a list of tasks for finding time zone names. Uncomment to use default local time. + # Run "rake -D time" for a list of tasks for finding time zone names. Uncomment to use default local time. config.time_zone = 'UTC' # Your secret key for verifying cookie session data integrity. @@ -54,7 +54,7 @@ Rails::Initializer.run do |config| # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information - # (create the session table with 'rake db:sessions:create') + # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. @@ -64,4 +64,4 @@ Rails::Initializer.run do |config| # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector -end
\ No newline at end of file +end diff --git a/railties/environments/test.rb b/railties/environments/test.rb index 58850a7974..1e709e1d19 100644 --- a/railties/environments/test.rb +++ b/railties/environments/test.rb @@ -16,7 +16,7 @@ config.action_controller.perform_caching = false # Disable request forgery protection in test environment config.action_controller.allow_forgery_protection = false -# Tell ActionMailer not to deliver emails to the real world. +# Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test diff --git a/railties/lib/commands/console.rb b/railties/lib/commands/console.rb index edffe4f1e6..2b9d92f647 100644 --- a/railties/lib/commands/console.rb +++ b/railties/lib/commands/console.rb @@ -24,9 +24,9 @@ ENV['RAILS_ENV'] = case ARGV.first end if options[:sandbox] - puts "Loading #{ENV['RAILS_ENV']} environment in sandbox (Rails #{Rails::VERSION::STRING})" + puts "Loading #{ENV['RAILS_ENV']} environment in sandbox (Rails #{Rails.version})" puts "Any modifications you make will be rolled back on exit" else - puts "Loading #{ENV['RAILS_ENV']} environment (Rails #{Rails::VERSION::STRING})" + puts "Loading #{ENV['RAILS_ENV']} environment (Rails #{Rails.version})" end exec "#{options[:irb]} #{libs} --simple-prompt" diff --git a/railties/lib/commands/dbconsole.rb b/railties/lib/commands/dbconsole.rb index 3e5010c688..17acb7b68f 100644 --- a/railties/lib/commands/dbconsole.rb +++ b/railties/lib/commands/dbconsole.rb @@ -2,8 +2,13 @@ require 'erb' require 'yaml' require 'optparse' +include_password = false + OptionParser.new do |opt| - opt.banner = "Usage: dbconsole [environment]" + opt.banner = "Usage: dbconsole [options] [environment]" + opt.on("-p", "--include-password", "Automatically provide the database from database.yml") do |v| + include_password = true + end opt.parse!(ARGV) abort opt.to_s unless (0..1).include?(ARGV.size) end @@ -31,19 +36,23 @@ when "mysql" 'port' => '--port', 'socket' => '--socket', 'username' => '--user', - 'password' => '--password', 'encoding' => '--default-character-set' }.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact + if config['password'] && include_password + args << "--password=#{config['password']}" + end + args << config['database'] exec(find_cmd('mysql5', 'mysql'), *args) when "postgresql" + ENV['PGUSER'] = config["username"] if config["username"] ENV['PGHOST'] = config["host"] if config["host"] ENV['PGPORT'] = config["port"].to_s if config["port"] - ENV['PGPASSWORD'] = config["password"].to_s if config["password"] - exec(find_cmd('psql'), '-U', config["username"], config["database"]) + ENV['PGPASSWORD'] = config["password"].to_s if config["password"] && include_password + exec(find_cmd('psql'), config["database"]) when "sqlite" exec(find_cmd('sqlite'), config["database"]) diff --git a/railties/lib/commands/plugin.rb b/railties/lib/commands/plugin.rb index d12d002c4e..105819ce90 100644 --- a/railties/lib/commands/plugin.rb +++ b/railties/lib/commands/plugin.rb @@ -163,7 +163,7 @@ class Plugin end def git_url? - @uri =~ /^git:\/\// || @url =~ /\.git$/ + @uri =~ /^git:\/\// || @uri =~ /\.git$/ end def installed? diff --git a/railties/lib/commands/process/spawner.rb b/railties/lib/commands/process/spawner.rb index fd09daa55b..dc0008698a 100644 --- a/railties/lib/commands/process/spawner.rb +++ b/railties/lib/commands/process/spawner.rb @@ -66,9 +66,9 @@ class MongrelSpawner < Spawner "-l #{OPTIONS[:rails_root]}/log/mongrel.log" # Add prefix functionality to spawner's call to mongrel_rails - # Digging through monrel's project subversion server, the earliest + # Digging through mongrel's project subversion server, the earliest # Tag that has prefix implemented in the bin/mongrel_rails file - # is 0.3.15 which also happens to be the earilest tag listed. + # is 0.3.15 which also happens to be the earliest tag listed. # References: http://mongrel.rubyforge.org/svn/tags if Mongrel::Const::MONGREL_VERSION.to_f >=0.3 && !OPTIONS[:prefix].nil? cmd = cmd + " --prefix #{OPTIONS[:prefix]}" diff --git a/railties/lib/commands/servers/lighttpd.rb b/railties/lib/commands/servers/lighttpd.rb index 07d4f9d0bf..c9d13e86f3 100644 --- a/railties/lib/commands/servers/lighttpd.rb +++ b/railties/lib/commands/servers/lighttpd.rb @@ -62,7 +62,7 @@ config = IO.read(config_file) default_port, default_ip = 3000, '0.0.0.0' port = config.scan(/^\s*server.port\s*=\s*(\d+)/).first rescue default_port ip = config.scan(/^\s*server.bind\s*=\s*"([^"]+)"/).first rescue default_ip -puts "=> Rails application starting on http://#{ip || default_ip}:#{port || default_port}" +puts "=> Rails #{Rails.version} application starting on http://#{ip || default_ip}:#{port || default_port}" tail_thread = nil diff --git a/railties/lib/commands/servers/mongrel.rb b/railties/lib/commands/servers/mongrel.rb index f59265e698..7bb110f63a 100644 --- a/railties/lib/commands/servers/mongrel.rb +++ b/railties/lib/commands/servers/mongrel.rb @@ -32,7 +32,7 @@ ARGV.clone.options do |opts| opts.parse! end -puts "=> Rails application starting on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}" +puts "=> Rails #{Rails.version} application starting on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}" parameters = [ "start", diff --git a/railties/lib/commands/servers/webrick.rb b/railties/lib/commands/servers/webrick.rb index b950376150..18c8897cc8 100644 --- a/railties/lib/commands/servers/webrick.rb +++ b/railties/lib/commands/servers/webrick.rb @@ -61,6 +61,6 @@ require 'webrick_server' OPTIONS['working_directory'] = File.expand_path(RAILS_ROOT) -puts "=> Rails application started on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}" +puts "=> Rails #{Rails.version} application started on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}" puts "=> Ctrl-C to shutdown server; call with --help for options" if OPTIONS[:server_type] == WEBrick::SimpleServer DispatchServlet.dispatch(OPTIONS) diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index dfd43042be..ec065e6f3c 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -8,6 +8,7 @@ require 'rails/version' require 'rails/plugin/locator' require 'rails/plugin/loader' require 'rails/gem_dependency' +require 'rails/rack' RAILS_ENV = (ENV['RAILS_ENV'] || 'development').dup unless defined?(RAILS_ENV) @@ -43,6 +44,10 @@ module Rails RAILS_CACHE end + def version + VERSION::STRING + end + def public_path @@public_path ||= self.root ? File.join(self.root, "public") : "public" end @@ -82,7 +87,7 @@ module Rails # Rails::Initializer.run(:set_load_path) # # This is useful if you only want the load path initialized, without - # incuring the overhead of completely loading the entire environment. + # incurring the overhead of completely loading the entire environment. def self.run(command = :process, configuration = Configuration.new) yield configuration if block_given? initializer = new configuration @@ -136,7 +141,8 @@ module Rails # pick up any gems that plugins depend on add_gem_load_paths load_gems - + check_gem_dependencies + load_application_initializers # the framework is now fully initialized @@ -149,6 +155,7 @@ module Rails initialize_routing # Observers are loaded after plugins in case Observers or observed models are modified by plugins. + load_observers end @@ -160,12 +167,12 @@ module Rails end # If Rails is vendored and RubyGems is available, install stub GemSpecs - # for Rails, ActiveSupport, ActiveRecord, ActionPack, ActionMailer, and - # ActiveResource. This allows Gem plugins to depend on Rails even when + # for Rails, Active Support, Active Record, Action Pack, Action Mailer, and + # Active Resource. This allows Gem plugins to depend on Rails even when # the Gem version of Rails shouldn't be loaded. def install_gem_spec_stubs unless Rails.respond_to?(:vendor_rails?) - abort "Your config/boot.rb is outdated: Run 'rake rails:update'." + abort %{Your config/boot.rb is outdated: Run "rake rails:update".} end if Rails.vendor_rails? @@ -210,8 +217,8 @@ module Rails end # Requires all frameworks specified by the Configuration#frameworks - # list. By default, all frameworks (ActiveRecord, ActiveSupport, - # ActionPack, ActionMailer, and ActiveResource) are loaded. + # list. By default, all frameworks (Active Record, Active Support, + # Action Pack, Action Mailer, and Active Resource) are loaded. def require_frameworks configuration.frameworks.each { |framework| require(framework.to_s) } rescue LoadError => e @@ -237,7 +244,24 @@ module Rails end def load_gems - @configuration.gems.each &:load + @configuration.gems.each(&:load) + end + + def check_gem_dependencies + unloaded_gems = @configuration.gems.reject { |g| g.loaded? } + if unloaded_gems.size > 0 + @gems_dependencies_loaded = false + # don't print if the gems rake tasks are being run + unless $rails_gem_installer + puts %{These gems that this application depends on are missing:} + unloaded_gems.each do |gem| + puts " - #{gem.name}" + end + puts %{Run "rake gems:install" to install them.} + end + else + @gems_dependencies_loaded = true + end end # Loads all plugins in <tt>config.plugin_paths</tt>. <tt>plugin_paths</tt> @@ -283,12 +307,8 @@ module Rails end def load_observers - if configuration.frameworks.include?(:active_record) - if @configuration.gems.any? { |g| !g.loaded? } - puts "Unable to instantiate observers, some gems that this application depends on are missing. Run 'rake gems:install'" - else - ActiveRecord::Base.instantiate_observers - end + if @gems_dependencies_loaded && configuration.frameworks.include?(:active_record) + ActiveRecord::Base.instantiate_observers end end @@ -326,7 +346,7 @@ module Rails end end - # If the +RAILS_DEFAULT_LOGGER+ constant is already set, this initialization + # If the RAILS_DEFAULT_LOGGER constant is already set, this initialization # routine does nothing. If the constant is not set, and Configuration#logger # is not +nil+, this also does nothing. Otherwise, a new logger instance # is created at Configuration#log_path, with a default log level of @@ -359,10 +379,10 @@ module Rails silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger } end - # Sets the logger for ActiveRecord, ActionController, and ActionMailer + # Sets the logger for Active Record, Action Controller, and Action Mailer # (but only for those frameworks that are to be loaded). If the framework's # logger is already set, it is not changed, otherwise it is set to use - # +RAILS_DEFAULT_LOGGER+. + # RAILS_DEFAULT_LOGGER. def initialize_framework_logging for framework in ([ :active_record, :action_controller, :action_mailer ] & configuration.frameworks) framework.to_s.camelize.constantize.const_get("Base").logger ||= RAILS_DEFAULT_LOGGER @@ -380,7 +400,7 @@ module Rails ActionController::Base.view_paths = [configuration.view_path] if configuration.frameworks.include?(:action_controller) && ActionController::Base.view_paths.empty? end - # If ActionController is not one of the loaded frameworks (Configuration#frameworks) + # If Action Controller is not one of the loaded frameworks (Configuration#frameworks) # this does nothing. Otherwise, it loads the routing definitions and sets up # loading module used to lazily load controllers (Configuration#controller_paths). def initialize_routing @@ -409,13 +429,13 @@ module Rails end end - # Sets the default value for Time.zone, and turns on ActiveRecord time_zone_aware_attributes. + # Sets the default value for Time.zone, and turns on ActiveRecord::Base#time_zone_aware_attributes. # If assigned value cannot be matched to a TimeZone, an exception will be raised. def initialize_time_zone if configuration.time_zone zone_default = Time.send!(:get_zone, configuration.time_zone) unless zone_default - raise "Value assigned to config.time_zone not recognized. Run `rake -D time` for a list of tasks for finding appropriate time zone names." + raise %{Value assigned to config.time_zone not recognized. Run "rake -D time" for a list of tasks for finding appropriate time zone names.} end Time.zone_default = zone_default if configuration.frameworks.include?(:active_record) @@ -443,14 +463,18 @@ module Rails # Fires the user-supplied after_initialize block (Configuration#after_initialize) def after_initialize - configuration.after_initialize_blocks.each do |block| - block.call + if @gems_dependencies_loaded + configuration.after_initialize_blocks.each do |block| + block.call + end end end def load_application_initializers - Dir["#{configuration.root_path}/config/initializers/**/*.rb"].sort.each do |initializer| - load(initializer) + if @gems_dependencies_loaded + Dir["#{configuration.root_path}/config/initializers/**/*.rb"].sort.each do |initializer| + load(initializer) + end end end @@ -475,22 +499,22 @@ module Rails # The application's base directory. attr_reader :root_path - # A stub for setting options on ActionController::Base + # A stub for setting options on ActionController::Base. attr_accessor :action_controller - # A stub for setting options on ActionMailer::Base + # A stub for setting options on ActionMailer::Base. attr_accessor :action_mailer - # A stub for setting options on ActionView::Base + # A stub for setting options on ActionView::Base. attr_accessor :action_view - # A stub for setting options on ActiveRecord::Base + # A stub for setting options on ActiveRecord::Base. attr_accessor :active_record - # A stub for setting options on ActiveRecord::Base + # A stub for setting options on ActiveRecord::Base. attr_accessor :active_resource - # A stub for setting options on ActiveSupport + # A stub for setting options on ActiveSupport. attr_accessor :active_support # Whether or not classes should be cached (set to false if you want @@ -618,9 +642,9 @@ module Rails end alias_method :breakpoint_server=, :breakpoint_server - # Sets the default time_zone. Setting this will enable time_zone - # awareness for ActiveRecord models and set the ActiveRecord default - # timezone to :utc. + # Sets the default +time_zone+. Setting this will enable +time_zone+ + # awareness for Active Record models and set the Active Record default + # timezone to <tt>:utc</tt>. attr_accessor :time_zone # Create a new Configuration instance, initialized with the default @@ -685,7 +709,7 @@ module Rails end # Return the currently selected environment. By default, it returns the - # value of the +RAILS_ENV+ constant. + # value of the RAILS_ENV constant. def environment ::RAILS_ENV end @@ -843,7 +867,7 @@ end # Needs to be duplicated from Active Support since its needed before Active # Support is available. Here both Options and Hash are namespaced to prevent -# conflicts with other implementations AND with the classes residing in ActiveSupport. +# conflicts with other implementations AND with the classes residing in Active Support. class Rails::OrderedOptions < Array #:nodoc: def []=(key, value) key = key.to_sym diff --git a/railties/lib/rails/gem_dependency.rb b/railties/lib/rails/gem_dependency.rb index 2034841cd2..9f088a18dd 100644 --- a/railties/lib/rails/gem_dependency.rb +++ b/railties/lib/rails/gem_dependency.rb @@ -31,12 +31,13 @@ module Rails args << @requirement.to_s if @requirement gem *args else - $LOAD_PATH << File.join(unpacked_paths.first, 'lib') + $LOAD_PATH.unshift File.join(unpacked_paths.first, 'lib') + ext = File.join(unpacked_paths.first, 'ext') + $LOAD_PATH.unshift(ext) if File.exist?(ext) @frozen = true end @load_paths_added = true rescue Gem::LoadError - puts $!.to_s end def dependencies @@ -73,7 +74,9 @@ module Rails end def install - Gem::GemRunner.new.run(install_command) + cmd = "#{gem_command} #{install_command.join(' ')}" + puts cmd + puts %x(#{cmd}) end def unpack_to(directory) @@ -100,10 +103,14 @@ private ################################################################### def specification @spec ||= Gem.source_index.search(Gem::Dependency.new(@name, @requirement)).sort_by { |s| s.version }.last end + + def gem_command + RUBY_PLATFORM =~ /win32/ ? 'gem.bat' : 'gem' + end def install_command cmd = %w(install) << @name - cmd << "--version" << "#{@requirement.to_s}" if @requirement + cmd << "--version" << %("#{@requirement.to_s}") if @requirement cmd << "--source" << @source if @source cmd end diff --git a/railties/lib/rails/mongrel_server/commands.rb b/railties/lib/rails/mongrel_server/commands.rb index 3786a56fde..0a92f418ad 100644 --- a/railties/lib/rails/mongrel_server/commands.rb +++ b/railties/lib/rails/mongrel_server/commands.rb @@ -119,7 +119,7 @@ module Rails config = RailsConfigurator.new(settings) do defaults[:log] = $stdout if defaults[:environment] == 'development' - Mongrel.log("=> Rails application starting on http://#{defaults[:host]}:#{defaults[:port]}") + Mongrel.log("=> Rails #{Rails.version} application starting on http://#{defaults[:host]}:#{defaults[:port]}") unless defaults[:daemon] Mongrel.log("=> Call with -d to detach") diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb index 04f7e37a20..256f4b0132 100644 --- a/railties/lib/rails/plugin.rb +++ b/railties/lib/rails/plugin.rb @@ -98,23 +98,18 @@ module Rails end end - # This Plugin subclass represents a Gem plugin. It behaves exactly like a - # "traditional" Rails plugin, but doesn't expose any additional load paths, - # since RubyGems has already taken care of things. + # This Plugin subclass represents a Gem plugin. Although RubyGems has already + # taken care of $LOAD_PATHs, it exposes its load_paths to add them + # to Dependencies.load_paths. class GemPlugin < Plugin - # Initialize this plugin from a Gem::Specification. def initialize(spec) - super(File.join(spec.full_gem_path, "rails")) + super(File.join(spec.full_gem_path)) @name = spec.name end - def valid? - true - end - - def load_paths - [] + def init_path + File.join(directory, 'rails', 'init.rb') end end end
\ No newline at end of file diff --git a/railties/lib/rails/rack.rb b/railties/lib/rails/rack.rb new file mode 100644 index 0000000000..abcd0741bf --- /dev/null +++ b/railties/lib/rails/rack.rb @@ -0,0 +1,5 @@ +module Rails + module Rack + autoload :Static, "rails/rack/static" + end +end diff --git a/railties/lib/rails/rack/static.rb b/railties/lib/rails/rack/static.rb new file mode 100644 index 0000000000..45eb0e5921 --- /dev/null +++ b/railties/lib/rails/rack/static.rb @@ -0,0 +1,35 @@ +module Rails + module Rack + class Static + FILE_METHODS = %w(GET HEAD).freeze + + def initialize(app) + @app = app + @file_server = ::Rack::File.new(File.join(RAILS_ROOT, "public")) + end + + def call(env) + path = env['PATH_INFO'].chomp('/') + method = env['REQUEST_METHOD'] + cached_path = (path.empty? ? 'index' : path) + ::ActionController::Base.page_cache_extension + + if FILE_METHODS.include?(method) + if file_exist?(path) + return @file_server.call(env) + elsif file_exist?(cached_path) + env['PATH_INFO'] = cached_path + return @file_server.call(env) + end + end + + @app.call(env) + end + + private + def file_exist?(path) + full_path = File.join(@file_server.root, ::Rack::Utils.unescape(path)) + File.file?(full_path) && File.readable?(full_path) + end + end + end +end diff --git a/railties/lib/rails/version.rb b/railties/lib/rails/version.rb index fea63beea9..48d24da52e 100644 --- a/railties/lib/rails/version.rb +++ b/railties/lib/rails/version.rb @@ -1,8 +1,8 @@ module Rails module VERSION #:nodoc: MAJOR = 2 - MINOR = 0 - TINY = 991 + MINOR = 1 + TINY = 0 STRING = [MAJOR, MINOR, TINY].join('.') end diff --git a/railties/lib/rails_generator/base.rb b/railties/lib/rails_generator/base.rb index 1ebcff9062..b5cfe79867 100644 --- a/railties/lib/rails_generator/base.rb +++ b/railties/lib/rails_generator/base.rb @@ -36,7 +36,7 @@ module Rails # view.html.erb # # The directory name (+controller+) matches the name of the generator file - # (controller_generator.rb) and class (+ControllerGenerator+). The files + # (controller_generator.rb) and class (ControllerGenerator). The files # that will be copied or used as templates are stored in the +templates+ # directory. # diff --git a/railties/lib/rails_generator/commands.rb b/railties/lib/rails_generator/commands.rb index 03b7d354a6..c0f8d05dde 100644 --- a/railties/lib/rails_generator/commands.rb +++ b/railties/lib/rails_generator/commands.rb @@ -155,7 +155,7 @@ HELP # such as the rest of the user's app. def class_collisions(*class_names) - # Initialize some check varibles + # Initialize some check variables last_class = Object current_class = nil name = nil @@ -380,12 +380,14 @@ HELP # Thanks to Florian Gross (flgr). def raise_class_collision(class_name) message = <<end_message - The name '#{class_name}' is reserved by Ruby on Rails. + The name '#{class_name}' is either already used in your application or reserved by Ruby on Rails. Please choose an alternative and run this generator again. end_message if suggest = find_synonyms(class_name) - message << "\n Suggestions: \n\n" - message << suggest.join("\n") + if suggest.any? + message << "\n Suggestions: \n\n" + message << suggest.join("\n") + end end raise UsageError, message end diff --git a/railties/lib/rails_generator/generators/components/migration/USAGE b/railties/lib/rails_generator/generators/components/migration/USAGE index 3e914a5d7b..b83c657963 100644 --- a/railties/lib/rails_generator/generators/components/migration/USAGE +++ b/railties/lib/rails_generator/generators/components/migration/USAGE @@ -2,7 +2,7 @@ Description: Stubs out a new database migration. Pass the migration name, either CamelCased or under_scored, and an optional list of attribute pairs as arguments. - A migration class is generated in db/migrate prefixed by the latest migration number. + A migration class is generated in db/migrate prefixed by a timestamp of the current date and time. You can name your migration in either of these formats to generate add/remove column lines from supplied attributes: AddColumnsToTable or RemoveColumnsFromTable @@ -10,12 +10,12 @@ Description: Example: `./script/generate migration AddSslFlag` - With 4 existing migrations, this creates the AddSslFlag migration in - db/migrate/005_add_ssl_flag.rb + If the current date is May 14, 2008 and the current time 09:09:12, this creates the AddSslFlag migration + db/migrate/20080514090912_add_ssl_flag.rb `./script/generate migration AddTitleBodyToPost title:string body:text published:boolean` - This will create the AddTitleBodyToPost in db/migrate/005_add_title_body_to_post.rb with + This will create the AddTitleBodyToPost in db/migrate/20080514090912_add_title_body_to_post.rb with this in the Up migration: add_column :posts, :title, :string diff --git a/railties/lib/rails_generator/generators/components/scaffold/USAGE b/railties/lib/rails_generator/generators/components/scaffold/USAGE index a0e4baea08..810aea16f1 100644 --- a/railties/lib/rails_generator/generators/components/scaffold/USAGE +++ b/railties/lib/rails_generator/generators/components/scaffold/USAGE @@ -1,10 +1,11 @@ Description: Scaffolds an entire resource, from model and migration to controller and views, along with a full test suite. The resource is ready to use as a - starting point for your restful, resource-oriented application. + starting point for your RESTful, resource-oriented application. - Pass the name of the model, either CamelCased or under_scored, as the first - argument, and an optional list of attribute pairs. + Pass the name of the model (in singular form), either CamelCased or + under_scored, as the first argument, and an optional list of attribute + pairs. Attribute pairs are column_name:sql_type arguments specifying the model's attributes. Timestamps are added by default, so you don't have to @@ -13,13 +14,16 @@ Description: You don't have to think up every attribute up front, but it helps to sketch out a few so you can start working with the resource immediately. - For example, `scaffold post title:string body:text published:boolean` + For example, 'scaffold post title:string body:text published:boolean' gives you a model with those three attributes, a controller that handles the create/show/update/destroy, forms to create and edit your posts, and an index that lists them all, as well as a map.resources :posts declaration in config/routes.rb. + If you want to remove all the generated files, run + 'script/destroy scaffold ModelName'. + Examples: - `./script/generate scaffold post` # no attributes, view will be anemic + `./script/generate scaffold post` `./script/generate scaffold post title:string body:text published:boolean` `./script/generate scaffold purchase order_id:integer amount:decimal` diff --git a/railties/lib/rails_generator/scripts.rb b/railties/lib/rails_generator/scripts.rb index f857f68de4..9b1a99838a 100644 --- a/railties/lib/rails_generator/scripts.rb +++ b/railties/lib/rails_generator/scripts.rb @@ -45,7 +45,7 @@ module Rails usage = "\nInstalled Generators\n" Rails::Generator::Base.sources.inject([]) do |mem, source| # Using an association list instead of a hash to preserve order, - # for esthetic reasons more than anything else. + # for aesthetic reasons more than anything else. label = source.label.to_s.capitalize pair = mem.assoc(label) mem << (pair = [label, []]) if pair.nil? diff --git a/railties/lib/rails_generator/scripts/destroy.rb b/railties/lib/rails_generator/scripts/destroy.rb index 4fcbc3e0df..a7c2a14751 100644 --- a/railties/lib/rails_generator/scripts/destroy.rb +++ b/railties/lib/rails_generator/scripts/destroy.rb @@ -3,7 +3,7 @@ require File.dirname(__FILE__) + '/../scripts' module Rails::Generator::Scripts class Destroy < Base mandatory_options :command => :destroy - + protected def usage_message usage = "\nInstalled Generators\n" @@ -15,14 +15,13 @@ module Rails::Generator::Scripts usage << <<end_blurb -This script will destroy all files created by the corresponding -script/generate command. For instance, script/destroy migration CreatePost -will delete the appropriate ###_create_post.rb file in db/migrate, while -script/destroy scaffold Post will delete the posts controller and +script/generate command. For instance, 'script/destroy migration CreatePost' +will delete the appropriate XXX_create_post.rb migration file in db/migrate, +while 'script/destroy scaffold Post' will delete the posts controller and views, post model and migration, all associated tests, and the map.resources :posts line in config/routes.rb. - -For instructions on finding new generators, run script/generate + +For instructions on finding new generators, run script/generate. end_blurb return usage end diff --git a/railties/lib/rails_generator/secret_key_generator.rb b/railties/lib/rails_generator/secret_key_generator.rb index 64fbbb90f8..5ae492312e 100644 --- a/railties/lib/rails_generator/secret_key_generator.rb +++ b/railties/lib/rails_generator/secret_key_generator.rb @@ -23,7 +23,7 @@ module Rails # Generate a random secret key by using the Win32 API. Raises LoadError # if the current platform cannot make use of the Win32 API. Raises - # SystemCallError if some other error occured. + # SystemCallError if some other error occurred. def generate_secret_with_win32_api # Following code is based on David Garamond's GUID library for Ruby. require 'Win32API' diff --git a/railties/lib/tasks/databases.rake b/railties/lib/tasks/databases.rake index f40f8463f7..8077d0a401 100644 --- a/railties/lib/tasks/databases.rake +++ b/railties/lib/tasks/databases.rake @@ -173,7 +173,7 @@ namespace :db do pending_migrations.each do |pending_migration| puts ' %4d %s' % [pending_migration.version, pending_migration.name] end - abort "Run `rake db:migrate` to update your database then try again." + abort %{Run "rake db:migrate" to update your database then try again.} end end end diff --git a/railties/lib/tasks/gems.rake b/railties/lib/tasks/gems.rake index c18fea2d60..0321e60e0f 100644 --- a/railties/lib/tasks/gems.rake +++ b/railties/lib/tasks/gems.rake @@ -1,5 +1,5 @@ desc "List the gems that this rails application depends on" -task :gems => :environment do +task :gems => 'gems:base' do Rails.configuration.gems.each do |gem| code = gem.loaded? ? (gem.frozen? ? "F" : "I") : " " puts "[#{code}] #{gem.name} #{gem.requirement.to_s}" @@ -10,8 +10,14 @@ task :gems => :environment do end namespace :gems do + task :base do + $rails_gem_installer = true + Rake::Task[:environment].invoke + end + desc "Build any native extensions for unpacked gems" task :build do + $rails_gem_installer = true require 'rails/gem_builder' Dir[File.join(RAILS_ROOT, 'vendor', 'gems', '*')].each do |gem_dir| spec_file = File.join(gem_dir, '.specification') @@ -24,14 +30,14 @@ namespace :gems do end desc "Installs all required gems for this application." - task :install => :environment do + task :install => :base do require 'rubygems' require 'rubygems/gem_runner' Rails.configuration.gems.each { |gem| gem.install unless gem.loaded? } end desc "Unpacks the specified gem into vendor/gems." - task :unpack => :environment do + task :unpack => :base do require 'rubygems' require 'rubygems/gem_runner' Rails.configuration.gems.each do |gem| diff --git a/railties/test/fixtures/about_yml_plugins/bad_about_yml/about.yml b/railties/test/fixtures/about_yml_plugins/bad_about_yml/about.yml index 79d5721a53..fe80872a16 100644 --- a/railties/test/fixtures/about_yml_plugins/bad_about_yml/about.yml +++ b/railties/test/fixtures/about_yml_plugins/bad_about_yml/about.yml @@ -1 +1 @@ -# an empty yaml file - any content in here seems to get parsed as a string
\ No newline at end of file +# an empty YAML file - any content in here seems to get parsed as a string
\ No newline at end of file diff --git a/railties/test/generators/generator_test_helper.rb b/railties/test/generators/generator_test_helper.rb index c99df6e2d3..80d5b145be 100644 --- a/railties/test/generators/generator_test_helper.rb +++ b/railties/test/generators/generator_test_helper.rb @@ -86,19 +86,19 @@ class GeneratorTestCase < Test::Unit::TestCase # don't complain, test/unit end - # Instantiates the Generator + # Instantiates the Generator. def build_generator(name, params) Rails::Generator::Base.instance(name, params) end - # Runs the create command (like the command line does) + # Runs the +create+ command (like the command line does). def run_generator(name, params) silence_generator do build_generator(name, params).command(:create).invoke! end end - # Silences the logger temporarily and returns the output as a String + # Silences the logger temporarily and returns the output as a String. def silence_generator logger_original = Rails::Generator::Base.logger myout = StringIO.new @@ -108,7 +108,7 @@ class GeneratorTestCase < Test::Unit::TestCase myout.string end - # asserts that the given controller was generated. + # Asserts that the given controller was generated. # It takes a name or symbol without the <tt>_controller</tt> part and an optional super class. # The contents of the class source file is passed to a block. def assert_generated_controller_for(name, parent = "ApplicationController") @@ -117,44 +117,44 @@ class GeneratorTestCase < Test::Unit::TestCase end end - # asserts that the given model was generated. + # Asserts that the given model was generated. # It takes a name or symbol and an optional super class. - # the contents of the class source file is passed to a block. + # The contents of the class source file is passed to a block. def assert_generated_model_for(name, parent = "ActiveRecord::Base") assert_generated_class "app/models/#{name.to_s.underscore}", parent do |body| yield body if block_given? end end - # asserts that the given helper was generated. - # It takes a name or symbol without the <tt>_helper</tt> part - # the contents of the module source file is passed to a block. + # Asserts that the given helper was generated. + # It takes a name or symbol without the <tt>_helper</tt> part. + # The contents of the module source file is passed to a block. def assert_generated_helper_for(name) assert_generated_module "app/helpers/#{name.to_s.underscore}_helper" do |body| yield body if block_given? end end - # asserts that the given functional test was generated. + # Asserts that the given functional test was generated. # It takes a name or symbol without the <tt>_controller_test</tt> part and an optional super class. - # the contents of the class source file is passed to a block. + # The contents of the class source file is passed to a block. def assert_generated_functional_test_for(name, parent = "ActionController::TestCase") assert_generated_class "test/functional/#{name.to_s.underscore}_controller_test",parent do |body| yield body if block_given? end end - # asserts that the given unit test was generated. + # Asserts that the given unit test was generated. # It takes a name or symbol without the <tt>_test</tt> part and an optional super class. - # the contents of the class source file is passed to a block. + # The contents of the class source file is passed to a block. def assert_generated_unit_test_for(name, parent = "ActiveSupport::TestCase") assert_generated_class "test/unit/#{name.to_s.underscore}_test", parent do |body| yield body if block_given? end end - # asserts that the given file was generated. - # the contents of the file is passed to a block. + # Asserts that the given file was generated. + # The contents of the file is passed to a block. def assert_generated_file(path) assert_file_exists(path) File.open("#{RAILS_ROOT}/#{path}") do |f| @@ -168,9 +168,9 @@ class GeneratorTestCase < Test::Unit::TestCase "The file '#{RAILS_ROOT}/#{path}' should exist" end - # asserts that the given class source file was generated. + # Asserts that the given class source file was generated. # It takes a path without the <tt>.rb</tt> part and an optional super class. - # the contents of the class source file is passed to a block. + # The contents of the class source file is passed to a block. def assert_generated_class(path, parent = nil) # FIXME: Sucky way to detect namespaced classes if path.split('/').size > 3 @@ -187,9 +187,9 @@ class GeneratorTestCase < Test::Unit::TestCase end end - # asserts that the given module source file was generated. + # Asserts that the given module source file was generated. # It takes a path without the <tt>.rb</tt> part. - # the contents of the class source file is passed to a block. + # The contents of the class source file is passed to a block. def assert_generated_module(path) # FIXME: Sucky way to detect namespaced modules if path.split('/').size > 3 @@ -206,18 +206,18 @@ class GeneratorTestCase < Test::Unit::TestCase end end - # asserts that the given css stylesheet file was generated. + # Asserts that the given CSS stylesheet file was generated. # It takes a path without the <tt>.css</tt> part. - # the contents of the stylesheet source file is passed to a block. + # The contents of the stylesheet source file is passed to a block. def assert_generated_stylesheet(path) assert_generated_file("public/stylesheets/#{path}.css") do |body| yield body if block_given? end end - # asserts that the given yaml file was generated. + # Asserts that the given YAML file was generated. # It takes a path without the <tt>.yml</tt> part. - # the parsed yaml tree is passed to a block. + # The parsed YAML tree is passed to a block. def assert_generated_yaml(path) assert_generated_file("#{path}.yml") do |body| yaml = YAML.load(body) @@ -226,18 +226,18 @@ class GeneratorTestCase < Test::Unit::TestCase end end - # asserts that the given fixtures yaml file was generated. + # Asserts that the given fixtures YAML file was generated. # It takes a fixture name without the <tt>.yml</tt> part. - # the parsed yaml tree is passed to a block. + # The parsed YAML tree is passed to a block. def assert_generated_fixtures_for(name) assert_generated_yaml "test/fixtures/#{name.to_s.underscore}" do |yaml| yield yaml if block_given? end end - # asserts that the given views were generated. + # Asserts that the given views were generated. # It takes a controller name and a list of views (including extensions). - # The body of each view is passed to a block + # The body of each view is passed to a block. def assert_generated_views_for(name, *actions) actions.each do |action| assert_generated_file("app/views/#{name.to_s.underscore}/#{action}") do |body| @@ -262,7 +262,7 @@ class GeneratorTestCase < Test::Unit::TestCase assert !File.exist?(migration_file), "should not create migration #{migration_file}" end - # asserts that the given resource was added to the routes. + # Asserts that the given resource was added to the routes. def assert_added_route_for(name) assert_generated_file("config/routes.rb") do |body| assert_match /map.resources :#{name.to_s.underscore}/, body, @@ -270,7 +270,7 @@ class GeneratorTestCase < Test::Unit::TestCase end end - # asserts that the given methods are defined in the body. + # Asserts that the given methods are defined in the body. # This does assume standard rails code conventions with regards to the source code. # The body of each individual method is passed to a block. def assert_has_method(body, *methods) @@ -280,7 +280,7 @@ class GeneratorTestCase < Test::Unit::TestCase end end - # asserts that the given column is defined in the migration + # Asserts that the given column is defined in the migration. def assert_generated_column(body, name, type) assert_match /t\.#{type.to_s} :#{name.to_s}/, body, "should have column #{name.to_s} defined" end diff --git a/release.rb b/release.rb index 94d2219525..2e1e8610b1 100755 --- a/release.rb +++ b/release.rb @@ -4,7 +4,7 @@ VERSION = ARGV.first PACKAGES = %w(activesupport activerecord actionpack actionmailer activeresource) # Checkout source -`rm -rf release && svn export http://dev.rubyonrails.org/svn/rails/trunk release` +# `rm -rf release && svn export http://dev.rubyonrails.org/svn/rails/trunk release` # Create Rails packages `cd release/railties && rake template=jamis package` @@ -19,7 +19,4 @@ end # Upload rails tgz/zip `rubyforge add_release rails rails 'REL #{VERSION}' release/rails-#{VERSION}.tgz` -`rubyforge add_release rails rails 'REL #{VERSION}' release/rails-#{VERSION}.zip` - -# Create SVN tag -puts "Remember to create SVN tag" +`rubyforge add_release rails rails 'REL #{VERSION}' release/rails-#{VERSION}.zip`
\ No newline at end of file |