Compare commits

..

693 Commits

Author SHA1 Message Date
David Heinemeier Hansson
186e3c71f9 Prep for relese 2010-11-15 13:23:02 -06:00
David Heinemeier Hansson
31b6a6a78b Prep for 3.0.2 release 2010-11-15 13:20:27 -06:00
James Miller
029c8ff46c Add HTTP Verb Constraints (:via) to routing guide 2010-11-15 19:59:52 +01:00
Jaime Iniesta
65fdd284e1 Getting Started guide: remove calls to f.error_messages as it has been removed from Rails 2010-11-15 19:59:37 +01:00
Rajinder Yadav
1540bf5816 removed unnecessary indentation 2010-11-15 19:59:15 +01:00
Rajinder Yadav
4369f132a6 added note with example for using flash in redirection 2010-11-15 19:59:06 +01:00
Rajinder Yadav
c41d9813be corrected sample code to clear @_current_user class variable also 2010-11-15 19:58:57 +01:00
Rajinder Yadav
7487767c31 the partial option is not required for simple partial rendering 2010-11-15 19:58:47 +01:00
Ryan Bigg
28f9d60f77 Document the constraints method 2010-11-15 19:58:37 +01:00
Paco Guzman
dbc0023d6d colorize_logging is a Rails General Configuration option not a specific option of ActiveRecord 2010-11-15 19:58:21 +01:00
Ryan Bigg
ccc8d9ce54 Add documentation for :path_names option on resources 2010-11-15 19:58:11 +01:00
Ryan Bigg
43b0fd7918 See the scope method for documentation for namespace's shallow_path option 2010-11-15 19:58:03 +01:00
Ryan Bigg
86534a35f9 Add documentation for the mount method in ActionDispatch's Mapper 2010-11-15 19:57:54 +01:00
Frederick Ros
13f10ac4ea Fixed the name of the 'generator option' 2010-11-15 19:57:45 +01:00
José Valim
4c3edae2bd Add a note to TextHelpers making explicit their default behavior of not escaping but sanitizing. 2010-11-15 19:57:09 +01:00
Rajinder Yadav
5d9219b1b5 removed indentation, for code style consistency and readibility 2010-11-15 19:57:00 +01:00
dmathieu
70e4403e46 Use Rails.logger, not ActiveRecord::Base.logger
Because everybody is not using ActiveRecord. And the logger is not specific to it.
2010-11-15 19:56:51 +01:00
Rajinder Yadav
41e5e4a7bd removed etc. not require 2010-11-15 19:56:42 +01:00
Rajinder Yadav
bad920f423 corrected to Rails 3 syntax for declaring resources 2010-11-15 19:56:13 +01:00
Francesc Esplugas
45c3abadfa Fixes ActionMailer example error 2010-11-15 19:56:04 +01:00
Ryan Bigg
205b24064e Fix indentation for :as option documentation on the namespace method 2010-11-15 19:55:56 +01:00
Ryan Bigg
4ffd31e195 Document the :shallow_path option for scope 2010-11-15 19:55:41 +01:00
Ryan Bigg
020f74b152 Indent final comment for :path option 2010-11-15 19:55:34 +01:00
Ryan Bigg
7a1f22ff33 Indent code example for :as option 2010-11-15 19:55:24 +01:00
Ryan Bigg
06402b03ea Document the :as option for the scope method 2010-11-15 19:55:15 +01:00
Ryan Bigg
0db841223a Space between module option documentation and path documentation 2010-11-15 19:55:04 +01:00
Ryan Bigg
34015296e0 Fix indentation on comment for :path option 2010-11-15 19:54:54 +01:00
Ryan Bigg
45525713f9 Document the :as option for the namespace method 2010-11-15 19:54:45 +01:00
Ryan Bigg
422831872e Document the :module option for namespace 2010-11-15 19:54:29 +01:00
Ryan Bigg
e777b914c8 Document the :path option for namespace 2010-11-15 19:54:05 +01:00
Ryan Bigg
1287fddff6 Begin to document the namespace method for AD's Mapper 2010-11-15 19:53:54 +01:00
Ryan Bigg
467d5844eb Document the controller method for AD's Mapper 2010-11-15 19:53:40 +01:00
Ryan Bigg
afc16f6dce Document the defaults method 2010-11-15 19:53:28 +01:00
Ryan Bigg
3551e254d2 Document the :module and :path options for the scope method. 2010-11-15 19:53:15 +01:00
Ryan Bigg
9078041ee8 Separate comments and examples with "Examples" header. 2010-11-15 19:53:02 +01:00
Ryan Bigg
9ccaf47012 Add further documentation + examples for the get, post, put and delete methods in ActionDispatch::Routing::Mapper::HttpHelpers 2010-11-15 19:50:40 +01:00
Mikel Lindsaar
10fc93b89e Revert "Bump up mail dependency to take advantage of relaxed i18n version requirement"
Locking to ~> 2.2.9.1 means locking to < 2.2.10, not intended behaviour.

This reverts commit e7de5dd11e.
2010-11-16 00:24:13 +11:00
Mikel Lindsaar
fc95196df0 Bump up mail dependency to take advantage of relaxed i18n version requirement 2010-11-16 00:08:04 +11:00
Santiago Pastorino
01ed7005e1 Remove unused var 2010-11-14 15:38:05 -02:00
Jason Cheow
f8b7c74f9b Fix bug where size of through association is not correct after adding a has_many association (occurs only before main object has been reloaded).
[#5968 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-11-14 15:37:58 -02:00
Carlos Antonio da Silva
4266e3e91a Remove lost commented debugger call
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-11-13 13:22:52 -02:00
Carlos Antonio da Silva
bdec56cbe7 Fix rendering partial with layout, when the partial contains another render layout with block call
In such situations, the first layout was not being applied. This fixes it by
storing the block variable before rendering the partial, so the variable
is not overrided, thus the layout is applied (bear in mind the renderer is
shared among all render calls).

This commit also adds some more tests to render partials with layouts and
nested render layout calls.

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-11-13 13:06:04 -02:00
Santiago Pastorino
b870193345 Make collection and collection_from_object methods return an array
This transforms for instance scoped objects into arrays and avoid
unneeded queries

[#5958 state:committed]
2010-11-13 04:06:53 -02:00
Santiago Pastorino
ed62b96e23 Use ! instead of not 2010-11-11 15:32:17 -02:00
Nathan B
d54ab371df Fixed bug in active_record/nested_attributes where an empty string id caused an ActiveRecord::RecordNotFound error. Found by [Ben Tillman]
[#5638 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-11-11 15:31:28 -02:00
Santiago Pastorino
30ae44a326 Bump Arel up to 2.0.2 2010-11-11 15:03:44 -02:00
Jeff Kreeftmeijer
be63e03fba The model generator shouldn't throw warnings when using mass nouns [#5363 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-11-11 17:24:37 +01:00
Neeraj Singh
86f66e9097 fields_for should treat ActiveRecord::Relation as an array
[#5795 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-11-11 17:18:12 +01:00
Marcelo Giorgi
0de95dfb2c Make after_filter halt when before_filter renders or redirects [#5648 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-11-11 17:07:31 +01:00
Carlos Antonio da Silva
d5fd83f4c7 Fix render partial with layout and no block
When using a render :partial with :layout call, without giving a block,
if the given :partial had another render :partial call, the layout was
not being rendered. This commit fixes this context by storing variables
before rendering the partial, so they are not overrided in any successive
call to render partials down the path. All ActionPack tests are ok.

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-11-11 16:24:01 +01:00
Carlos Antonio da Silva
3e86e4b34e Fix issue with rendering partials and then yielding inside a render layout call
The given block was never being executed when another render :partial call
existed before the yield call, due to the block being overriden.

This commit also adds some more tests to render with :layout option.

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-11-11 16:23:55 +01:00
Carlos Antonio da Silva
55a8bd666d Bring ActionPack tests back to life
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-11-11 16:23:32 +01:00
Aditya Sanghi
1b66a646db patching to ensure separator is printed with order [#5816 state:resolved]
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-11-11 12:36:25 -02:00
Santiago Pastorino
2e4e1ed916 Duck typing here 2010-11-11 01:34:35 -02:00
Alvaro Bautista
387a1a6365 Fix ActiveSupport::TimeWithZone#localtime method with DateTime
[#5344 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-11-11 01:34:26 -02:00
Xavier Noria
7611a0925c registers number_to_currency's :negative_format in the CHANGELOG of AP 2010-11-09 20:55:14 +01:00
Santiago Pastorino
bf875b273d Double negation of an already boolean value produces the same result 2010-11-09 17:28:06 -02:00
Santiago Pastorino
b0f6349a07 Don't check if persisted is defined just initialize it properly 2010-11-09 17:28:06 -02:00
Santiago Pastorino
844b9a5018 Execute less operations 2010-11-09 17:28:05 -02:00
David Chelimsky
f1c13b0dd7 use persisted? instead of new_record? wherever possible
- persisted? is the API defined in ActiveModel
- makes it easier for extension libraries to conform to ActiveModel
  APIs
  without concern for whether the extended object is specifically
  ActiveRecord

[#5927 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-11-09 17:26:11 -02:00
Andrew White
4b33bd9888 Strip regexp anchors from rake routes output [#5934 state:resolved] 2010-11-09 05:20:15 +00:00
Santiago Pastorino
c7fac8c6ea Test cache.key_file_path with separators ht. Jim Wilson [#5611] 2010-11-07 20:03:41 -02:00
Denis Odorcic
ad2c0bdb9b Fix FileStore cache incorrectly regenerating its key from a pathname when a regexp is used in expire_fragment
[#5850 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-11-07 20:03:29 -02:00
Michael Koziarski
f676beb647 Make safe_append= live on AV::OutputBuffer not AS::SafeBuffer 2010-11-08 10:06:16 +13:00
Michael Koziarski
ea1fde6ae7 Added support for Erubis <%== tag
<%== x %> is syntactic sugar for <%= raw(x) %>

Signed-off-by: Michael Koziarski <michael@koziarski.com>
[#5918 status:committed]

Conflicts:

	actionpack/test/controller/new_base/render_template_test.rb
2010-11-08 10:03:33 +13:00
Chris Eppstein
d4b7fa5fb6 Correctly handle the case of an API response that returns a hash by treating a single hash argument as the resource instead of as options.
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-11-07 18:19:52 -02:00
sblackstone
7ab940c7ad Association Proxy should not undefine the default respond_to_missing 2010-11-04 15:05:03 -07:00
José Valim
e6abfc46bf Update to latest thor with https bug fix. 2010-11-04 11:09:30 -02:00
Xavier Noria
a56142cc6b made a pass to the docs of :negative_format 2010-11-03 06:21:05 +01:00
Don Wilson
b91371763e Added :negative_format option to number_to_currency function [#5894 state:resolved]
Signed-off-by: Andrew White <andyw@pixeltrix.co.uk>
2010-11-02 23:06:08 +00:00
Santiago Pastorino
a682986d0d Test that capture doesn't escape twice 2010-11-02 20:18:26 -02:00
Santiago Pastorino
2c8bff3513 Call as ERB::Util.html_escape since is not the module is not included here 2010-11-02 20:18:22 -02:00
Jeff Kreeftmeijer
5cb1dad228 Make sure capture's output gets html_escaped [#5545 state:resolved]
Also remove a duplicate test_link_to_unless assertion and add .html_safe
to the remaining one.

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-11-02 20:17:37 -02:00
Andrew White
6c8982fa13 Add additional HTTP request methods from the following RFCs:
* Hypertext Transfer Protocol -- HTTP/1.1
  http://www.ietf.org/rfc/rfc2616.txt)

* HTTP Extensions for Distributed Authoring -- WEBDAV
  http://www.ietf.org/rfc/rfc2518.txt

* Versioning Extensions to WebDAV
  http://www.ietf.org/rfc/rfc3253.txt

* Ordered Collections Protocol (WebDAV)
  http://www.ietf.org/rfc/rfc3648.txt

* Web Distributed Authoring and Versioning (WebDAV) Access Control Protocol
  http://www.ietf.org/rfc/rfc3744.txt

* Web Distributed Authoring and Versioning (WebDAV) SEARCH
  http://www.ietf.org/rfc/rfc5323.txt

* PATCH Method for HTTP
  http://www.ietf.org/rfc/rfc5789.txt

[#2809 state:resolved] [#5895 state:resolved]
2010-11-02 11:06:54 +00:00
Jon Leighton
918bf847d8 Fix bug with 0bb85ed9ff which missed out a fixtures declaration in cascaded_eager_loading_test.rb 2010-10-31 20:02:32 -02:00
Ugis Ozols
3ca1bc381f Changed environment.rb to application.rb 2010-10-30 23:31:05 +02:00
Ugis Ozols
eca3791d0f Reworded sentence using text from rails source code. 2010-10-30 23:31:05 +02:00
Rob Zolkos
b5efa8fc67 added tip about ruby-debug needing a different gem if using 1.9 [#190 state:resolved] 2010-10-30 23:31:05 +02:00
Ugis Ozols
c95f155731 Changed environment.rb to application.rb 2010-10-30 23:31:05 +02:00
Aaron Patterson
29b3af539b only returning where values for the corresponding relation, also filtering where value hash based on table name [#5234 state:resolved] [#5184 state:resolved] 2010-10-30 13:34:23 -07:00
Aaron Patterson
3bc12d3ee6 adding tests for #5234 and #5184. Tests were from Akira Matsuda. Thanks Akira! 2010-10-30 13:32:09 -07:00
Aaron Patterson
ae7a354110 no need to merge where values if no new where values have been added 2010-10-30 13:31:59 -07:00
Aaron Patterson
4d2a53d9ea reduce duplicate where removal to one loop 2010-10-30 13:30:33 -07:00
Aaron Patterson
4772abc7d8 swap out some n^2 for some n 2010-10-30 13:30:26 -07:00
Aaron Patterson
4fd9c20fb3 dup rather than create so many arrays 2010-10-30 13:30:19 -07:00
Ernie Miller
c681df48e3 Fix issues when including the same association multiple times and mixing joins/includes together. 2010-10-30 11:19:26 -07:00
Andrew White
ddf73603c1 Backport of documentation fixes:
cfc8c7ab54
  dfebdb1b03

[#5520] [#5537] [#5581]
2010-10-29 07:23:17 +01:00
Aaron Patterson
f73a3e6838 reducing the number of parameters to select() 2010-10-27 04:15:17 -07:00
Andrew White
0d23c2160d Ensure that Rails.env is defined first 2010-10-27 10:31:29 +01:00
Andrew White
63b0d0e9d2 Allow generated url helpers to be overriden [#5243 state:resolved] 2010-10-26 14:33:34 +01:00
Mikel Lindsaar
5f6a02f4ba Updating mail dependency to 2.2.9 2010-10-26 18:51:06 +11:00
Andrew White
909c860a42 Don't write out secure cookies unless the request is secure 2010-10-25 16:47:17 +01:00
Xavier Noria
e9d593bc18 ensures that no browser shows a vertical scrollbar in the code blocks of guides, thanks to Marcelino Llano for a hint to fix this 2010-10-24 19:28:57 +02:00
Xavier Noria
ec23bc15ba configure a uniform font-family for code in guides 2010-10-24 16:23:02 +02:00
Xavier Noria
7ca9dcd434 use a gray a little darker in code blocks, for better contrast with the gray background 2010-10-24 16:22:52 +02:00
Xavier Noria
1a618e98e0 removes the toolbar from guides code blocks 2010-10-24 16:22:42 +02:00
Xavier Noria
5a4a2323b0 switches guides code syntax highlighting to the better SyntaxHighlighter, I did my best with the theme, I swear 2010-10-24 00:38:14 +02:00
Santiago Pastorino
c53f301b48 Revert "Bump bundler up to 1.0.3"
This reverts commit 0891f49075.
2010-10-21 15:12:07 -02:00
Jan
f294540154 default scope merge where clauses [#5488 state:resolved] 2010-10-20 08:54:02 -07:00
Aaron Patterson
4480521df9 bumping mysql2 requirement 2010-10-19 17:53:41 -07:00
Santiago Pastorino
adea1467f6 compact is unneeded here 2010-10-18 12:03:00 -02:00
Santiago Pastorino
14b33a4eb7 Merge 3.0.1 CHANGELOGs and prepare 3.0.2.pre 2010-10-18 12:00:46 -02:00
Andrew White
141cba8f1d Reset assert_template instance variables between requests [#5832 state:resolved] 2010-10-18 10:05:24 +01:00
Santiago Pastorino
0891f49075 Bump bundler up to 1.0.3 2010-10-16 18:24:18 -02:00
Michael Koziarski
37431bb34e Revert 0c0b0aa0f2 which introduced a security vulnerability.
This addresses  CVE-2010-3933

Conflicts:

	activerecord/lib/active_record/nested_attributes.rb
2010-10-15 10:25:49 +13:00
Santiago Pastorino
f7faa86690 Leave env :AREL only for testing purposes 2010-10-14 18:56:11 -02:00
Santiago Pastorino
10d3ab79dc Don't use Arel from git anymore 2010-10-14 18:25:34 -02:00
Aaron Patterson
85ffbfef9c stop using deprecated arel API 2010-10-12 14:32:48 -07:00
Xavier Noria
869118aaae getting started guide: deletes orphan <% end %>, reported by Michael L. Miller 2010-10-12 23:07:43 +02:00
Szymon Nowak
1556e0874d Return a valid empty JSON on successful PUT and DELETE requests. [#5199 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-10-12 00:56:44 +02:00
Aaron Patterson
0a8eaff3d1 we should always cast the value based on the column 2010-10-11 13:36:38 -07:00
Marcelo Giorgi
dba7de0da0 Honor distinct option when used with count operation after group clause [#5721 state:resolved] 2010-10-11 09:47:26 -07:00
Santiago Pastorino
0c56a27926 data-disable-with in button_to helper
[#4993 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-10-11 13:35:35 -02:00
Santiago Pastorino
448a187606 CHANGELOG of reorder deprecation 2010-10-11 11:48:54 -02:00
Santiago Pastorino
0b46f72226 Deprecate reorder in favor of except(:order).order(...) 2010-10-11 11:43:29 -02:00
Santiago Pastorino
d0d1acab58 Add except as AR public API 2010-10-11 11:39:46 -02:00
Santiago Pastorino
3021297e89 Revert "Make InstanceTagMethods#value_before_type_cast raise if the model don't respond to attr_before_type_cast or attr method"
And    "Makes form_helper use overriden model accessors"

This reverts commit 3ba8e31005 and fb0bd8c109.
2010-10-10 21:14:10 -02:00
wycats
b4954e81c1 Cherry pick didn't get this deletion 2010-10-10 16:13:35 -07:00
wycats
83d5180bec Always pull in version for frameworks (standardize autoload / require / none) 2010-10-10 16:12:57 -07:00
Barry Sears
4245dcd521 Make ActiveSupport load own version.
[#5739 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-10-10 19:48:11 -02:00
Wincent Colaiuta
3a6acb6162 Fix misleading advice to add 'memcache' to Gemfile
[#5539 state:committed]

Commit 57144388f removed the hard-coded dependency on the memcache-client
gem, and added this warning advising people to install it if needed. The
problem is, however, that if people follow the advice literally and install
the 'memcache' gem, they will wind up with a completely different thing,
which is not API compatible with the memcache-client gem and which Rails
can't work with.

So, be explicit and tell users to install the 'memcache-client' gem.

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-10-10 14:30:43 -02:00
Andrea Campi
61fc0f0ba0 Override #store to be consistent with #[].
[#5775 state:resolved]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-10-10 14:08:27 -02:00
wycats
b4b4a2aa28 Fix a few bugs when trying to use Head standalone 2010-10-10 00:53:52 -07:00
Santiago Pastorino
0b9eced70d Merge rails routing guide from master 2010-10-09 15:00:33 -02:00
Andrew White
d066ad638a Refactor resource action scope methods 2010-10-08 22:09:50 +01:00
Andrew White
981942a326 Backport ca3936d to 3-0-stable [#5274] 2010-10-08 11:20:21 +01:00
James MacAulay
2ded862226 fix rendering a partial with an array as its :object [#5746 state:resolved]
Signed-off-by: Michael Koziarski <michael@koziarski.com>
2010-10-08 09:36:12 +13:00
Aaron Patterson
5e685caf1c only forwarding enough methods to work. People should grab the delegate tempfile if they really need to do hard work 2010-10-07 10:10:40 -06:00
Aaron Patterson
fc9e9ed406 making sure respond_to? works properly 2010-10-07 10:10:31 -06:00
Aaron Patterson
d75244785f raising an argument error if tempfile is not provided 2010-10-07 10:10:24 -06:00
Aaron Patterson
003d67efb2 if it walks like a duck and talks like a duck, it must be a duck 2010-10-07 10:10:17 -06:00
Aaron Patterson
c4528deec1 delegate to the @tempfile instance variable 2010-10-07 10:10:11 -06:00
Aaron Patterson
1e50fae259 adding tests for uploaded file 2010-10-07 10:10:06 -06:00
Santiago Pastorino
9eeb24cd57 Add a TODO to remove gem "jruby-openssl" when jruby-openssl is merge in jruby
[#5762]
2010-10-07 13:50:49 -02:00
Anil Wadghule
b9fd742bb6 Add jruby-openssl gem in Gemfile necessary for JRuby
[#5762 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-10-07 11:49:00 -02:00
Ryan Bigg
53def60d83 Add "a" to make it better English
[#3796 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-10-07 11:41:22 -02:00
Hemant Kumar
444aa9c735 fix ruby 1.9 deadlock problem, fixes #5736 add connection pool tests 2010-10-06 14:43:26 -06:00
Aditya Sanghi
af53ed89c4 adding test for namedspaced mailers 2010-10-06 19:28:47 +11:00
Aditya Sanghi
accc5676d6 mailer comment should use namespace in comment 2010-10-06 19:28:47 +11:00
Erik Michaels-Ober
3e958a5bf7 Fix copy/paste bug
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-10-06 09:22:15 +02:00
Xavier Noria
13a4d1436f a couple of touches to the guides guidelines 2010-10-05 22:53:18 +02:00
Xavier Noria
cec7129729 aaaaannnddd, your beloved typo only spotted in the github colored diff no matter how many passes you did before pushing 2010-10-05 19:38:23 +02:00
Xavier Noria
da927d2e16 new guide: Ruby on Rails Guides Guidelines 2010-10-05 19:35:31 +02:00
Aaron Patterson
c13aaaa2f0 calling correct method on minitest for test name when teardown callback fails 2010-10-04 09:35:11 -07:00
Aaron Patterson
4a77431b9a [#5406 state:resolved] calling the correct method on minitest to obtain the test name 2010-10-04 09:35:06 -07:00
David Chelimsky
86571a1f43 Add view_assigns and deprecate _assigns for AV::TC on 3-0-stable
branch.

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-10-04 18:09:44 +02:00
Santiago Pastorino
e5da873db1 _assigns can have more internal vars in this test 2010-10-04 10:20:40 -02:00
Santiago Pastorino
e99c894767 PERF: Hash[] + map is faster than this inject, and var[1..-1] is faster than var.sub('@', '') 2010-10-03 13:28:25 -02:00
David Chelimsky
2380c71601 Added test case to specify that _assigns returns a Hash in AV::TC
[#5751 state:resolved]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-10-03 13:16:08 -02:00
José Valim
ebfbb2a2e3 :'' is not valid ruby. 2010-10-02 19:01:57 +02:00
José Valim
fef42738d7 Deprecate config.generators in Rails::Engine in favor of config.app_generators.
config.generators still works fine in Rails::Application and Rails::Railtie, but it will be deprecated in the latter in Rails 3.1.
2010-10-02 19:01:00 +02:00
Aditya Sanghi
f283812bed added test for form_for with search_field
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-10-02 17:52:33 +02:00
Aditya Sanghi
3569bde28e Fixing search_field to remove object attribute from options hash [#5730 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-10-02 17:52:21 +02:00
José Valim
f9b5f63319 Revert "Perf: refactor _assign method to avoid inject and defining unneeded local var."
_assigns must return a hash.

This reverts commit e66c1cee86.
2010-10-02 08:39:09 +02:00
Aaron Patterson
87104a71a9 Arel::Sql::Engine.new does not do anything anymore 2010-09-30 16:28:22 -07:00
Aaron Patterson
fc1c799241 type_name should check for blank because people may have messed up databases 2010-09-30 16:03:14 -07:00
Aaron Patterson
b0b2d41a48 build_where should be private 2010-09-30 14:35:36 -07:00
Aaron Patterson
7e73344f7a type_name is never a blank string, so use faster .nil? call 2010-09-30 14:22:09 -07:00
Aaron Patterson
ea6305411f speeding up object instantiation by eliminating instance_eval 2010-09-30 13:33:38 -07:00
Marcelo Giorgi
2221b701b4 AssociationCollection#include? working properly for objects added with build method [#3472 state:resolved] 2010-09-30 12:13:42 -07:00
Aaron Patterson
fc1bd2bba4 [#5441 state:resolved] refactoring code to determine aggregate column 2010-09-30 10:17:49 -07:00
Aaron Patterson
de3c0d7eb4 group clause must be more specific 2010-09-30 10:17:49 -07:00
oleg dashevskii
43f404ed6e Tests proving #5441 2010-09-30 10:17:49 -07:00
yalab
b08175825e Fix 'rake db:create' is ignore encoding when using postgres [#5717 state:resolved]
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-30 13:53:49 -03:00
José Valim
5704aa2e1a Use .find here as it is simpler and faster. 2010-09-30 07:25:45 +02:00
José Valim
1a2b28c9d9 Ensure that named routes do not overwrite previously defined routes. 2010-09-29 14:27:16 +02:00
Santiago Pastorino
9ddda10b67 Add gem 'arel' from git commented out as an example of how to Bundle egde Rails with Arel edge
[#5723 state:committed]
2010-09-29 00:15:53 -03:00
Aaron Patterson
f640af5a7a removing more useless code! yay! 2010-09-28 17:45:43 -07:00
Aaron Patterson
a35c8c6426 SqlLiteral is a string, so we can dry up these conditionals 2010-09-28 17:45:39 -07:00
Aaron Patterson
e080144242 shorten up or sql literal creation statements 2010-09-28 17:45:33 -07:00
Aaron Patterson
8ae8125e75 we only care about arrays and strings 2010-09-28 17:45:28 -07:00
Aaron Patterson
ddc2f2ee50 dry up calls to arel.join() 2010-09-28 17:45:23 -07:00
Aaron Patterson
a01547cc12 removing unused lasgns 2010-09-28 17:45:18 -07:00
Aaron Patterson
2e0114182c refactoring to remove crazy logic 2010-09-28 17:45:06 -07:00
Aaron Patterson
439a0ceb43 removing a conditional that is not used 2010-09-28 17:42:11 -07:00
Aaron Patterson
3daf8228f9 fisting the postgresql tests 2010-09-28 17:42:07 -07:00
Aaron Patterson
1685bd2e10 convert inject to map + join 2010-09-28 17:42:01 -07:00
Aaron Patterson
ede0466d13 each works well too 2010-09-28 17:41:57 -07:00
Aaron Patterson
bf388f37ac no need for splat and flatten 2010-09-28 17:41:53 -07:00
Aaron Patterson
93096aedcb avoid calling to_sql when we can 2010-09-28 17:41:49 -07:00
Aaron Patterson
c493624fc2 removing an inject + merge in favor of Hash#[] 2010-09-28 17:41:44 -07:00
Aaron Patterson
6059c9679e use new skool Ruby instead of Ruby Classic™ 2010-09-28 17:41:33 -07:00
Aaron Patterson
721f43498a be kind to the garbage collector: only instantiate objects when absolutely necessary 2010-09-28 17:41:28 -07:00
Aaron Patterson
e6e90839d0 adding test cases for the dynamic finder matcher match method 2010-09-28 17:41:24 -07:00
Aaron Patterson
ecbfed2f83 constructor should not do so much work; avoid allocating object if possible 2010-09-28 17:41:18 -07:00
Aaron Patterson
409bd22a2d @klass also uses DynamicFinderMatch, so no need for it on the relation 2010-09-28 17:41:13 -07:00
Aaron Patterson
1e687e98ac no need for a case / when statement 2010-09-28 17:41:08 -07:00
Aaron Patterson
cab12076d7 do not need intermediate variable, avoid lasgn 2010-09-28 17:41:03 -07:00
Aaron Patterson
1efeb5c935 DRY up our regular expression 2010-09-28 17:40:58 -07:00
Aaron Patterson
10d9740827 reduce method calls in the dynamic finder matcher 2010-09-28 17:40:50 -07:00
Aaron Patterson
40bc0cb34d where_values_hash always returns a hash 2010-09-28 17:39:06 -07:00
Marcelo Giorgi
9e5545cd66 Set attributes properly for model built from association with conditions [#5562 state:resolved]
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-28 15:23:23 -03:00
Étienne Barrié
fae57ef4f5 Test add_index and remove_index with a symbol name #4891 2010-09-28 10:08:35 -07:00
Aaron Patterson
9edaf10fee porting 0665182950 to master. Thanks Marcelo Giorgi 2010-09-28 10:05:07 -07:00
Aaron Patterson
c2c6f12c84 porting 515917f5d8 to master 2010-09-28 10:05:02 -07:00
Neeraj Singh
2525bfc5dd backport of #5706 and #5579 to 3-0-stable
[#5706 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-28 10:32:24 +02:00
Neeraj Singh
e0411f3412 backport of #5705 to 3-0-stable
[#5705 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-28 10:32:20 +02:00
Xavier Noria
61e70bf623 revises RDoc of Hash#to_param to be more precise about ordering 2010-09-28 00:37:21 +02:00
Xavier Noria
6643929d5a let Hash#to_param and Hash#to_query sort again
This was a regression introduced in 5c85822008. We bring
sorting back because people rely on it, eg for constructing consistent cache keys.
2010-09-28 00:33:13 +02:00
Aaron Patterson
b32bd08622 make sure we use the engine assigned to the table when quoting 2010-09-27 14:29:21 -07:00
Neeraj Singh
9e32b1cbe5 after_create in ActiveModel should in the order specified
[#5650 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-27 23:18:05 +02:00
Diego Carrion
a56df5b052 renderer calls object.to_json when rendering :json => object [#5655 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-27 23:17:55 +02:00
Aaron Patterson
e677275068 depending on arel 2.0.0 2010-09-27 09:27:24 -07:00
Aaron Patterson
f38c46cfcf Revert "depend on the arel gem, not the arel git repo"
This reverts commit d5e916563e.
2010-09-27 09:26:32 -07:00
Aaron Patterson
a88af8a669 removing nonsensical tests, limit now actually adds a limit 2010-09-27 09:23:32 -07:00
Aaron Patterson
d5e916563e depend on the arel gem, not the arel git repo 2010-09-27 08:56:31 -07:00
Tim Connor
d3ffea25b2 Fix issue with remove_index and add unit test [#5645 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-27 14:59:59 +02:00
Tim Connor
2f618bf7da Raise errors when index creation fails
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-27 14:59:56 +02:00
Aaron Patterson
f90a29853f do not pass nil values to arel 2010-09-26 18:42:18 -07:00
Nic Benders
59ef0a2a50 db:structure:dump should list current Rails.env adapter in errors, not always the test adapter
[#5710 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-26 20:44:39 -03:00
Tim Connor
15fd9a21dc Fix remove_index issue when provided :name is a symbol
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-26 20:40:57 -03:00
Santiago Pastorino
19b71233fe Fix the precedence issue here 2010-09-26 17:55:13 -03:00
Santiago Pastorino
262319ab01 Not need to do this double ternary 2010-09-26 17:43:49 -03:00
Santiago Pastorino
268319c8ba port is appended twice to HTTP_HOST when host already has the port 2010-09-26 12:06:39 -03:00
Santiago Pastorino
c8bf9674dd Bump up more deps 2010-09-26 01:03:27 -03:00
Santiago Pastorino
c8b34f2d9f Bump up some deps 2010-09-26 00:43:09 -03:00
Andrew Kaspick
0387d5b6f2 memoized protected methods should remain protected
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-24 20:32:10 -03:00
Marcelo Giorgi
23f728abd5 Delegate ActiveRecord::Base.offset to scoped methods (analogous to limit) [#5688 state:resolved]
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-24 20:25:24 -03:00
Brian Candler
4d023a6970 Fix warning message when db/schema.rb doesn't exist [#5625 state:resolved]
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-24 17:43:02 -03:00
Emilio Tagua
e41add0d30 These tests shouldn't depend on local time to pass or fail, we can use utc here.
Signed-off-by: José Valim <jose.valim@gmail.com>
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-24 17:15:07 -03:00
Emilio Tagua
8a68862020 Fix typo and add sanity test for code statistics rake task.
Signed-off-by: José Valim <jose.valim@gmail.com>
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-24 17:15:07 -03:00
Emilio Tagua
49d54b4fb6 Refactor decode_credentials to avoid inject and use map instead.
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-24 17:15:07 -03:00
Emilio Tagua
e66c1cee86 Perf: refactor _assign method to avoid inject and defining unneeded local var.
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-24 17:15:06 -03:00
Emilio Tagua
8105bc022e Refactor methods in html node to avoid injects.
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-24 17:15:06 -03:00
Emilio Tagua
abb99e3ac0 Refactor association_collection uniq method.
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-24 17:15:06 -03:00
Emilio Tagua
e1e39a9a7b No need to use inject here.
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-24 17:15:06 -03:00
Emilio Tagua
27cfb3e7bb Perf: refactor method.
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-24 17:15:06 -03:00
Emilio Tagua
093a30a019 No need to use inject here, use map instead.
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-24 17:15:06 -03:00
Emilio Tagua
68e1b5a397 Goodbye inject, hello map.
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-24 17:15:06 -03:00
Jeff Kreeftmeijer
109c37b73f got rid of the "ambiguous first argument; put parentheses or even spaces" warnings in the scaffold_generator tests [#4872 state:resolved]
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-24 16:18:50 -03:00
tnp
bdba74819c restore behavior of touch for models without :updated_xx [#5439 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-24 20:49:51 +02:00
Rodrigo Rosenfeld Rosas
8d14fa8959 Properly interpolate i18n keys in modules [#5572 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-24 20:49:33 +02:00
Aaron Patterson
1a61a797aa fixing bug with rails use of rack-test 2010-09-24 13:47:36 +02:00
Fred Wu
b0f059136b Ensures the app generator generates the correct @app_name. [#5434 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-24 13:12:25 +02:00
Carl Lerche
684bb86266 Improve performance of applications using file uploads by not busting the method cache on every request containing a file upload. 2010-09-22 17:37:00 -07:00
Santiago Pastorino
2db30351ed Missing the mysql2 gem here 2010-09-22 14:34:01 -03:00
Neeraj Singh
3c36c12a65 Error message should advice to use 'mysql2' gem.
If I create a new app using command
rails new demo -d mysql
then Gemfile contains 'mysql2' gem by default.

However if mysql gem is missing then error message says
raise "!!! Missing the mysql gem. Add it to your Gemfile: gem 'mysql', '2.8.1'"

[#5569 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-22 14:21:44 -03:00
Hemant Kumar
8765e06937 remove join table rows before removing owner row for habtm associations, fixes#5674 2010-09-22 08:36:29 -07:00
Aaron Patterson
7a6c715517 removing lolinject 2010-09-21 14:43:25 -07:00
Aaron Patterson
bfd4022075 fixing tests. woo 2010-09-21 14:43:20 -07:00
Aaron Patterson
a0fc2f7b74 providing arel with column information when possible [#5392 state:resolved] 2010-09-21 13:53:39 -07:00
Thiago Pradi
9d36e2ad2c Updating error message on ruby_version_check.rb
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-19 22:32:50 -07:00
rohit
39cb27b414 Fix output of 'rails runner --help' [#5661 state:committed]
Backport of 76266a

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-19 22:30:04 -07:00
rohit
68034efea1 Send 'rails runner' help message to stdout instead of stderr.
[#5661 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-19 16:47:46 -07:00
Santiago Pastorino
164e3b6612 application.js should be the last file on javascript_include_tag(:all) 2010-09-19 14:44:40 -07:00
Thiago Pradi
ab59522ea1 Exception handling more readable
[#5601 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-19 12:19:45 -07:00
Prem Sichanugrist
e125bf264e Use Time.current to maintain consistency with AS::Duration
In [32b82e4c6f], the committer has switch
methods in AS::Duration to use `Time.current` to return the correct
duration based on the `Time.default_zone` instead of using `Time.now`.

[#5607 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-19 11:47:25 -07:00
Andrew White
b79a782a05 Raise ArgumentError instead of normalizing controller name when there is a leading slash [#5651 state:resolved] 2010-09-18 17:59:24 +01:00
Andrew White
301462c89b Remove leading slash from controller [#5651 state:resolved] 2010-09-18 13:47:16 +01:00
rohit
7d54fba421 Application settings are specified in application.rb and not environment.rb 2010-09-14 20:08:08 +02:00
Carl Lerche
5391dd3821 Require lazy_load_hooks.rb with the correct path. 2010-09-14 10:40:15 -07:00
Jack Dempsey
a23bf047b6 require i18n in transliterate so it can run in isolated situations 2010-09-14 10:25:14 -07:00
Carl Lerche
b5a17d7648 Allow view helper's #initialize method to be called. [#5061 state:resolved] 2010-09-13 12:52:37 -07:00
Prem Sichanugrist
4ef2dead68 Add documentation for :spacer_template in Rails 3
This setting was existed since Rails 2.3.x, and seems like it have been left out when we rewriting the documentation.
2010-09-13 13:22:21 +10:00
Mikel Lindsaar
41807eb152 Backport of: added documentation for :as and :object in PartialRenderer
Commit: 02656ac397
2010-09-13 11:52:13 +10:00
Mikel Lindsaar
75b985e4e8 Fixing documentation to reflect deprecated add_to_base 2010-09-12 14:19:13 +10:00
Mikel Lindsaar
91693ddfe4 Backport of: added block arguments to ActionController::Metal#use
Commit: f0dbcc7a692bc375e3e52a9661af4037392ee52f
Useful for cases such as warden, where a block configuration is taken.

    class SomeController < ApplicationController
      use RailsWarden::Manager do |manager|
        manager.default_strategies :facebook_oauth
        manager.failure_app = SomeController.action(:authorize)
      end
    end
2010-09-12 11:47:25 +10:00
Mikel Lindsaar
14f1b09b46 Intersection between a relation and an array works in both directions.
Back port of commits a513f8f8bb marklazz (author) & 1c283765b6  Kanetontli (author)
2010-09-11 11:26:50 +10:00
Aaron Patterson
3479c1ea62 passing the quoted id to arel if the object has a quoted id 2010-09-10 15:30:48 -07:00
Aaron Patterson
89cc7426dd converting an inject to a map + Hash[] 2010-09-10 15:30:43 -07:00
Emilio Tagua
1817ae327e Add more examples in performance script.
[#5610 state:committed]

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
2010-09-10 13:15:34 -07:00
Jeremy Kemper
c510870a8f Revert "Fix require for class_attribute"
This reverts commit 82ea5db030.
2010-09-10 12:17:02 -07:00
Jeremy Kemper
ceb193a201 Switch back to mysql for easier comparison 2010-09-10 12:17:02 -07:00
Jeremy Kemper
f6d5ff2f00 Ruby 1.9 compat: convert Pathname to string 2010-09-10 12:17:02 -07:00
Jeremy Kemper
b8ff3df6a4 Include addressable for AR perf bench 2010-09-10 12:17:02 -07:00
Aaron Patterson
465dd6f0e9 specific number of spaces should not be enforced 2010-09-10 11:51:47 -07:00
Aaron Patterson
2ef60690ff avoid method_missing and reduce method calls 2010-09-10 10:22:37 -07:00
Jeremy Kemper
ac89275f1d AR perf test: switch to mysql2, bundle faker and rbench 2010-09-09 14:42:55 -07:00
Jeremy Kemper
298da5b8a9 Fix require for class_attribute 2010-09-09 14:42:50 -07:00
Emilio Tagua
993572472a Refactor finder conditions look up and assigment for apply_finder_conditions. 2010-09-09 13:45:58 -07:00
Emilio Tagua
ab1ab5fcec Refactor Relation#only. No need to go through every option and test it. 2010-09-09 13:07:09 -07:00
Emilio Tagua
d30fb467c9 Add tests for Relation#only. 2010-09-09 13:07:05 -07:00
Emilio Tagua
172377df45 No need to go through every option and test it, just don't add skipped ones. 2010-09-09 13:07:01 -07:00
Neeraj Singh
733e928234 return is not needed here 2010-09-09 10:34:35 -07:00
Neeraj Singh
742da4b0d4 remove unnecessary call
if operation is count then column_name will never be blank
2010-09-09 10:34:05 -07:00
Aaron Patterson
2820addea7 creating a new array is required. who knew? :-( 2010-09-09 10:33:31 -07:00
Aaron Patterson
7108daf20e no need for Array.wrap, also avoid array creation 2010-09-09 09:44:25 -07:00
Neeraj Singh
a9b5b19d9a make apply_modules run faster 2010-09-09 09:44:20 -07:00
Mikel Lindsaar
ed9d30981f Fixing up rails application init command - Rails Guides ticket 32 2010-09-09 23:08:14 +10:00
Mikel Lindsaar
3de55aafbf Adding linkage to redirect_to from Base and adding status code option reference 2010-09-09 14:04:34 +10:00
Aaron Patterson
378728b5d1 eliminate present? for fewer method calls 2010-09-08 16:56:22 -07:00
Aaron Patterson
662ce52ed7 returning arrays lets us avoid Array.wrap 2010-09-08 16:53:41 -07:00
Aaron Patterson
ad781a175c removing unnecessary conditional test 2010-09-08 16:39:36 -07:00
Aaron Patterson
16cff17e53 switch to blank? to avoid method calls 2010-09-08 16:33:24 -07:00
Aaron Patterson
5297e641cd refactor to use faster empty? 2010-09-08 16:07:00 -07:00
Aaron Patterson
7ddf663c75 drying up joins() 2010-09-08 15:34:21 -07:00
Aaron Patterson
41e0f68474 reduce method calls, use reject + blank? instead of select + present? 2010-09-08 15:15:17 -07:00
Aaron Patterson
a746090a31 refactor a couple injects to map + Hash[] 2010-09-08 14:02:57 -07:00
Aaron Patterson
1276c28336 avoid an inject in favor of dup 2010-09-08 13:56:10 -07:00
Aaron Patterson
9a28d42d60 attributes should be constructed with table objects 2010-09-07 16:47:21 -07:00
Aaron Patterson
442e4d087b attributes should be associated with tables 2010-09-07 16:39:09 -07:00
Aaron Patterson
b1c104296e serialized attributes should be serialized before validation [#5525 state:resolved] 2010-09-07 13:39:37 -07:00
Aaron Patterson
ef66a08160 no need to freeze this string 2010-09-07 13:13:30 -07:00
Jeremy Kemper
33b954005c fixed some issues with JSON encoding
- as_json in ActiveModel should return a hash
  and handle :only/:except/:methods options
- Array and Hash should call as_json on their elements
- json methods should not modify options argument

[#5374 state:committed]

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>

Conflicts:

	activemodel/lib/active_model/serialization.rb
2010-09-07 11:33:46 -07:00
Aaron Patterson
3091cb386f removing useless code, cleaning variable names 2010-09-07 11:28:10 -07:00
Aaron Patterson
d73fcfeb52 select should raise error when no block or no parameter is passed 2010-09-07 10:48:24 -07:00
Aaron Patterson
b8899bba12 select does not need a *args 2010-09-07 10:33:43 -07:00
ISHIKAWA Takayuki
a461c2b595 revision of typo: crytographically [#5566 state:resolved]
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-07 11:04:28 -03:00
Santiago Pastorino
c72140198d unscoped has nothing so merging with a relation just returns the relation 2010-09-07 03:33:42 -03:00
Aaron Patterson
bd1059f5ad cleaning up confusing logic 2010-09-06 18:56:38 -07:00
Santiago Pastorino
7020c92e0f Use scoped here to get the scoped where 2010-09-05 20:31:05 -03:00
Santiago Pastorino
817b8f0ac4 Make number_to_human and number_with_precision work with negatives 2010-09-05 10:26:03 -03:00
Santiago Pastorino
8c49666474 Fix indentation errors 2010-09-05 10:25:53 -03:00
Santiago Pastorino
9fe7ef65ea Fix code style a bit 2010-09-05 10:25:44 -03:00
Ben Sharpe
935fa9d6d5 Fix number_to_human(0) exception [#5532 state:resolved]
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-05 10:25:35 -03:00
Santiago Pastorino
f0113e59c2 Make scoped reorder override previous applied orders
[5528 state:committed]
2010-09-05 09:29:57 -03:00
Nick Ragaz
02daf68e6a failing test for reorder overriding default_scope
[5528]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-05 09:29:51 -03:00
Neeraj Singh
1c7a7545eb order should always be concatenated.
order that is declared first has highest priority in all cases.

Here are some examples.

Car.order('name desc').find(:first, :order => 'id').name

Car.named_scope_with_order.named_scope_with_another_order

Car.order('id DESC').scoping do
  Car.find(:first, :order => 'id asc')
end

No special treatment to with_scope or scoping.

Also note that if default_scope declares an order then the order
declared in default_scope has the highest priority unless
with_exclusive_scope is used.

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-09-05 08:14:49 -03:00
Xavier Noria
29887510bf too many people are looking for the 2.3 guides, put by now a link at the top of the home, and add the Rails version in the main header 2010-09-03 22:00:42 +02:00
Andrew White
2ad2bd3644 Add missing lookup keys for error messages 2010-09-03 21:31:47 +02:00
Emilio Tagua
d7201210ba Use new finders syntax in docs. 2010-09-03 21:31:30 +02:00
Akira Matsuda
dcce930a8f fix typo(?) 2010-09-03 21:31:14 +02:00
Ken Collins
b1291836c3 A few schema changes for the SQL Server adapter.
Signed-off-by: Michael Koziarski <michael@koziarski.com>
2010-09-03 14:52:17 +12:00
rohit
6a60387dce Add two integration tests for GeneratedAttribute missing type error. [#5461 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-02 13:00:39 +02:00
rohit
233e0e8ce8 Output a friendly message when no type given for GeneratedAttribute [#5461 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-02 13:00:39 +02:00
rohit
5c06777293 Failing test for GeneratedAttribute [#5461 state:open]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-02 13:00:39 +02:00
Andreas Garnæs
86a96fb17c ActiveModel#to_xml fix (renamed parameter).
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-02 13:00:39 +02:00
José Valim
20866a5c95 Ensure routes are loaded only after the initialization process finishes, ensuring all configuration options were applied. 2010-09-02 13:00:39 +02:00
Akira Matsuda
3e931b1961 "rails console t" must not load "production" but "test" [#5527 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-02 11:55:33 +02:00
Santiago Pastorino
36e625df83 Add ruby-debug19 for mri 1.9 2010-09-01 21:24:51 -03:00
David Heinemeier Hansson
b227a9a948 Dont need to spell out the dependency 2010-09-01 19:09:48 -05:00
David Heinemeier Hansson
7221d6a841 Have sections for both Ruby 1.8.7 and 1.9.2 for the debugger since they use different gems 2010-09-01 17:38:48 -05:00
Andrew White
aefa11be11 Reset default scope in Thread.current when class is unloaded [#5497 state:resolved]
Signed-off-by: Xavier Noria <fxn@hashref.com>
2010-09-01 22:52:06 +02:00
Andrew White
bf87528b53 Add before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants!
Signed-off-by: Xavier Noria <fxn@hashref.com>
2010-09-01 22:52:06 +02:00
Emilio Tagua
93a716fb9c Fix test: this should return 0 not 7, since Arel was ignoring select clause and now it's fixed.
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-01 15:09:16 +02:00
Andrew White
9441eabbbf Move implicit nested call before options handling so that nested constraints work [#5513 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-01 10:15:24 +02:00
Alex Chrome
3b6d7f0df8 Added :format option for form_for helper and spec for this [#5226 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-01 10:15:24 +02:00
Jack Dempsey
c25c81e7c9 split out active_record migration logic so others can easily reuse [#5389 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-01 10:15:23 +02:00
Neeraj Singh
d1eb9ff8b1 delegate method should treat :prefix => false same as :prefix => nil
[#5375 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-01 10:15:23 +02:00
yury
3df90defa8 Remove unnecessary code from UrlHelper#link_to.
convert_options_to_data_attributes always returns not nil stringified html_options [#5445 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-01 10:15:23 +02:00
Krekoten' Marjan
2adad2a0cc Make ActiveSupport::Duration#method_missing delegate blocks to value [#5498 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-01 10:15:22 +02:00
Subba Rao Pasupuleti
9c5248f6f2 nested attributes tests should rely on associated objects to verify results not on assert_difference [#5206 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-01 10:15:22 +02:00
Thiago Pradi
fed73ffecf Use join instead of looping and calling to_s [#5492 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-09-01 10:15:21 +02:00
Andrew White
69ae216bcf Bump rack-mount to 0.6.13 and add test case for named character classes [#5509 state:resolved]
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-08-31 21:28:44 -03:00
Pratik Naik
8cba115301 Make all the Relation finder methods consistent 2010-08-31 21:28:12 -03:00
Emilio Tagua
54b193fe16 Avoid calling build_where is no argument is given. 2010-08-31 21:27:49 -03:00
Emilio Tagua
5fc006a9a4 Improved conditionals usage to prevent calling methods. 2010-08-31 21:27:38 -03:00
Emilio Tagua
4144eace88 Don't test conditional in iteration if it is not present just clone it. 2010-08-31 21:27:27 -03:00
Pratik Naik
3746453c3a Remove default values for Relation#limit/offset/from/create_with 2010-08-31 21:26:26 -03:00
Pratik Naik
c2a87b45b8 Change relation merging to always append select, group and order values 2010-08-31 21:26:10 -03:00
Damien Mathieu
031b60d270 Fix benchmarking for rails3
* Fix the generated file examples
* Fix the generators commands
2010-09-01 00:06:41 +02:00
Jaime Iniesta
63306de3e7 Fix API docs for button_to options 2010-09-01 00:06:15 +02:00
Michael MacDonald
b29eb89be8 Corrected typo in example on rendering collections in partials changing @posts to @products to match the example 2010-09-01 00:05:52 +02:00
Pratik Naik
c1bafe07a9 Fix an english fail 2010-09-01 00:05:28 +02:00
Pratik Naik
e7b1b3f610 Fix the readonly section 2010-09-01 00:05:09 +02:00
Pratik Naik
3e786065f5 Update the section about joins 2010-09-01 00:04:55 +02:00
Pratik Naik
67b4c42b89 Fix pessimistic locking examples 2010-09-01 00:04:40 +02:00
Pratik Naik
bab620fe5c Reword calculations section 2010-09-01 00:04:24 +02:00
Pratik Naik
d37a44e42c Reword the section about exists? 2010-09-01 00:04:07 +02:00
Pratik Naik
c1915f5ff3 Improve example for having() 2010-09-01 00:03:48 +02:00
Pratik Naik
6ba646329b Remove {} from hash conditions. And more occurrences of [] in array conditions 2010-09-01 00:03:21 +02:00
Pratik Naik
9017e1f03f Array conditions dont need [] 2010-09-01 00:03:04 +02:00
Pratik Naik
6655a3c248 User.each is a lie 2010-08-31 00:28:16 +02:00
Joost Baaij
46fddc305a Remove mention of InstantRails, it is completely obsolete.
Mention RubyInstaller instead which is actually quite pleasant and runs Rails fine.

Signed-off-by: Xavier Noria <fxn@hashref.com>
2010-08-31 00:28:01 +02:00
Joost Baaij
3e7f7668fc Remove beta and RC paths in documentation
Signed-off-by: Xavier Noria <fxn@hashref.com>
2010-08-31 00:27:41 +02:00
Damien Mathieu
3a96fa485c fix the cache_fu links
Signed-off-by: Xavier Noria <fxn@hashref.com>
2010-08-31 00:27:03 +02:00
Bryan Helmkamp
e709c97e08 Update README to match Rails 3 generated directory structure
Signed-off-by: Xavier Noria <fxn@hashref.com>
2010-08-31 00:26:43 +02:00
Akira Matsuda
050a345972 The command for creating the sessions table has changed
Signed-off-by: Xavier Noria <fxn@hashref.com>
2010-08-31 00:26:27 +02:00
Joost Baaij
e8d2002f21 Expanded routing documentation with current best practices
Signed-off-by: Xavier Noria <fxn@hashref.com>
2010-08-31 00:26:04 +02:00
Joost Baaij
05bb9cae95 Rework the routing documentation.
Move the default route to the bottom, as this practise should be discouraged.
Add documentation for resources, external redirects and Rack applications.

Signed-off-by: Xavier Noria <fxn@hashref.com>
2010-08-31 00:25:35 +02:00
Xavier Noria
6ed616d51a let String#strip_heredoc handle blank lines even if they are not indented 2010-08-30 10:24:43 +02:00
Mikel Lindsaar
d9a323ea81 Adding option to ActiveResource to allow you to not reset the previously stored requests and responses by passing false to respond_to 2010-08-29 22:54:45 -07:00
Mikel Lindsaar
676b5bf970 Updating documentation on ActiveResource HTTP Mock and also adding test coverage 2010-08-29 22:54:45 -07:00
Jeremy Kemper
fcdedb2c00 Bump version to 3.0.1.pre 2010-08-29 21:59:53 -07:00
Jeremy Kemper
99a87e9dd0 Bump arel to 1.0.1 2010-08-29 16:33:09 -07:00
Loren Segal
9891ca89c6 Add .yardopts so YARD can document Rails 2010-08-30 07:00:04 +09:00
Xavier Noria
e38fa05781 implements String#strip_heredoc 2010-08-29 23:51:19 +02:00
Xavier Noria
c7106e827e revises a deprecation message 2010-08-29 22:48:53 +02:00
Santiago Pastorino
3d0c92868c -v=1.0.0 not needed 2010-08-29 16:53:44 -03:00
Santiago Pastorino
a8a9f00058 Make CI install bundler stable since 1.0 is out 2010-08-29 16:19:16 -03:00
Santiago Pastorino
ca73b5ba65 No more beta or rc on guides 2010-08-29 15:22:29 -03:00
David Heinemeier Hansson
9f9c50f917 No more build 2010-08-29 13:03:41 -05:00
David Heinemeier Hansson
b63b6c4033 Depend on ARel 1.0 w/ tiny fixes 2010-08-29 12:56:49 -05:00
David Heinemeier Hansson
647ed22aad Depend on Bundler 1.0 w/ tiny fixes 2010-08-29 12:55:21 -05:00
David Heinemeier Hansson
851552bd80 Prep for final release 2010-08-29 12:53:51 -05:00
Sam Ruby
829df8007d Make rake routes gracefully handle routes with no name
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-08-29 14:39:22 -03:00
José Valim
a2c547f592 Ensure we are not calling length on nil. 2010-08-28 22:53:48 -03:00
Santiago Pastorino
15e9b53a57 PERF: Avoid two method calls 2010-08-28 21:35:43 -03:00
Mike Perham
90d4a19285 Support pluggable cache stores.
[#5486 state:committed]

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
2010-08-28 15:51:39 -07:00
Jeremy Kemper
0f94ca31b1 Clean up CHANGELOGs 2010-08-28 15:50:43 -07:00
Jesse Storimer
ef01f8840b Ensure that inherited helper_methods are available after calling clear_helpers [#5348 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-28 18:09:02 -03:00
Fred Wu
3edd3d052e Fixed the session name generated by the app_generator. Also refactored the corresponding test suites to be cleaner. [#5434 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-28 18:08:50 -03:00
yury
331234e0ab Micro optimization for build_named_route_call in PolymorphicRoutes:
1. use map instead of inject
2. use [].join("_") instead of '<<'. It is a little bit faster for ruby 1.9.2 and x2 faster for ruby 1.8.7. http://gist.github.com/548143

[#5450 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-28 18:08:47 -03:00
Thiago Pradi
cc5a9c642b Fixing typo [#5485 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-28 18:08:46 -03:00
Santiago Pastorino
bf35d1e7c0 type="password" for password_fields 2010-08-28 04:54:13 -03:00
Andrew White
7f83aefd38 Read the route name directly from the route instead of looking it up in the named routes hash
Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
2010-08-27 17:05:30 -07:00
Joost Baaij
0c87873455 Use common terminology 2010-08-28 00:03:31 +02:00
Joost Baaij
8da45763b2 escape constants that should not be linked to 2010-08-28 00:03:16 +02:00
Joost Baaij
5502a78c3e mention the alert and notice accessors on the flash 2010-08-28 00:03:01 +02:00
Joost Baaij
6c84fd80b7 expand cookie examples with signed and permanent methods 2010-08-28 00:02:33 +02:00
Xavier Noria
c144f50347 solves everything in guides raised by WARNINGS=1 (except for one which is abandoned atm) 2010-08-27 23:20:57 +02:00
Xavier Noria
e2d73f01a9 adds a comment in cli.rb so that it is clear that exec_script_rails! performs an exec call 2010-08-27 23:20:56 +02:00
Sam Aarons
ba03dd4774 Fix em_mysql2 error in rake db:create
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-27 14:57:45 -03:00
José Valim
dbbf198f5c Add missing require. 2010-08-27 14:57:40 -03:00
Santiago Pastorino
3ba8e31005 Make InstanceTagMethods#value_before_type_cast raise if the model don't respond to attr_before_type_cast or attr method
[#3374] [#5471 state:committed]
2010-08-27 09:09:02 -03:00
Jeremy Kemper
e8a083ecc2 Ruby 1.9: be sure to explicitly reference toplevel constants within BasicObject deprecation proxies 2010-08-26 23:17:12 -07:00
Carlos Antonio da Silva
39f2f18679 Removing some unuseful begin/end and refactor prompt_option_tag a bit
[#5469 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-08-27 01:19:39 -03:00
Xavier Noria
983a5e2970 updates de title of the generators guide in the home and index 2010-08-27 00:17:36 +02:00
Xavier Noria
2af7f29203 getting started guide: adds a reference to Michael Hartl's free online book in the what's next section 2010-08-26 23:47:30 +02:00
José Valim
a2d3e6e29f Be sure to call helper :all just on direct children. (Tests by Jesse Storimer) 2010-08-26 18:18:43 -03:00
José Valim
473feeb32d Doh, be sure to store the string modification. 2010-08-26 16:48:04 -03:00
José Valim
d806aa2b68 Do not modify frozen strings in place. 2010-08-26 16:26:17 -03:00
José Valim
daf2f95830 Update CHANGELOG. 2010-08-26 16:03:34 -03:00
José Valim
52e962086d Add clear_helpers as a way to clean up all helpers added to this controller, maintaing just the helper with the same name as the controller. 2010-08-26 16:03:10 -03:00
José Valim
b78011314e Ensure templates like template.html are found but still uses the proper virtual path. 2010-08-26 15:32:41 -03:00
Xavier Noria
9df512be94 getting started guide: revises text wrt bundler 2010-08-26 15:59:23 +02:00
Xavier Noria
ace0f87056 revises a few link texts 2010-08-26 15:59:15 +02:00
Jaime Iniesta
1c2a2f711d change 'a SQL' to 'an SQL' as suggested by the api documentation guidelines 2010-08-26 14:23:29 +02:00
Jaime Iniesta
a3161096c2 lifecycle should be two words, life cycle 2010-08-26 14:23:10 +02:00
Jaime Iniesta
217fb3e9b5 Fix capture_helper.rb api documentation, unescaped script tag was breaking it on the content_for explanation 2010-08-26 14:22:55 +02:00
Xavier Noria
dcdb8bae38 Revert "to_json => as_json"
This reverts commit 7a6d8e4ad4.

Reason: The method that gives you a Ruby string with JSON source code is #to_json
2010-08-26 02:00:04 +02:00
Xavier Noria
27512c2161 adds missing require for #parameterize 2010-08-26 01:56:27 +02:00
Aleksander Pohl
60685475dc - Fix non-ascii characters in headers
Signed-off-by: Xavier Noria <fxn@hashref.com>
2010-08-26 01:46:00 +02:00
James Miller
3ecbae0672 to_json => as_json 2010-08-26 01:44:12 +02:00
James Miller
59cd141c81 mysql2 is now the default, typos 2010-08-26 01:43:43 +02:00
James Miller
d7f1226412 Fix typo, favour => favor 2010-08-26 01:43:17 +02:00
Joost Baaij
6a035099b2 Restored top-level documentation for ActionController::Base.
This information was lost in commit bd6b61be88.
This might have been intentional, but this class does represent the starting
point for all things related to actions, and as such should document it.

I couldn't find any trace of this documentation, which seems like a waste.
Updated parts here and there to conform to current best practices.
2010-08-26 01:43:01 +02:00
Joost Baaij
3b3cfa44f6 fixed capitalization 2010-08-26 01:42:48 +02:00
Joost Baaij
908544c90e change rdoc to conform to api guidelines 2010-08-26 01:42:26 +02:00
Joost Baaij
2722c82f6e remove unwanted linebreak 2010-08-26 01:42:12 +02:00
Rémy Coutable
d810854d42 Restore consistency with the rest of the doc. 2010-08-26 01:41:51 +02:00
Rémy Coutable
e12ff5b3bd Fixed a missing simple quote. 2010-08-26 01:41:24 +02:00
Neeraj Singh
61292a1f87 minor formatting fixes 2010-08-26 01:40:15 +02:00
Xavier Noria
8bad8ac758 AS guide: Array.wrap vs splat is only valid for 1.8 2010-08-25 20:30:28 +02:00
Andrew White
241dfa3c90 Catch mysql2 access denied errors in rake db:create [#5432 state:resolved]
Signed-off-by: Xavier Noria <fxn@hashref.com>
2010-08-25 18:07:42 +02:00
Aaron Patterson
9ba46cf15a use blank? instead of present?, mark SQL literals as SQL literals 2010-08-25 05:17:32 -07:00
Aaron Patterson
3dc9880866 no need to send on a public method 2010-08-25 05:17:31 -07:00
Aaron Patterson
da7a28027a refactor select { is_a? } to grep() 2010-08-25 05:17:31 -07:00
Aaron Patterson
bfe956d785 run tests in verbose mode 2010-08-25 05:17:31 -07:00
Aaron Patterson
e991f39709 mark SQL literals as SQL literals 2010-08-25 05:17:31 -07:00
Jakub Suder
aec084955d better callstack reporting in deprecation messages
now the reported line is the first line in the stack
that's outside Rails, which is the one that actually
caused the problem in the first place

[#5231 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-25 07:25:19 -03:00
Andrew White
55c1f351c4 Remove rails info route from rake routes output [#5452 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-25 07:25:18 -03:00
Mikel Lindsaar
d887dbc2d6 Make ActiveResource::InvalidRequestError more user friendly
Signed-off-by: Xavier Noria <fxn@hashref.com>
2010-08-25 10:06:27 +02:00
Andrew White
37467bf0fc Use nested scope for routes defined at the :resources scope level (as in Rails 2.3)
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-24 21:14:32 -03:00
Xavier Noria
30dcac2926 :nodoc:s #unscoped until its behavior is more clear, now sometimes works, sometimes not 2010-08-25 01:10:54 +02:00
Xavier Noria
5deeb43fca edit pass to a recent doc patch 2010-08-25 01:10:54 +02:00
Neeraj Singh
78f6f0dc4b touch operationg if used along with belongs_to will also be invoked on associated objects 2010-08-25 01:10:54 +02:00
Trevor Turk
174d5cd7ee Note about how to exit the console in the Getting Started guide 2010-08-25 01:10:53 +02:00
Neeraj Singh
2ae4f01650 unscoped does not work when chained with named_scope 2010-08-25 01:10:53 +02:00
José Valim
3a831cb7d6 Allow format to be skipped. This is used internally by mount. 2010-08-24 16:56:51 -03:00
José Valim
0d7b8f8c83 Finally fix the bug where symbols and strings were not having the same behavior in the router.
If you were using symbols before for methods like match/get/post/put/delete, it is likely that this commit will break your routes.
Everything should behave the same if you are using strings, if not, please open up a ticket.
2010-08-24 16:44:47 -03:00
José Valim
91916e6c3c Ensure shortcuts inside resources also generates helpers. 2010-08-24 14:54:23 -03:00
José Valim
6b54a6a8ff Hide internal apps from rake routes [#5443 state:resolved] 2010-08-24 13:22:34 -03:00
José Valim
6d1e87b16b Fix how routes inside namespaces are generated. 2010-08-24 13:05:56 -03:00
Santiago Pastorino
7830f8d9f8 Allow actions which start with A-Za-z_ only 2010-08-24 12:44:14 -03:00
Aaron Suggs
d8196bf994 Bump rake dependency to 0.8.4. [#5279 state:resolved]
This rake version adds the Rake::RDocTask#rdoc_task_name method, used in
railties/lib/rails/tasks/documentation.rake

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-24 11:58:00 -03:00
Neeraj Singh
aa384de7dd @user.touch should not fail if User does not have updated_at/updated_on column.
[#5439 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-24 11:27:00 -03:00
Andrew White
78486cb9c5 Reset symbolized path parameters when a test request is recycled [#5437 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-24 11:26:53 -03:00
José Valim
6579173814 Ensure prefix in routes are generated properly. 2010-08-24 11:26:37 -03:00
Joost Baaij
a32f46d0ce fix broken relative links [#5415 state:committed]
Signed-off-by: Xavier Noria <fxn@hashref.com>
2010-08-24 16:15:43 +02:00
José Valim
c857bd23c0 Ensure timestamps are not generated when explicitly set to false [#5440 state:resolved] 2010-08-24 10:47:38 -03:00
Wincent Colaiuta
5ccdb362b4 Add test case for ActiveRecord::Base.record_timestamps = false
This is a failing test case for Lighthouse ticket #5440:

  https://rails.lighthouseapp.com/projects/8994/tickets/5440

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-24 10:47:30 -03:00
José Valim
7a7012c717 Fix a bug where symbols and strings were not behaving the same in the router. [#5431 state:resolved] 2010-08-24 10:19:01 -03:00
Andrew White
8feb2856ea When custom resource actions are specified using strings add the default name and action if the string is a valid ruby method name.
[#5431 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-24 10:09:44 -03:00
Krekoten' Marjan
5708412052 Fix test of generated Gemfile with mysql selected as DB driver
[#5435 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-08-24 09:39:13 -03:00
David Heinemeier Hansson
822fa17c6c mysql db defaults to mysql2 gem 2010-08-23 21:40:59 -05:00
David Heinemeier Hansson
04aa14f8d7 Bump rails version 2010-08-23 21:31:08 -05:00
David Heinemeier Hansson
bc61196bf5 Depend on latest arel RC 2010-08-23 21:27:58 -05:00
Santiago Pastorino
aafb29073a Point guides to bundler 1.0.0.rc.6 2010-08-23 23:27:13 -03:00
David Heinemeier Hansson
880eaa145e Depend on latest Bundler RC 2010-08-23 21:22:22 -05:00
David Heinemeier Hansson
fc6db6226f Prefer the mysql2 gem for MySQL database.ymls 2010-08-23 21:19:20 -05:00
David Heinemeier Hansson
8931dd17a9 Prep for RC2 2010-08-23 21:15:48 -05:00
Santiago Pastorino
c8b84a1c8c Config is deprecated on 1.8.8 and 1.9.3 use RbConfig 2010-08-23 23:09:35 -03:00
Aaron Patterson
36fcc99cce marking sql literals as sql literals 2010-08-23 18:49:10 -07:00
José Valim
a1ca2e0a38 Update CHANGELOG for ActionPack. 2010-08-23 21:53:56 -03:00
Aaron Patterson
6a1ea881cf we should mark sql strings as sql literals 2010-08-23 14:27:16 -07:00
Aaron Patterson
1cc653f9b3 sql literal strings should be marked as sql literal strings 2010-08-23 13:57:32 -07:00
Aaron Patterson
eeb9b379f9 we should mark strings as SQL Literal values 2010-08-23 13:30:46 -07:00
Brian Lopez
ce04ea973c mysql2 adapter is being maintained in the mysql2 gem itself
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-08-23 16:01:16 -03:00
Brian Lopez
ab64dc9c20 no need to depend on mysql2 master anymore
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-08-23 15:51:01 -03:00
Raimonds Simanovskis
f10fb1c4e9 use database from ARUNIT_DB_NAME environment variable when running tests on Oracle 2010-08-24 01:49:42 +08:00
Xavier Noria
2570fda5ab removes words moved in previous edit of the generator generator USAGE 2010-08-23 09:45:34 +02:00
Xavier Noria
b97ad85d44 generators guide: edit pass 2010-08-23 09:15:10 +02:00
Xavier Noria
d125687b97 adds USAGE to the generator generator USAGE (not sure this meta thing is any good at 8:12 AM with little coffee) 2010-08-23 09:15:10 +02:00
Raimonds Simanovskis
2c81a31039 Do not use time zone in test_read_attributes_before_type_cast_on_datetime for Oracle database
As currently string_to_time method is not doing time zone conversion to database time zone
2010-08-23 07:34:07 +08:00
Raimonds Simanovskis
bedf6a0061 updated test_should_record_timestamp_for_join_table for Oracle 2010-08-23 07:34:07 +08:00
Santiago Pastorino
6edae4553e Bump up rack-mount to 0.6.12 2010-08-22 20:29:14 -03:00
Santiago Pastorino
8235c9288f type fixed 2010-08-23 01:23:24 +02:00
Aaron Patterson
6ca6ef2ab0 removing duplicate tests 2010-08-22 16:06:21 -07:00
Santiago Pastorino
0579963a38 Silence warnings for Encoding.default_external= and Encoding.default_internal= 2010-08-22 18:43:51 -03:00
Santiago Pastorino
7cb44a5092 Fix namespace problem on object which inherit from ActiveSupport::BasicObject 2010-08-22 17:18:02 -03:00
Andrew White
df0a7bfb8f Cache the symbolized path parameters using a instance variable in the request object rather than the environment hash. This it to prevent stale parameters in later routing constraints/redirects as only the normal path parameters are set by Rack::Mount.
Also if a constraint proc arity is more than one, pass the symbolized path parameters
as the first argument to match redirect proc args and provide easier access.

[#5157 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-22 16:18:42 -03:00
Santiago Pastorino
2106782828 Set default_internal and default_external on AS for testing purposes 2010-08-22 02:23:13 -03:00
Santiago Pastorino
e88f8bee5e Set default_internal and default_external on AM for testing purposes 2010-08-21 22:53:42 -03:00
Santiago Pastorino
11e9883f19 Move encoding settings for testing purposes to abstract_unit file 2010-08-21 22:38:15 -03:00
Raphomet
b4e5da6bde Trifling typos
[#5422 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-08-21 19:22:54 -03:00
Brian Lopez
7dbc99ef0d reload bob after his journy to a new timezone 2010-08-20 20:00:21 -07:00
Jeremy Kemper
d0e3323d5b Revert "Just add connection management middleware if running in a concurrent environment."
This reverts commit 6b29dc876f.
2010-08-20 18:55:12 -07:00
Xavier Noria
68e2d1e496 prevent RDoc from autolinking "Rails" in the API home page 2010-08-21 02:29:39 +02:00
Xavier Noria
9011f8f49c requires horo 1.0.2 2010-08-21 02:29:25 +02:00
Nick Sieger
b4a520874a Fix hash modification during iteration in Mapper [#5420]
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-08-20 18:28:19 -03:00
Andrew White
47f6d8b880 Support routing constraints in functional tests
Extend assert_recognizes and assert_generates to support passing
full urls as the path argument. This allows testing of routing
constraints such as subdomain and host within functional tests.

[#5005 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-20 14:51:50 -03:00
Aaron Patterson
612c233a28 adding FOUND_ROWS to the connect flags for mysql2 2010-08-20 10:15:52 -07:00
Neeraj Singh
8f72ddc12b after_validation should be called irrespective of the result of validation.
I confirmed that this is the behavior on 2.3.x .

[5419 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-20 11:24:58 -03:00
Andrew White
47280f083a Don't add the standard https port when using redirect in routes.rb and ensure that request.scheme returns https when using a reverse proxy.
[#5408 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-20 10:41:43 -03:00
Andrew White
c6391e6676 Allow symbols for :path resource(s) option [#5306 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-20 09:33:33 -03:00
Xavier Noria
20088f6fff deletes the rdoc task of each component, they are no longer published separately 2010-08-20 13:34:28 +02:00
Xavier Noria
d033b237c4 the pdoc task is no longer needed 2010-08-20 13:33:51 +02:00
Aaron Patterson
809a04ba8f fisting after_rollback and after commit callbacks 2010-08-20 00:06:32 -07:00
Santiago Pastorino
ac66de4a82 Bump up tzinfo to 0.3.23 2010-08-20 02:46:10 -03:00
Aaron Patterson
e509d4afc9 updates return number of rows matched rather than number of rows affected 2010-08-19 19:13:35 -07:00
Andrew White
ad063263bc Optimize find_sti_class when store_full_sti_class is true
[#5403]

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
2010-08-19 16:03:37 -05:00
José Valim
8f2b2781b0 Use attribute readers as they are faster in general. 2010-08-19 15:15:46 -03:00
Andrew White
6b52a58f72 Move regexps in options hash to :constraints hash so that they are pushed into the scope [#5208 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-19 15:09:46 -03:00
Andrew White
1031fe1478 Move edit route before show route so that it will have precedence if the :id parameter allows slashes [#5409 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-19 15:09:40 -03:00
Neeraj Singh
758f01d49e While creating a new record using has_many create method default scope of child should be respected.
author.posts.create should take into account default_scope
defined on post.

[#3939: state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-19 15:09:34 -03:00
Santiago Pastorino
21c9795c15 Bump up rack-mount to 0.6.10 2010-08-19 14:50:06 -03:00
Aaron Patterson
49e406efb7 removing useless ternary 2010-08-19 10:46:01 -07:00
Aaron Patterson
1ef9b98a31 we should wrap strings as sql literals 2010-08-19 10:35:23 -07:00
Santiago Pastorino
bef90f8449 We need bundle update only here 2010-08-19 14:13:54 -03:00
Jeremy Kemper
64f4dc68f6 Memoize STI class lookups for the duration of a request 2010-08-19 11:28:49 -05:00
Aaron Patterson
a16ec2f4cf refactor if / else to ||= 2010-08-18 23:37:11 -07:00
Xavier Noria
6fb6ddb9a7 avoids warnings about mismatched indentations in Ruby 1.9.2 2010-08-19 03:44:31 +02:00
Xavier Noria
632a224bd1 now for real, the suite loads everything and these went unpatched 2010-08-19 03:00:34 +02:00
Xavier Noria
6580c6df36 avoids a ton o warnings activesupport/lib/active_support/dependencies.rb:239: warning: loading in progress, circular require considered harmful ... activesupport/lib/active_support/core_ext/hash/indifferent_access.rb while running the suite in Ruby 1.9.2 2010-08-19 03:00:19 +02:00
Xavier Noria
ddce48a355 get rid of the warning "+ after local variable is interpreted as binary operator even though it seems like unary operator" in Ruby 1.9.2 2010-08-19 02:29:02 +02:00
wycats
06632578c2 Revert "It's snowing!"
This reverts commit e4283007d6.
2010-08-18 16:49:34 -07:00
Aaron Patterson
2f6383e340 refactoring to remove duplicate logic 2010-08-18 12:10:37 -07:00
Aaron Patterson
7e85b16518 call to present? is not necessary 2010-08-18 11:51:39 -07:00
Javier Martín
12f7f7a714 Don't pluralize resource methods [#4704 state:resolved]
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-08-18 13:58:21 -03:00
Santiago Pastorino
82eff0ffe9 Bump up rdoc to 2.5.10 2010-08-18 13:55:56 -03:00
wycats
588ac71213 1.8 block variable shadowing strikes again 2010-08-17 16:52:34 -07:00
wycats
0a41ece3e3 Sadly, this segv's in 1.8 :( 2010-08-17 16:52:34 -07:00
Andre Arko
c40856c46c Allow member actions (get, etc) to accept strings, with test 2010-08-18 07:36:49 +08:00
Xavier Noria
23303d6ab7 you rarely want ^ or $ in validations, use \A when you mean \A 2010-08-18 00:35:05 +02:00
Trey Bean
017840beb8 Missing object for comparison in ActiveModel::EachValidator example code. 2010-08-18 00:34:46 +02:00
Matthew Mongeau
92f4cca4a3 to_sentence should return a duplicate 2010-08-17 13:53:22 -07:00
Jeff Lawson
82a58abe05 Bug Fix -- clean up connection after stored procedure [#3151 state:resolved] 2010-08-17 13:14:57 -07:00
Jeff Lawson
90176a6f15 Bug Fix -- clean up connection after stored procedure [#3151 state:resolved] 2010-08-17 13:14:57 -07:00
Xavier Noria
4b21dfe9a7 debugging guide: revises the section on debugging RJS 2010-08-17 13:33:53 +02:00
Luke Brown
c11ba424e7 Added an example and explaination for using an optional path scope for the locale 2010-08-17 13:31:52 +02:00
Josiah Ivey
21063e5e27 Debugging Guide: Improve grammar for the RJS section 2010-08-17 13:31:40 +02:00
Santiago Pastorino
22d242c2ca recommended is the right word here 2010-08-17 13:31:28 +02:00
Santiago Pastorino
6f478b0698 Restore pet -> owner relationship to the previous state
[#5365]
2010-08-16 22:47:49 -03:00
Mark Turner
fc43c62fc6 added testcase for belongs_to with a counter_cache and touch
[#5365 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-08-16 22:47:40 -03:00
Peter Wagenet
b9281e8e2c Class Attribute setter returns set value
Signed-off-by: wycats <wycats@gmail.com>
2010-08-16 18:38:33 -07:00
Xavier Noria
5f5c508444 code gardening: we have assert_(nil|blank|present), more concise, with better default failure messages - let's use them 2010-08-17 03:31:39 +02:00
Santiago Pastorino
020aeb6192 assert_equal here 2010-08-16 22:01:04 -03:00
Tobias Lütke
141634ddc6 Added test case to verify that transaction callbacks are correctly propagated to class observers
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-08-16 22:00:52 -03:00
Xavier Noria
14be1789b7 the (public) routing DSL does not accept symbols for get|post|put|delete|match 2010-08-17 02:50:31 +02:00
Raimonds Simanovskis
1d2e075bf1 Replaced hardcoded SessionStore table creation SQL with calls to ActiveRecord adapter migration methods
Otherwise hardcoded table creation SQL was failing on Oracle database
2010-08-17 06:18:39 +08:00
Raimonds Simanovskis
d1480926e8 added dependencies in Gemfile for running ActiveRecord tests with Oracle database 2010-08-17 06:18:38 +08:00
José Valim
047e411fd2 annoted_source_code may return nil if an erro rhappens during template compiling. 2010-08-16 14:12:07 -03:00
wycats
452a56ad51 Make sure apps upgrading from 2.3 get defaulted to UTF-8 (ht: parndt) 2010-08-15 16:31:40 -07:00
wycats
83cb532009 Test callbacks 2010-08-15 16:31:40 -07:00
Xavier Noria
c330e96a6e routing guide: wildcard segments are quite flexible, go beyond the simple use case 2010-08-16 01:12:10 +02:00
wycats
a34dce9717 Add back #callback and deprecate it 2010-08-15 15:36:18 -07:00
wycats
b8ec4eaac5 find .text.html and .text.plain files, and deprecate it 2010-08-15 15:27:57 -07:00
wycats
688368100a headers["X-Foo-Count"] = 2 is deprecated properly now 2010-08-15 15:18:22 -07:00
wycats
19fb031d84 render :file in 2.3 behaved like render :template in Rails 3 (adding the current controller as a prefix) 2010-08-15 15:07:05 -07:00
Subba Rao Pasupuleti
dbe5ae488e select tags coerce the :selected option, options to strings before comparison [#5056 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-15 16:54:31 -03:00
Bryce Thornton
1091a6e9b7 Allow for any possible TLD when using the :all option with the cookie session store. This works for subdomain.mysite.local, google.co.uk, google.com.au, etc. [#5147 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-15 16:54:31 -03:00
José Valim
8520045200 Improve routes task code and print the application as :to => RackApp. [#5338 state:resolved] 2010-08-15 16:54:31 -03:00
Mark Turner
ebf7447b34 make rake routes print the name of a Rack endpoint app [#5338 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-15 16:54:31 -03:00
Santiago Pastorino
10177d3a38 Revert "Makes AR use AMo to_key implementation"
This reverts commit ccd4364a13.
2010-08-15 11:37:50 -03:00
José Valim
f224c66a91 to_key should return all exists keys (if any exists), regardless if the object is persisted or not. If you need it to reflect persistance, you should use to_param. 2010-08-15 11:30:06 -03:00
Mikel Lindsaar
88fc37ff03 Making time_zone_options_for_select return a html_safe string
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-08-15 09:59:24 -03:00
Santiago Pastorino
bdeeca358b This is not needed anymore 2010-08-15 09:18:46 -03:00
Santiago Pastorino
5f7bfb1c3a Makes use of class << self instead of def self. 2010-08-15 08:42:05 -03:00
Santiago Pastorino
ae7732f957 remove already defined method to avoid warnings 2010-08-15 08:03:26 -03:00
Santiago Pastorino
df8a941a43 Revert "connection reader is defined later"
This reverts commit f4cce71d96.
2010-08-15 08:03:17 -03:00
Santiago Pastorino
6d68cde2c5 connection reader is defined later 2010-08-15 07:21:10 -03:00
Santiago Pastorino
0f1b9bbbf8 Makes topics.written_on null => true back again some tests rely on that 2010-08-15 07:20:58 -03:00
Santiago Pastorino
477a9d4d86 MySQL2 added to CI 2010-08-14 21:56:29 -03:00
Santiago Pastorino
a036999ed1 Should be Boolean there 2010-08-14 19:49:33 -03:00
Santiago Pastorino
707248a629 Add missing model 2010-08-14 18:50:15 -03:00
Santiago Pastorino
ecf59b4776 Both tests are using the same model, move the model to another file and add the missing require 2010-08-14 18:50:07 -03:00
Santiago Pastorino
677564f8f7 object/try should be required after abstract_unit to have AS in the load path 2010-08-14 18:34:15 -03:00
Mark Hayes
f6f7ae4020 in Rendering objects with RecordIdentifier example, locals should reference @account not @buyer 2010-08-14 13:26:03 +02:00
Santiago Pastorino
b3ece73114 deprected -> deprecated 2010-08-14 13:26:03 +02:00
Subba Rao Pasupuleti
76c91a237c Adding missing required statement
[#5056 state:resolved]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-08-14 06:28:54 -03:00
Santiago Pastorino
05ba082c6a Fixes some ActionMailer tests 2010-08-14 05:59:05 -03:00
Santiago Pastorino
3270c58ebb Deletes trailing whitespaces (over text files only find * -type f -exec sed 's/[ \t]*$//' -i {} \;) 2010-08-14 04:20:06 -03:00
Santiago Pastorino
ccd4364a13 Makes AR use AMo to_key implementation
[#5249]
2010-08-13 22:28:26 -03:00
Santiago Pastorino
6373dd466f This method is actually not used, it's implemented on the concrete adapters
[#5331 state:committed]
2010-08-13 21:20:50 -03:00
Aaron Patterson
59e63e76c3 converting to a symbol is not necessary 2010-08-13 16:50:22 -07:00
Prem Sichanugrist
433d7a26fe Removing most of the symbol to proc usage in Active Record
This will hopefully make Active Record run a bit more faster.
2010-08-13 16:22:54 -07:00
Aaron Patterson
79e15f0340 removing a lolinject 2010-08-13 14:45:06 -07:00
Santiago Pastorino
3698da65e5 Moves local_request? to require.local?
[#5361 state:committed]
2010-08-13 18:17:26 -03:00
Aaron Patterson
108179b068 avoid direct use of arel constants 2010-08-13 13:32:48 -07:00
Aaron Patterson
bacf78150c removing references to arel constants 2010-08-13 12:35:58 -07:00
Aaron Patterson
e86b758592 avoiding symbol to proc again 2010-08-13 12:35:58 -07:00
Aaron Patterson
abd973689d do not use arel constants directly 2010-08-13 12:35:58 -07:00
Aaron Patterson
fb6edb1769 symbol to proc is slow, we should avoid it 2010-08-13 12:35:58 -07:00
Jeremy Kemper
e4283007d6 It's snowing! 2010-08-12 13:32:39 -07:00
Xavier Noria
91ae6e9933 be more precise re :validate and :autosave 2010-08-12 19:32:26 +02:00
Subba Rao Pasupuleti
fe2d65864e no callbacks should be created for empty array [#5289 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-12 13:13:41 -03:00
Subba Rao Pasupuleti
9df227983f tidy up validations length code [#5297 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-12 13:13:37 -03:00
Greg Campbell
d03a1249a0 Add missing ActiveModel::Validations require
[#5311 state: resolved]

ActiveModel::Validations uses Hash#except, but does not require it from
ActiveSupport.  (This wasn't showing up in the tests, because it was
required in the helper, and was also required in
ActiveModel::Serialization).

Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-12 13:13:33 -03:00
Neeraj Singh
9528aa9f86 Ensure we can nest include calls [#5285 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-12 13:13:26 -03:00
Xavier Noria
4dcce5d06e revises some autosave docs, style and content 2010-08-12 17:40:32 +02:00
Paco Guzman
ab68d4b52e applied guidelines to "# =>" 2010-08-12 17:40:20 +02:00
Xavier Noria
1e6e868d8c commit review: applies guidelines to "# =>" 2010-08-12 17:40:10 +02:00
Neeraj Singh
198bffe3be updating documentation for named_scope and default_scope 2010-08-12 17:39:52 +02:00
Neeraj Singh
06af291346 adding more documentation for autosave option 2010-08-12 17:39:05 +02:00
José Valim
30ea923040 Make update_attribute behave as in Rails 2.3 and document the behavior intrinsic to its implementation. 2010-08-12 12:06:57 -03:00
Mark Turner
7325dd21b3 fixed indentation in test cases
Signed-off-by: wycats <wycats@gmail.com>
2010-08-11 23:56:11 -07:00
wycats
f2d22ecbb3 Replace snowman with utf8=✓ 2010-08-11 18:37:06 -07:00
Paul Hieromnimon
1c970b8394 Raising exception if fixture file can't be found 2010-08-11 15:45:29 -07:00
Aaron Patterson
c8509d5303 subtracting blank strings is slightly faster than blank? 2010-08-11 15:44:54 -07:00
Xavier Noria
36cb62eb9d AS guide: some revisions 2010-08-12 00:15:43 +02:00
Xavier Noria
bfd728182c no need to assign if we are gonna return 2010-08-12 00:15:43 +02:00
Aaron Patterson
ff760dd6ce avoid multiple hash lookups 2010-08-11 14:59:47 -07:00
Aaron Patterson
5352a89d50 dry up the hash dup and avoid sending nil values 2010-08-11 14:45:07 -07:00
Aaron Patterson
a56ee4c9a2 avoiding tap saves us time 2010-08-11 11:43:27 -07:00
Aaron Patterson
dac2b37b03 unless Array#empty? is faster than if Array#present? 2010-08-11 11:28:13 -07:00
Aaron Patterson
8464ee0650 stop using private methods 2010-08-11 11:24:59 -07:00
José Valim
e1b85c3bda Ensure @config is not a reserved instance variable in controllers. [#5342 state:resolved] 2010-08-11 10:27:11 -03:00
José Valim & Carlos Antonio da Silva
1fbcd5f5fc layout_for works again with objects as specified in the documentation and Rails 2.3 [#5357 state:resolved] 2010-08-11 10:27:11 -03:00
Nick Sieger
43b8722f4b Missed one spot for --skip-active-record, which means that new Gemfile isn't set up right
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-08-11 00:43:49 -03:00
Gonçalo Silva
d9b77ddecd added support for more printers 2010-08-10 10:24:00 -07:00
José Valim
6f88b82263 Revert "require_dependency should require using the normal mechanism if possible to avoid double-requires"
This was causing double requires since 991cd59a22 was reverted.
This reverts commit 8bf79739b4.
2010-08-10 11:20:04 -03:00
Xavier Noria
b2eaac24c3 fixes a typo reported by rymai 2010-08-10 15:35:23 +02:00
Xavier Noria
5859f5eee1 AS guide: removes some duplication, and makes a second pass on method delegation 2010-08-10 11:53:27 +02:00
Xavier Noria
63ffec85b7 adds the AS guide to the guides index 2010-08-10 04:09:52 +02:00
Xavier Noria
ca3fc4b325 AS guide: documents Module#redefine_method 2010-08-10 03:59:48 +02:00
Xavier Noria
aaa52c6d1f AS guide: documents Module#(instance_)method_names 2010-08-10 03:46:21 +02:00
Xavier Noria
68bed3a4ad AS guide: documents Module#delegate 2010-08-10 03:29:26 +02:00
Xavier Noria
8968eecb93 AS guide: documents Process.daemon 2010-08-10 01:53:53 +02:00
Xavier Noria
3c404c56eb AS guide: documents date/datetime/time arithmetic with durations 2010-08-10 01:31:23 +02:00
Jeremy Kemper
cbf89a378c Merge remote branch 'brianmario/3-0-stable' into 3-0-stable 2010-08-09 16:12:33 -07:00
Brian Lopez
2d681838c0 move mysql2 adapter into core 2010-08-09 15:30:06 -07:00
Brian Lopez
b02751c961 ignore this test for mysql2 2010-08-09 15:29:59 -07:00
Brian Lopez
3ccf3504d2 skip the before_type_cast_on_datetime test entirely for mysql2 2010-08-09 15:29:53 -07:00
Brian Lopez
98384b1ce8 typo 2010-08-09 15:29:33 -07:00
Brian Lopez
a263a8ffd5 update tests for mysql2 support 2010-08-09 15:29:26 -07:00
wycats
dd7e872e85 Properly deprecate register_javascript_include_default and reset_javascript_include_default 2010-08-09 12:42:09 -07:00
wycats
f85b206e7a rename _snowman to _e 2010-08-09 12:06:51 -07:00
wycats
22cbc3f0fa Improve best_standards_support to use only IE=Edge in development mode 2010-08-09 11:48:53 -07:00
Xavier Noria
efb2bd0409 adds missing requires for Object#try 2010-08-09 15:14:00 +02:00
Xavier Noria
195e891954 form helpers guide: fixes an example 2010-08-09 14:11:37 +02:00
Xavier Noria
28d82bd2e9 adds URL to the body generated by the redirect macro in the routes mapper as per the RFC, extracts common test pattern into a test macro, adds a test to cover the :status option 2010-08-09 13:32:45 +02:00
Xavier Noria
4d4b865b11 AC guide: commit review, block examples go at column 0, use .example.com as example domain 2010-08-09 12:25:22 +02:00
Adam Meehan
5c109e243f typo in AM 2010-08-09 12:25:11 +02:00
Daniel McNevin
f7996be0c7 updated the action_controller guide with the new session configuration options 2010-08-09 12:24:56 +02:00
Neeraj Singh
d55491c844 correcting wrong example 2010-08-08 18:34:58 +02:00
Xavier Noria
4b18d3c210 routing guide: documents the CONTROLLER environment variable understood by the routes task 2010-08-08 18:30:09 +02:00
Xavier Noria
783dc5207b updates horo dependency to 1.0.1 2010-08-08 11:29:21 +02:00
Xavier Noria
78c7705b32 undoes one of the modifications to RDoc::Parser.binary? 2010-08-07 20:10:56 +02:00
Xavier Noria
5aec933385 quick hack: hijacks the predicate RDoc::Parser.binary? so that it does not consider a handful of ordinary Ruby files in the Rails tree as binary (and thus excluded from the API) 2010-08-07 15:19:22 +02:00
Xavier Noria
413c9c8235 adds Abstract Controller to the API 2010-08-07 01:45:48 +02:00
Aaron Patterson
91930dc30b reduce the number of times current_connection_id is called in with_connection() 2010-08-06 16:38:53 -07:00
Aaron Patterson
001a574785 test to ensure that respond_to? delegates to arel 2010-08-06 15:23:11 -07:00
Aaron Patterson
a897a1f4a3 sorry AR, my privates are none of your business 2010-08-06 14:52:33 -07:00
Aaron Patterson
8fb0c9f509 do not rely on arel class structure 2010-08-06 11:31:32 -07:00
Xavier Noria
0bb8d0561a AS guide: documents calculations with Time objects 2010-08-06 17:31:48 +02:00
Xavier Noria
bed98b9bf2 AR guide: fixes a query 2010-08-06 13:37:44 +02:00
Neeraj Singh
148dd2eac6 fixing typo 2010-08-05 22:58:36 +02:00
Neeraj Singh
06e4c48815 more documentation for class_inheritable_* 2010-08-05 22:58:20 +02:00
Aaron Patterson
0a86cb5972 fixing whitespace errors 2010-08-05 08:15:07 -07:00
Xavier Noria
e34fb808db AS guide: documents DateTime#advance 2010-08-05 15:57:59 +02:00
Tom Stuart
2005f8234a Fix ActiveSupport::Callbacks' define_callbacks and ActiveSupport::Concern documentation to look like native English 2010-08-05 15:57:44 +02:00
Aaron Patterson
05a49c7718 avoid passing lists of lists to the group clause 2010-08-04 16:24:29 -07:00
Xavier Noria
902d732617 Merge remote branch 'docrails/master' into 3-0-stable 2010-08-05 01:15:08 +02:00
Łukasz Strzałkowski
84d5461d43 Fixed broken test suite - there was problem with namespacing in DeprecatedConstant class 2010-08-05 05:28:39 +08:00
Łukasz Strzałkowski
18bcc548bf Typo in class name 2010-08-05 05:28:39 +08:00
Aaron Patterson
ba9602b9e7 call to_a since we are not passing anything to all() 2010-08-04 14:22:20 -07:00
Aaron Patterson
906ef233e4 fisting indentation 2010-08-04 14:11:20 -07:00
Piotr Sarnacki
4da32babdf Reload action_methods in AbstractController after defining new method.
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-04 14:45:55 -03:00
José Valim
87365272e9 Revert "If a file is in the load path, require it without its full path (in more places)"
Caused failures in ActionMailer test suite.

This reverts commit 963638aac8.
2010-08-04 14:45:55 -03:00
Aaron Patterson
f316a851dd do not pass AR objects to ARel 2010-08-04 08:44:35 -07:00
José Valim
19c77a0d2b Revert "Put lib back on the autoload path"
This was causing engines/gems to eager load everything in lib. Another fix is comming soon.

This reverts commit 02a5842cd0.
2010-08-04 14:16:18 +02:00
wycats
2498cdaf14 I'm unsure how cloning was working in Rails 3 before 2010-08-04 04:05:28 -07:00
wycats
963638aac8 If a file is in the load path, require it without its full path (in more places) 2010-08-04 03:21:37 -07:00
wycats
fbc40a4d94 Fix a subtle bug involving RAILS_ROOT 2010-08-04 03:20:56 -07:00
wycats
32d840d98a Concernify SanitizeHelper and TextHelper so including TextHelper correctly include SanitizeHelper and extends its ClassMethods 2010-08-04 03:20:44 -07:00
wycats
bd1cf94a29 Add a fake UrlRewriter, since instantiating it in tests happens, but is basically crazysauce 2010-08-04 03:20:08 -07:00
wycats
d599e94e45 require_dependency should require using the normal mechanism if possible to avoid double-requires 2010-08-04 02:16:48 -07:00
wycats
91e4249c02 Provide a bit more information in the deprecation for config.gem 2010-08-04 02:15:15 -07:00
wycats
07c5e5416b Shim Initializer.run 2010-08-04 01:07:23 -07:00
rohit
8158afa47e Give extracted options back to args in AMo callbacks. Fixes two failing tests in AR.
Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-08-04 00:33:23 -03:00
Aaron Patterson
9269e55b1f avoid passing AR::Base objects to Arel when we can 2010-08-03 17:57:59 -07:00
wycats
b46b5a6d54 Fix up constant deprecation to be less dependent on load order 2010-08-03 16:03:35 -07:00
wycats
46a1da7c79 Put lib back on the autoload path 2010-08-03 15:00:17 -07:00
RainerBlessing
8b7219b9d6 query value is converted to_s instead of to_yaml 2010-08-03 14:55:15 -07:00
wycats
109dc3c39c Deprecate the @controller instance variable 2010-08-03 14:23:46 -07:00
wycats
af8e085190 Move the deprecations before the load hooks 2010-08-03 12:50:41 -07:00
wycats
146a013c42 Fix a couple of mistaken deprecation solutions 2010-08-03 12:50:13 -07:00
wycats
84703be5ff Deprecate ActionController::UrlWriter properly 2010-08-03 12:41:18 -07:00
wycats
43cc69cb65 Fix the session= deprecation to include the secret key 2010-08-03 12:31:39 -07:00
wycats
01186652cc Even though exempt_from_layout is no longer needed, some people are still using it. Deprecate it instead of removing. 2010-08-03 12:29:03 -07:00
wycats
7a1bba4799 Allow :name to be a Symbol (was this removed by accident?) 2010-08-03 12:22:10 -07:00
wycats
4474470ffd update this for a change in the core method 2010-08-03 11:49:44 -07:00
wycats
9ae7f04cd6 properly deprecate #{type}_validation_on_#{on} 2010-08-03 11:48:06 -07:00
wycats
1318bf6e33 Properly deprecate validate_on_#{on} 2010-08-03 11:48:06 -07:00
Subba Rao Pasupuleti
5987fd4c79 Tidy up error.rb code
[#5288 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
2010-08-03 14:58:53 -03:00
Santiago Pastorino
677e1e58b6 Stub is_a? not instance_of? here 2010-08-03 12:20:11 -03:00
José Valim
3b170b2e14 Freeze options so we raise an error when people modify it in place. 2010-08-03 15:37:35 +02:00
José Valim
79583ca9b1 validates_length_of should not change the options hash in place. [#5283 state:resolved] 2010-08-03 15:37:26 +02:00
rohit
257e9c4ec4 Failing test for validates_length_of, when both too_short and too_long messages are set [#5283 state:open]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-03 15:37:17 +02:00
Samuel Lebeau
a44779e9bb Avoid potentially expensive inspect call in router. [#4491 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
2010-08-03 12:03:45 +02:00
José Valim
503931df05 Merge branch 'master' into 3-0-stable 2010-08-03 10:55:09 +02:00
wycats
f73e9d2df8 Properly deprecate config.load_paths and config.gem 2010-08-02 23:39:33 -07:00
1762 changed files with 69969 additions and 87748 deletions

41
.gitignore vendored
View File

@@ -1,22 +1,21 @@
# Don't put *.swp, *.bak, etc here; those belong in a global ~/.gitignore.
# Check out http://help.github.com/ignore-files/ for how to set that up.
*.gem
pkg
.bundle
Gemfile.lock
debug.log
.Gemfile
/.bundle
/.ruby-version
/pkg
/dist
/doc/rdoc
/*/doc
/*/test/tmp
/activerecord/sqlnet.log
/activemodel/test/fixtures/fixture_database.sqlite3
/activesupport/test/fixtures/isolation_test
/railties/test/500.html
/railties/test/fixtures/tmp
/railties/test/initializer/root/log
/railties/doc
/railties/guides/output
/railties/tmp
/RDOC_MAIN.rdoc
doc/rdoc
activemodel/doc
activeresource/doc
activerecord/doc
actionpack/doc
actionmailer/doc
activesupport/doc
activemodel/test/fixtures/fixture_database.sqlite3
actionpack/test/tmp
activesupport/test/fixtures/isolation_test
railties/test/500.html
railties/test/fixtures/tmp
railties/test/initializer/root/log
railties/doc
railties/guides/output
railties/tmp

View File

@@ -1,28 +0,0 @@
script: 'ci/travis.rb'
before_install:
- gem install bundler
rvm:
- 1.8.7
- 1.9.2
- 1.9.3
- 2.0.0
env:
- "GEM=railties"
- "GEM=ap,am,amo,ares,as"
- "GEM=ar:mysql"
- "GEM=ar:mysql2"
- "GEM=ar:sqlite3"
- "GEM=ar:postgresql"
notifications:
email: false
irc:
on_success: change
on_failure: always
channels:
- "irc.freenode.org#rails-contrib"
campfire:
on_success: change
on_failure: always
rooms:
- secure: "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="
bundler_args: --path vendor/bundle

View File

@@ -1,4 +1,3 @@
--exclude /templates/
--quiet
act*/lib/**/*.rb
railties/lib/**/*.rb

105
Gemfile
View File

@@ -1,65 +1,76 @@
source 'https://rubygems.org'
source 'http://rubygems.org'
gemspec
gem "rails", :path => File.dirname(__FILE__)
if ENV['AREL']
gem 'arel', :path => ENV['AREL']
else
gem 'arel'
end
gem "rake", ">= 0.8.7"
gem "mocha", ">= 0.9.8"
gem "rdoc", ">= 2.5.10"
gem "horo", ">= 1.0.2"
gem 'bcrypt-ruby', '~> 3.0.0'
gem 'jquery-rails'
# for perf tests
gem "faker"
gem "rbench"
gem "addressable"
if ENV['JOURNEY']
gem 'journey', :path => ENV['JOURNEY']
else
gem 'journey'
end
# This needs to be with require false to avoid
# it being automatically loaded by sprockets
gem 'uglifier', '>= 1.0.3', :require => false
# execjs >= 2.1.0 doesn't work with Ruby 1.8
gem 'execjs', '< 2.1.0'
gem 'rake', '>= 0.8.7'
gem 'mocha', '~> 0.14', :require => false
group :doc do
# The current sdoc cannot generate GitHub links due
# to a bug, but the PR that fixes it has been there
# for some weeks unapplied. As a temporary solution
# this is our own fork with the fix.
gem 'sdoc', :git => 'git://github.com/fxn/sdoc.git'
gem 'RedCloth', '~> 4.2'
gem 'w3c_validators'
end
# AS
gem 'memcache-client', '>= 1.8.5'
gem "memcache-client", ">= 1.8.5"
# Add your own local bundler stuff
instance_eval File.read '.Gemfile' if File.exists? '.Gemfile'
# AM
gem "text-format", "~> 1.0.0"
platforms :mri do
group :test do
gem 'ruby-prof', '~> 0.11.2' if RUBY_VERSION < '2.0'
end
platforms :mri_18 do
gem "system_timer"
gem "ruby-debug", ">= 0.10.3"
gem 'ruby-prof'
end
platforms :mri_19 do
gem "ruby-debug19"
end
platforms :ruby do
gem 'json'
gem 'yajl-ruby'
gem 'nokogiri', '>= 1.4.5', '< 1.6'
gem "nokogiri", ">= 1.4.3.1"
# AR
gem 'sqlite3', '~> 1.3.5'
gem "sqlite3-ruby", "~> 1.3.1", :require => 'sqlite3'
group :db do
gem 'pg', '>= 0.11.0'
gem 'mysql', '>= 2.8.1'
gem 'mysql2', '>= 0.3.10'
gem "pg", ">= 0.9.0"
gem "mysql", ">= 2.8.1"
gem "mysql2", ">= 0.2.6"
end
end
gem 'benchmark-ips'
platforms :jruby do
gem "ruby-debug", ">= 0.10.3"
gem "activerecord-jdbcsqlite3-adapter"
# This is needed by now to let tests work on JRuby
# TODO: When the JRuby guys merge jruby-openssl in
# jruby this will be removed
gem "jruby-openssl"
group :db do
gem "activerecord-jdbcmysql-adapter"
gem "activerecord-jdbcpostgresql-adapter"
end
end
env :AREL do
gem "arel", :path => ENV['AREL']
end
# gems that are necessary for ActiveRecord tests with Oracle database
if ENV['ORACLE_ENHANCED_PATH'] || ENV['ORACLE_ENHANCED']
platforms :ruby do
gem 'ruby-oci8', ">= 2.0.4"
end
if ENV['ORACLE_ENHANCED_PATH']
gem 'activerecord-oracle_enhanced-adapter', :path => ENV['ORACLE_ENHANCED_PATH']
else
gem "activerecord-oracle_enhanced-adapter", :git => "git://github.com/rsim/oracle-enhanced.git"
end
end

View File

@@ -1,131 +0,0 @@
GIT
remote: git://github.com/fxn/sdoc.git
revision: 9977ca4ecf83a76d637861f79319b11830d51de5
specs:
sdoc (0.3.19)
json (>= 1.1.3)
rdoc (~> 3.10)
PATH
remote: .
specs:
actionmailer (3.2.19)
actionpack (= 3.2.19)
mail (~> 2.5.4)
actionpack (3.2.19)
activemodel (= 3.2.19)
activesupport (= 3.2.19)
builder (~> 3.2)
erubis (~> 2.7.0)
journey (~> 1.0.4)
rack (~> 1.4.5)
rack-cache (~> 1.2)
rack-test (~> 0.6.1)
activemodel (3.2.19)
activesupport (= 3.2.19)
builder (~> 3.2)
activerecord (3.2.19)
activemodel (= 3.2.19)
activesupport (= 3.2.19)
arel (~> 3.0.2)
tzinfo (~> 0.3.29)
activeresource (3.2.19)
activemodel (= 3.2.19)
activesupport (= 3.2.19)
activesupport (3.2.19)
i18n (~> 0.6, >= 0.6.4)
multi_json (~> 1.0)
rails (3.2.19)
actionmailer (= 3.2.19)
actionpack (= 3.2.19)
activerecord (= 3.2.19)
activeresource (= 3.2.19)
activesupport (= 3.2.19)
bundler (~> 1.0)
railties (= 3.2.19)
railties (3.2.19)
actionpack (= 3.2.19)
activesupport (= 3.2.19)
rack-ssl (~> 1.3.2)
rake (>= 0.8.7)
rdoc (~> 3.4)
thor (>= 0.14.6, < 2.0)
GEM
remote: https://rubygems.org/
specs:
RedCloth (4.2.9)
arel (3.0.3)
bcrypt-ruby (3.0.1)
benchmark-ips (1.2.0)
builder (3.2.2)
erubis (2.7.0)
execjs (2.0.2)
i18n (0.6.11)
journey (1.0.4)
jquery-rails (3.1.0)
railties (>= 3.0, < 5.0)
thor (>= 0.14, < 2.0)
json (1.8.1)
mail (2.5.4)
mime-types (~> 1.16)
treetop (~> 1.4.8)
memcache-client (1.8.5)
metaclass (0.0.4)
mime-types (1.25.1)
mocha (0.14.0)
metaclass (~> 0.0.1)
multi_json (1.10.1)
mysql (2.9.1)
mysql2 (0.3.15)
nokogiri (1.5.11)
pg (0.17.1)
polyglot (0.3.5)
rack (1.4.5)
rack-cache (1.2)
rack (>= 0.4)
rack-ssl (1.3.4)
rack
rack-test (0.6.2)
rack (>= 1.0)
rake (10.2.2)
rdoc (3.12.2)
json (~> 1.4)
sqlite3 (1.3.9)
thor (0.19.1)
treetop (1.4.15)
polyglot
polyglot (>= 0.3.1)
tzinfo (0.3.41)
uglifier (2.5.0)
execjs (>= 0.3.0)
json (>= 1.8.0)
w3c_validators (1.2)
json
nokogiri
yajl-ruby (1.2.0)
PLATFORMS
ruby
DEPENDENCIES
RedCloth (~> 4.2)
arel
bcrypt-ruby (~> 3.0.0)
benchmark-ips
execjs (< 2.1.0)
journey
jquery-rails
memcache-client (>= 1.8.5)
mocha (~> 0.14)
mysql (>= 2.8.1)
mysql2 (>= 0.3.10)
nokogiri (>= 1.4.5, < 1.6)
pg (>= 0.11.0)
rails!
rake (>= 0.8.7)
sdoc!
sqlite3 (~> 1.3.5)
uglifier (>= 1.0.3)
w3c_validators
yajl-ruby

View File

@@ -1 +1 @@
3.2.19.github9
3.0.2

View File

@@ -1,43 +1,38 @@
== Welcome to Rails
== Welcome to \Rails
Rails is a web-application framework that includes everything needed to create
database-backed web applications according to the {Model-View-Controller (MVC)}[http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller] pattern.
\Rails is a web-application framework that includes everything needed to create
database-backed web applications according to the Model-View-Control pattern.
Understanding the MVC pattern is key to understanding Rails. MVC divides your application
into three layers, each with a specific responsibility.
This pattern splits the view (also called the presentation) into "dumb"
templates that are primarily responsible for inserting pre-built data in between
HTML tags. The model contains the "smart" domain objects (such as Account,
Product, Person, Post) that holds all the business logic and knows how to
persist themselves to a database. The controller handles the incoming requests
(such as Save New Account, Update Product, Show Post) by manipulating the model
and directing data to the view.
The View layer is composed of "templates" that are responsible for providing
appropriate representations of your application's resources. Templates
can come in a variety of formats, but most view templates are \HTML with embedded Ruby
code (.erb files).
In \Rails, the model is handled by what's called an object-relational mapping
layer entitled Active Record. This layer allows you to present the data from
database rows as objects and embellish these data objects with business logic
methods. You can read more about Active Record in its
{README}[link:files/activerecord/README_rdoc.html].
The Model layer represents your domain model (such as Account, Product, Person, Post)
and encapsulates the business logic that is specific to your application. In Rails,
database-backed model classes are derived from ActiveRecord::Base. Active Record allows
you to present the data from database rows as objects and embellish these data objects
with business logic methods. Although most Rails models are backed by a database, models
can also be ordinary Ruby classes, or Ruby classes that implement a set of interfaces as
provided by the ActiveModel module. You can read more about Active Record in its
{README}[link:/rails/rails/blob/master/activerecord/README.rdoc].
The controller and view are handled by the Action Pack, which handles both
layers by its two parts: Action View and Action Controller. These two layers
are bundled in a single package due to their heavy interdependence. This is
unlike the relationship between the Active Record and Action Pack that is much
more separate. Each of these packages can be used independently outside of
\Rails. You can read more about Action Pack in its
{README}[link:files/actionpack/README_rdoc.html].
The Controller layer is responsible for handling incoming HTTP requests and providing a
suitable response. Usually this means returning \HTML, but Rails controllers can also
generate XML, JSON, PDFs, mobile-specific views, and more. Controllers manipulate models
and render view templates in order to generate the appropriate HTTP response.
In Rails, the Controller and View layers are handled together by Action Pack.
These two layers are bundled in a single package due to their heavy interdependence.
This is unlike the relationship between Active Record and Action Pack which are
independent. Each of these packages can be used independently outside of Rails. You
can read more about Action Pack in its {README}[link:/rails/rails/blob/master/actionpack/README.rdoc].
== Getting Started
1. Install Rails at the command prompt if you haven't yet:
1. Install \Rails at the command prompt if you haven't yet:
gem install rails
2. At the command prompt, create a new Rails application:
2. At the command prompt, create a new \Rails application:
rails new myapp
@@ -49,29 +44,25 @@ can read more about Action Pack in its {README}[link:/rails/rails/blob/master/ac
Run with <tt>--help</tt> for options.
4. Go to http://localhost:3000 and you'll see:
4. Go to http://localhost:3000/ and you'll see:
"Welcome aboard: You're riding Ruby on Rails!"
5. Follow the guidelines to start developing your application. You may find the following resources handy:
5. Follow the guidelines to start developing your application. You can find the following resources handy:
* The README file created within your application.
* The {Getting Started with Rails}[http://guides.rubyonrails.org/getting_started.html].
* The {Ruby on Rails Tutorial}[http://railstutorial.org/book].
* The {Ruby on Rails Guides}[http://guides.rubyonrails.org].
* The {API Documentation}[http://api.rubyonrails.org].
* The {Ruby on Rails guides}[http://guides.rubyonrails.org/getting_started.html].
* The {API documentation}[http://api.rubyonrails.org].
== Contributing
We encourage you to contribute to Ruby on Rails! Please check out the {Contributing to Rails
guide}[http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html] for guidelines about how
We encourage you to contribute to Ruby on \Rails! Please check out the {Contributing to Rails
guide}[http://edgeguides.rubyonrails.org/contributing_to_rails.html] for guidelines about how
to proceed. {Join us}[http://contributors.rubyonrails.org]!
== Build Status {<img src="https://secure.travis-ci.org/rails/rails.png"/>}[http://travis-ci.org/rails/rails]
== Dependency Status {<img src="https://gemnasium.com/rails/rails.png?travis"/>}[https://gemnasium.com/rails/rails]
== License
Ruby on Rails is released under the MIT license.
Ruby on \Rails is released under the MIT license.

View File

@@ -1,238 +0,0 @@
= Releasing Rails
In this document, we'll cover the steps necessary to release Rails. Each
section contains steps to take during that time before the release. The times
suggested in each header are just that: suggestions. However, they should
really be considered as minimums.
== 10 Days before release
Today is mostly coordination tasks. Here are the things you must do today:
=== Is the CI green? If not, make it green. (See "Fixing the CI")
Do not release with a Red CI. You can find the CI status here:
http://travis-ci.org/#!/rails/rails
=== Is Sam Ruby happy? If not, make him happy.
Sam Ruby keeps a test suite that makes sure the code samples in his book (Agile
Web Development with Rails) all work. These are valuable integration tests
for Rails. You can check the status of his tests here:
http://intertwingly.net/projects/dashboard.html
Do not release with Red AWDwR tests.
=== Are the postgres tests green? If not, make them green
Currently Travis CI doesn't run the Active Record postgres tests. They are
working to resolve this, but in the mean time, it is crucial to ensure that
the tests are still green before release.
=== Do we have any git dependencies? If so, contact those authors.
Having git dependencies indicates that we depend on unreleased code.
Obviously rails cannot be released when it depends on unreleased code.
Contact the authors of those particular gems and work out a release date that
suits them.
=== Contact the security team (either Koz or tenderlove)
Let them know of your plans to release. There may be security issues to be
addressed, and that can impact your release date.
=== Notify implementors.
Ruby implementors have high stakes in making sure Rails works. Be kind and
give them a heads up that Rails will be released soonish.
Send an email just giving a heads up about the upcoming release to these
lists:
* team@jruby.org
* community@rubini.us
* rubyonrails-core@googlegroups.com
Implementors will love you and help you.
== 3 Days before release
This is when you should release the release candidate. Here are your tasks
for today:
=== Is the CI green? If not, make it green.
=== Is Sam Ruby happy? If not, make him happy.
=== Are the postgres tests green? If not, make them green
=== Contact the security team. CVE emails must be sent on this day.
=== Create a release branch.
From the stable branch, create a release branch. For example, if you're
releasing Rails 3.0.10, do this:
[aaron@higgins rails (3-0-stable)]$ git checkout -b 3-0-10
Switched to a new branch '3-0-10'
[aaron@higgins rails (3-0-10)]$
=== Update each CHANGELOG.
Many times commits are made without the CHANGELOG being updated. You should
review the commits since the last release, and fill in any missing information
for each CHANGELOG.
You can review the commits for the 3.0.10 release like this:
[aaron@higgins rails (3-0-10)]$ git log v3.0.9..
If you're doing a stable branch release, you should also ensure that all of
the CHANGELOG entries in the stable branch are also synced to the master
branch.
=== Update the RAILS_VERSION file to include the RC.
=== Build and test the gem.
Run `rake install` to generate the gems and install them locally. Then try
generating a new app and ensure that nothing explodes.
This will stop you from looking silly when you push an RC to rubygems.org and
then realise it is broken.
=== Release the gem.
IMPORTANT: Due to YAML parse problems on the rubygems.org server, it is safest
to use Ruby 1.8 when releasing.
Run `rake release`. This will populate the gemspecs with data from
RAILS_VERSION, commit the changes, tag it, and push the gems to rubygems.org.
Here are the commands that `rake release` should use, so you can understand
what to do in case anything goes wrong:
$ rake all:build
$ git commit -am'updating RAILS_VERSION'
$ git tag -m'tagging rc release' v3.0.10.rc1
$ git push
$ git push --tags
$ for i in $(ls dist); do gem push $i; done
=== Send Rails release announcements
Write a release announcement that includes the version, changes, and links to
github where people can find the specific commit list. Here are the mailing
lists where you should announce:
* rubyonrails-core@googlegroups.com
* rubyonrails-talk@googlegroups.com
* ruby-talk@ruby-lang.org
Use markdown format for your announcement. Remember to ask people to report
issues with the release candidate to the rails-core mailing list.
IMPORTANT: If any users experience regressions when using the release
candidate, you *must* postpone the release. Bugfix releases *should not*
break existing applications.
=== Post the announcement to the Rails blog.
If you used markdown format for your email, you can just paste it in to the
blog.
* http://weblog.rubyonrails.org
=== Post the announcement to the Rails twitter account.
== Time between release candidate and actual release
Check the rails-core mailing list and the github issue list for regressions in
the RC.
If any regressions are found, fix the regressions and repeat the release
candidate process. We will not release the final until 72 hours after the
last release candidate has been pushed. This means that if users find
regressions, the scheduled release date must be postponed.
When you fix the regressions, do not create a new branch. Fix them on the
stable branch, then cherry pick the commit to your release branch. No other
commits should be added to the release branch besides regression fixing commits.
== Day of release
Many of these steps are the same as for the release candidate, so if you need
more explanation on a particular step, so the RC steps.
Today, do this stuff in this order:
* Apply security patches to the release branch
* Update CHANGELOG with security fixes.
* Update RAILS_VERSION to remove the rc
* Build and test the gem
* Release the gems
* Email security lists
* Email general announcement lists
=== Emailing the rails security announce list
Email the security announce list once for each vulnerability fixed.
You can do this, or ask the security team to do it.
Email the security reports to:
* rubyonrails-security@googlegroups.com
* linux-distros@vs.openwall.org
Be sure to note the security fixes in your announcement along with CVE numbers
and links to each patch. Some people may not be able to upgrade right away,
so we need to give them the security fixes in patch form.
* Blog announcements
* Twitter announcements
* Merge the release branch to the stable branch.
* Drink beer (or other cocktail)
== Misc
=== Fixing the CI
There are two simple steps for fixing the CI:
1. Identify the problem
2. Fix it
Repeat these steps until the CI is green.
=== Manually trigger docs generation
We have a post-receive hook in GitHub that calls the docs server on pushes.
It triggers generation and publication of edge docs, updates the contrib app,
and generates and publishes stable docs if a new stable tag is detected.
The hook unfortunately is not invoked by tag pushing, so once the new stable
tag has been pushed to origin, please run
rake publish_docs
You should see something like this:
Rails master hook tasks scheduled:
* updates the local checkout
* updates Rails Contributors
* generates and publishes edge docs
If a new stable tag is detected it also
* generates and publishes stable docs
This needs typically a few minutes.
Note you do not need to specify the tag, the docs server figures it out.
Also, don't worry if you call that multiple times or the hook is triggered
again by some immediate regular push, if the scripts are running new calls
are just queued (in a queue of size 1).

148
Rakefile Executable file → Normal file
View File

@@ -1,17 +1,34 @@
#!/usr/bin/env rake
gem 'rdoc', '>= 2.5.10'
require 'rdoc'
require 'rake'
require 'rdoc/task'
require 'sdoc'
require 'net/http'
require 'rake/gempackagetask'
$:.unshift File.expand_path('..', __FILE__)
require "tasks/release"
# RDoc skips some files in the Rails tree due to its binary? predicate. This is a quick
# hack for edge docs, until we decide which is the correct way to address this issue.
# If not fixed in RDoc itself, via an option or something, we should probably move this
# to railties and use it also in doc:rails.
def hijack_rdoc!
require "rdoc/parser"
class << RDoc::Parser
def binary?(file)
s = File.read(file, 1024) or return false
desc "Build gem files for all projects"
task :build => "all:build"
desc "Release all gems to gemcutter and create a tag"
task :release => "all:release"
if s[0, 2] == Marshal.dump('')[0, 2] then
true
elsif file =~ /erb\.rb$/ then
false
elsif s.index("\x00") then # ORIGINAL is s.scan(/<%|%>/).length >= 4 || s.index("\x00")
true
elsif 0.respond_to? :fdiv then
s.count("^ -~\t\r\n").fdiv(s.size) > 0.3
else # HACK 1.8.6
(s.count("^ -~\t\r\n").to_f / s.size) > 0.3
end
end
end
end
PROJECTS = %w(activesupport activemodel actionpack actionmailer activeresource activerecord railties)
@@ -37,6 +54,27 @@ task :smoke do
system %(cd activerecord && #{$0} sqlite3:isolated_test)
end
spec = eval(File.read('rails.gemspec'))
Rake::GemPackageTask.new(spec) do |pkg|
pkg.gem_spec = spec
end
desc "Release all gems to gemcutter. Package rails, package & push components, then push rails"
task :release => :release_projects do
require 'rake/gemcutter'
Rake::Gemcutter::Tasks.new(spec).define
Rake::Task['gem:push'].invoke
end
desc "Release all components to gemcutter."
task :release_projects => :package do
errors = []
PROJECTS.each do |project|
system(%(cd #{project} && #{$0} release)) || errors << project
end
fail("Errors in #{errors.join(', ')}") unless errors.empty?
end
desc "Install gems for all projects."
task :install => :gem do
version = File.read("RAILS_VERSION").strip
@@ -50,72 +88,35 @@ end
desc "Generate documentation for the Rails framework"
RDoc::Task.new do |rdoc|
RDOC_MAIN = 'RDOC_MAIN.rdoc'
# This is a hack.
#
# Backslashes are needed to prevent RDoc from autolinking "Rails" to the
# documentation of the Rails module. On the other hand, as of this
# writing README.rdoc is displayed in the front page of the project in
# GitHub, where backslashes are shown and look weird.
#
# The temporary solution is to have a README.rdoc without backslashes for
# GitHub, and gsub it to generate the main page of the API.
#
# Also, relative links in GitHub have to point to blobs, whereas in the API
# they need to point to files.
#
# The idea for the future is to have totally different files, since the
# API is no longer a generic entry point to Rails and deserves a
# dedicated main page specifically thought as an API entry point.
rdoc.before_running_rdoc do
rdoc_main = File.read('README.rdoc')
# The ^(?=\S) assertion prevents code blocks from being processed,
# since no autolinking happens there and RDoc displays the backslash
# otherwise.
rdoc_main.gsub!(/^(?=\S).*?\b(?=Rails)\b/) { "#$&\\" }
rdoc_main.gsub!(%r{link:/rails/rails/blob/master/(\w+)/README\.rdoc}, "link:files/\\1/README_rdoc.html")
# Remove Travis and Gemnasium status images from API pages. Only GitHub
# README page gets these images. Travis' https build image is used to avoid
# GitHub caching: http://about.travis-ci.org/docs/user/status-images
rdoc_main.gsub!(%r{^== (Build|Dependency) Status.*}, '')
File.open(RDOC_MAIN, 'w') do |f|
f.write(rdoc_main)
end
rdoc.rdoc_files.include(RDOC_MAIN)
end
hijack_rdoc!
rdoc.rdoc_dir = 'doc/rdoc'
rdoc.title = "Ruby on Rails Documentation"
rdoc.options << '-f' << 'sdoc'
rdoc.options << '-T' << 'rails'
rdoc.options << '-e' << 'UTF-8'
rdoc.options << '-g' # SDoc flag, link methods to GitHub
rdoc.options << '-m' << RDOC_MAIN
rdoc.options << '-f' << 'horo'
rdoc.options << '-c' << 'utf-8'
rdoc.options << '-m' << 'README.rdoc'
rdoc.rdoc_files.include('railties/CHANGELOG.md')
rdoc.rdoc_files.include('README.rdoc')
rdoc.rdoc_files.include('railties/CHANGELOG')
rdoc.rdoc_files.include('railties/MIT-LICENSE')
rdoc.rdoc_files.include('railties/README.rdoc')
rdoc.rdoc_files.include('railties/lib/**/*.rb')
rdoc.rdoc_files.exclude('railties/lib/rails/generators/**/templates/**/*.rb')
rdoc.rdoc_files.exclude('railties/lib/rails/generators/**/templates/*')
rdoc.rdoc_files.include('activerecord/README.rdoc')
rdoc.rdoc_files.include('activerecord/CHANGELOG.md')
rdoc.rdoc_files.include('activerecord/CHANGELOG')
rdoc.rdoc_files.include('activerecord/lib/active_record/**/*.rb')
rdoc.rdoc_files.exclude('activerecord/lib/active_record/vendor/*')
rdoc.rdoc_files.include('activeresource/README.rdoc')
rdoc.rdoc_files.include('activeresource/CHANGELOG.md')
rdoc.rdoc_files.include('activeresource/CHANGELOG')
rdoc.rdoc_files.include('activeresource/lib/active_resource.rb')
rdoc.rdoc_files.include('activeresource/lib/active_resource/*')
rdoc.rdoc_files.include('actionpack/README.rdoc')
rdoc.rdoc_files.include('actionpack/CHANGELOG.md')
rdoc.rdoc_files.include('actionpack/CHANGELOG')
rdoc.rdoc_files.include('actionpack/lib/abstract_controller/**/*.rb')
rdoc.rdoc_files.include('actionpack/lib/action_controller/**/*.rb')
rdoc.rdoc_files.include('actionpack/lib/action_dispatch/**/*.rb')
@@ -123,18 +124,17 @@ RDoc::Task.new do |rdoc|
rdoc.rdoc_files.exclude('actionpack/lib/action_controller/vendor/*')
rdoc.rdoc_files.include('actionmailer/README.rdoc')
rdoc.rdoc_files.include('actionmailer/CHANGELOG.md')
rdoc.rdoc_files.include('actionmailer/CHANGELOG')
rdoc.rdoc_files.include('actionmailer/lib/action_mailer/base.rb')
rdoc.rdoc_files.include('actionmailer/lib/action_mailer/mail_helper.rb')
rdoc.rdoc_files.exclude('actionmailer/lib/action_mailer/vendor/*')
rdoc.rdoc_files.include('activesupport/README.rdoc')
rdoc.rdoc_files.include('activesupport/CHANGELOG.md')
rdoc.rdoc_files.include('activesupport/CHANGELOG')
rdoc.rdoc_files.include('activesupport/lib/active_support/**/*.rb')
rdoc.rdoc_files.exclude('activesupport/lib/active_support/vendor/*')
rdoc.rdoc_files.include('activemodel/README.rdoc')
rdoc.rdoc_files.include('activemodel/CHANGELOG.md')
rdoc.rdoc_files.include('activemodel/CHANGELOG')
rdoc.rdoc_files.include('activemodel/lib/active_model/**/*.rb')
end
@@ -172,27 +172,3 @@ task :update_versions do
end
end
end
#
# We have a webhook configured in Github that gets invoked after pushes.
# This hook triggers the following tasks:
#
# * updates the local checkout
# * updates Rails Contributors
# * generates and publishes edge docs
# * if there's a new stable tag, generates and publishes stable docs
#
# Everything is automated and you do NOT need to run this task normally.
#
# We publish a new version by tagging, and pushing a tag does not trigger
# that webhook. Stable docs would be updated by any subsequent regular
# push, but if you want that to happen right away just run this.
#
desc 'Publishes docs, run this AFTER a new stable tag has been pushed'
task :publish_docs do
Net::HTTP.new('api.rubyonrails.org', 8080).start do |http|
request = Net::HTTP::Post.new('/rails-master-hook')
response = http.request(request)
puts response.body
end
end

419
actionmailer/CHANGELOG Normal file
View File

@@ -0,0 +1,419 @@
*Rails 3.0.2 (November 15, 2010)*
* No changes.
*Rails 3.0.1 (October 15, 2010)*
* No Changes.
*Rails 3.0.0 (August 29, 2010)*
* subject is automatically looked up on I18n using mailer_name and action_name as scope as in t(".subject") [JK]
* Changed encoding behaviour of mail, so updated tests in actionmailer and bumped mail version to 2.2.1 [ML]
* Added ability to pass Proc objects to the defaults hash [ML]
* Removed all quoting.rb type files from ActionMailer and put Mail 2.2.0 in instead [ML]
* Lot of updates to various test cases that now work better with the new Mail and so have different expectations
* Added interceptors and observers from Mail [ML]
ActionMailer::Base.register_interceptor calls Mail.register_interceptor
ActionMailer::Base.register_observer calls Mail.register_observer
* Mail::Part now no longer has nil as a default charset, it is always set to something, and defaults to UTF-8
* Added explict setting of charset in set_fields! method to make sure Mail has the user defined default
* Removed quoting.rb and refactored for Mail to take responsibility of all quoting and auto encoding requirements for the header.
* Fixed several tests which had incorrect encoding.
* Changed all utf-8 to UTF-8 for consistency
* Whole new API added with tests. See base.rb for full details. Old API is deprecated.
* The Mail::Message class has helped methods for all the field types that return 'common' defaults for the common use case, so to get the subject, mail.subject will give you a string, mail.date will give you a DateTime object, mail.from will give you an array of address specs (mikel@test.lindsaar.net) etc. If you want to access the field object itself, call mail[:field_name] which will return the field object you want, which you can then chain, like mail[:from].formatted
* Mail#content_type now returns the content_type field as a string. If you want the mime type of a mail, then you call Mail#mime_type (eg, text/plain), if you want the parameters of the content type field, you call Mail#content_type_parameters which gives you a hash, eg {'format' => 'flowed', 'charset' => 'utf-8'}
* ActionMailer::Base :default_implicit_parts_order now is in the sequence of the order you want, no reversing of ordering takes place. The default order now is text/plain, then text/enriched, then text/html and then any other part that is not one of these three.
* Mail does not have "quoted_body", "quoted_subject" etc. All of these are accessed via body.encoded, subject.encoded etc
* Every object in a Mail object returns an object, never a string. So Mail.body returns a Mail::Body class object, need to call #encoded or #decoded to get the string you want.
* Mail::Message#set_content_type does not exist, it is simply Mail::Message#content_type
* Every mail message gets a unique message_id unless you specify one, had to change all the tests that check for equality with expected.encoded == actual.encoded to first replace their message_ids with control values
* Mail now has a proper concept of parts, remove the ActionMailer::Part and ActionMailer::PartContainer classes
* Calling #encoded on any object returns it as a string ready to go into the output stream of an email, this means it includes the \r\n at the end of the lines and the object is pre-wrapped with \r\n\t if it is a header field. Also, the "encoded" value includes the field name if it is a header field.
* Attachments are only the actual attachment, with filename etc. A part contains an attachment. The part has the content_type etc. So attachments.last.content_type is invalid. But parts.last.content_type
* There is no idea of a "sub_head" in Mail. A part is just a Message with some extra functionality, so it just has a "header" like a normal mail message
*2.3.2 [Final] (March 15, 2009)*
* Fixed that ActionMailer should send correctly formatted Return-Path in MAIL FROM for SMTP #1842 [Matt Jones]
* Fixed RFC-2045 quoted-printable bug #1421 [squadette]
* Fixed that no body charset would be set when there are attachments present #740 [Paweł Kondzior]
*2.2.1 [RC2] (November 14th, 2008)*
* Turn on STARTTLS if it is available in Net::SMTP (added in Ruby 1.8.7) and the SMTP server supports it (This is required for Gmail's SMTP server) #1336 [Grant Hollingworth]
*2.2.0 [RC1] (October 24th, 2008)*
* Add layout functionality to mailers [Pratik Naik]
Mailer layouts behaves just like controller layouts, except layout names need to
have '_mailer' postfix for them to be automatically picked up.
*2.1.0 (May 31st, 2008)*
* Fixed that a return-path header would be ignored #7572 [joost]
* Less verbose mail logging: just recipients for :info log level; the whole email for :debug only. #8000 [iaddict, Tarmo Tänav]
* Updated TMail to version 1.2.1 [Mikel Lindsaar]
* Fixed that you don't have to call super in ActionMailer::TestCase#setup #10406 [jamesgolick]
*2.0.2* (December 16th, 2007)
* Included in Rails 2.0.2
*2.0.1* (December 7th, 2007)
* Update ActionMailer so it treats ActionView the same way that ActionController does. Closes #10244 [Rick Olson]
* Pass the template_root as an array as ActionView's view_path
* Request templates with the "#{mailer_name}/#{action}" as opposed to just "#{action}"
* Fixed that partials would be broken when using text.plain.erb as the extension #10130 [java]
* Update README to use new smtp settings configuration API. Closes #10060 [psq]
* Allow ActionMailer subclasses to individually set their delivery method (so two subclasses can have different delivery methods) #10033 [Zach Dennis]
* Update TMail to v1.1.0. Use an updated version of TMail if available. [Mikel Lindsaar]
* Introduce a new base test class for testing Mailers. ActionMailer::TestCase [Michael Koziarski]
* Fix silent failure of rxml templates. #9879 [jstewart]
* Fix attachment decoding when using the TMail C extension. #7861 [orangechicken]
* Increase mail delivery test coverage. #8692 [Kamal Fariz Mahyuddin]
* Register alternative template engines using ActionMailer::Base.register_template_extension('haml'). #7534 [cwd, Josh Peek]
* Only load ActionController::UrlWriter if ActionController is present [Rick Olson]
* Make sure parsed emails recognized attachments nested inside multipart parts. #6714 [Jamis Buck]
* Allow mailer actions named send by using __send__ internally. #6467 [iGEL]
* Add assert_emails and assert_no_emails to test the number of emails delivered. #6479 [Jonathan Viney]
# Assert total number of emails delivered:
assert_emails 0
ContactMailer.deliver_contact
assert_emails 1
# Assert number of emails delivered within a block:
assert_emails 1 do
post :signup, :name => 'Jonathan'
end
*1.3.3* (March 12th, 2007)
* Depend on Action Pack 1.13.3
*1.3.2* (February 5th, 2007)
* Deprecate server_settings renaming it to smtp_settings, add sendmail_settings to allow you to override the arguments to and location of the sendmail executable. [Michael Koziarski]
*1.3.1* (January 16th, 2007)
* Depend on Action Pack 1.13.1
*1.3.0* (January 16th, 2007)
* Make mime version default to 1.0. closes #2323 [ror@andreas-s.net]
* Make sure quoted-printable text is decoded correctly when only portions of the text are encoded. closes #3154. [jon@siliconcircus.com]
* Make sure DOS newlines in quoted-printable text are normalized to unix newlines before unquoting. closes #4166 and #4452. [Jamis Buck]
* Fixed that iconv decoding should catch InvalidEncoding #3153 [jon@siliconcircus.com]
* Tighten rescue clauses. #5985 [james@grayproductions.net]
* Automatically included ActionController::UrlWriter, such that URL generation can happen within ActionMailer controllers. [David Heinemeier Hansson]
* Replace Reloadable with Reloadable::Deprecated. [Nicholas Seckar]
* Mailer template root applies to a class and its subclasses rather than acting globally. #5555 [somekool@gmail.com]
* Resolve action naming collision. #5520 [ssinghi@kreeti.com]
* ActionMailer::Base documentation rewrite. Closes #4991 [Kevin Clark, Marcel Molina Jr.]
* Replace alias method chaining with Module#alias_method_chain. [Marcel Molina Jr.]
* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.]
* Correct spurious documentation example code which results in a SyntaxError. [Marcel Molina Jr.]
*1.2.1* (April 6th, 2006)
* Be part of Rails 1.1.1
*1.2.0* (March 27th, 2006)
* Nil charset caused subject line to be improperly quoted in implicitly multipart messages #2662 [ehalvorsen+rails@runbox.com]
* Parse content-type apart before using it so that sub-parts of the header can be set correctly #2918 [Jamis Buck]
* Make custom headers work in subparts #4034 [elan@bluemandrill.com]
* Template paths with dot chars in them no longer mess up implicit template selection for multipart messages #3332 [Chad Fowler]
* Make sure anything with content-disposition of "attachment" is passed to the attachment presenter when parsing an email body [Jamis Buck]
* Make sure TMail#attachments includes anything with content-disposition of "attachment", regardless of content-type [Jamis Buck]
*1.1.5* (December 13th, 2005)
* Become part of Rails 1.0
*1.1.4* (December 7th, 2005)
* Rename Version constant to VERSION. #2802 [Marcel Molina Jr.]
* Stricter matching for implicitly multipart filenames excludes files ending in unsupported extensions (such as foo.rhtml.bak) and without a two-part content type (such as foo.text.rhtml or foo.text.really.plain.rhtml). #2398 [Dave Burt <dave@burt.id.au>, Jeremy Kemper]
*1.1.3* (November 7th, 2005)
* Allow Mailers to have custom initialize methods that set default instance variables for all mail actions #2563 [mrj@bigpond.net.au]
*1.1.2* (October 26th, 2005)
* Upgraded to Action Pack 1.10.2
*1.1.1* (October 19th, 2005)
* Upgraded to Action Pack 1.10.1
*1.1.0* (October 16th, 2005)
* Update and extend documentation (rdoc)
* Minero Aoki made TMail available to Rails/ActionMailer under the MIT license (instead of LGPL) [RubyConf '05]
* Austin Ziegler made Text::Simple available to Rails/ActionMailer under a MIT-like licens [See rails ML, subject "Text::Format Licence Exception" on Oct 15, 2005]
* Fix vendor require paths to prevent files being required twice
* Don't add charset to content-type header for a part that contains subparts (for AOL compatibility) #2013 [John Long]
* Preserve underscores when unquoting message bodies #1930
* Encode multibyte characters correctly #1894
* Multipart messages specify a MIME-Version header automatically #2003 [John Long]
* Add a unified render method to ActionMailer (delegates to ActionView::Base#render)
* Move mailer initialization to a separate (overridable) method, so that subclasses may alter the various defaults #1727
* Look at content-location header (if available) to determine filename of attachments #1670
* ActionMailer::Base.deliver(email) had been accidentally removed, but was documented in the Rails book #1849
* Fix problem with sendmail delivery where headers should be delimited by \n characters instead of \r\n, which confuses some mail readers #1742 [Kent Sibilev]
*1.0.1* (11 July, 2005)
* Bind to Action Pack 1.9.1
*1.0.0* (6 July, 2005)
* Avoid adding nil header values #1392
* Better multipart support with implicit multipart/alternative and sorting of subparts [John Long]
* Allow for nested parts in multipart mails #1570 [Flurin Egger]
* Normalize line endings in outgoing mail bodies to "\n" #1536 [John Long]
* Allow template to be explicitly specified #1448 [tuxie@dekadance.se]
* Allow specific "multipart/xxx" content-type to be set on multipart messages #1412 [Flurin Egger]
* Unquoted @ characters in headers are now accepted in spite of RFC 822 #1206
* Helper support (borrowed from ActionPack)
* Silently ignore Errno::EINVAL errors when converting text.
* Don't cause an error when parsing an encoded attachment name #1340 [lon@speedymac.com]
* Nested multipart message parts are correctly processed in TMail::Mail#body
* BCC headers are removed when sending via SMTP #1402
* Added 'content_type' accessor, to allow content type to be set on a per-message basis. content_type defaults to "text/plain".
* Silently ignore Iconv::IllegalSequence errors when converting text #1341 [lon@speedymac.com]
* Support attachments and multipart messages.
* Added new accessors for the various mail properties.
* Fix to only perform the charset conversion if a 'from' and a 'to' charset are given (make no assumptions about what the charset was) #1276 [Jamis Buck]
* Fix attachments and content-type problems #1276 [Jamis Buck]
* Fixed the TMail#body method to look at the content-transfer-encoding header and unquote the body according to the rules it specifies #1265 [Jamis Buck]
* Added unquoting even if the iconv lib can't be loaded--in that case, only the charset conversion is skipped #1265 [Jamis Buck]
* Added automatic decoding of base64 bodies #1214 [Jamis Buck]
* Added that delivery errors are caught in a way so the mail is still returned whether the delivery was successful or not
* Fixed that email address like "Jamis Buck, M.D." <wild.medicine@example.net> would cause the quoter to generate emails resulting in "bad address" errors from the mail server #1220 [Jamis Buck]
*0.9.1* (20th April, 2005)
* Depend on Action Pack 1.8.1
*0.9.0* (19th April, 2005)
* Added that deliver_* will now return the email that was sent
* Added that quoting to UTF-8 only happens if the characters used are in that range #955 [Jamis Buck]
* Fixed quoting for all address headers, not just to #955 [Jamis Buck]
* Fixed unquoting of emails that doesn't have an explicit charset #1036 [wolfgang@stufenlos.net]
*0.8.1* (27th March, 2005)
* Fixed that if charset was found that the end of a mime part declaration TMail would throw an error #919 [lon@speedymac.com]
* Fixed that TMail::Unquoter would fail to recognize quoting method if it was in lowercase #919 [lon@speedymac.com]
* Fixed that TMail::Encoder would fail when it attempts to parse e-mail addresses which are encoded using something other than the messages encoding method #919 [lon@speedymac.com]
* Added rescue for missing iconv library and throws warnings if subject/body is called on a TMail object without it instead
*0.8.0* (22th March, 2005)
* Added framework support for processing incoming emails with an Action Mailer class. See example in README.
*0.7.1* (7th March, 2005)
* Bind to newest Action Pack (1.5.1)
*0.7.0* (24th February, 2005)
* Added support for charsets for both subject and body. The default charset is now UTF-8 #673 [Jamis Buck]. Examples:
def iso_charset(recipient)
@recipients = recipient
@subject = "testing iso charsets"
@from = "system@loudthinking.com"
@body = "Nothing to see here."
@charset = "iso-8859-1"
end
def unencoded_subject(recipient)
@recipients = recipient
@subject = "testing unencoded subject"
@from = "system@loudthinking.com"
@body = "Nothing to see here."
@encode_subject = false
@charset = "iso-8859-1"
end
*0.6.1* (January 18th, 2005)
* Fixed sending of emails to use Tmail#from not the deprecated Tmail#from_address
*0.6* (January 17th, 2005)
* Fixed that bcc and cc should be settable through @bcc and @cc -- not just @headers["Bcc"] and @headers["Cc"] #453 [Eric Hodel]
* Fixed Action Mailer to be "warnings safe" so you can run with ruby -w and not get framework warnings #453 [Eric Hodel]
*0.5*
* Added access to custom headers, like cc, bcc, and reply-to #268 [Andreas Schwarz]. Example:
def post_notification(recipients, post)
@recipients = recipients
@from = post.author.email_address_with_name
@headers["bcc"] = SYSTEM_ADMINISTRATOR_EMAIL
@headers["reply-to"] = "notifications@example.com"
@subject = "[#{post.account.name} #{post.title}]"
@body["post"] = post
end
*0.4* (5)
* Consolidated the server configuration options into Base#server_settings= and expanded that with controls for authentication and more [Marten]
NOTE: This is an API change that could potentially break your application if you used the old application form. Please do change!
* Added Base#deliveries as an accessor for an array of emails sent out through that ActionMailer class when using the :test delivery option. [Jeremy Kemper]
* Added Base#perform_deliveries= which can be set to false to turn off the actual delivery of the email through smtp or sendmail.
This is especially useful for functional testing that shouldn't send off real emails, but still trigger delivery_* methods.
* Added option to specify delivery method with Base#delivery_method=. Default is :smtp and :sendmail is currently the only other option.
Sendmail is assumed to be present at "/usr/sbin/sendmail" if that option is used. [Kent Sibilev]
* Dropped "include TMail" as it added to much baggage into the default namespace (like Version) [Chad Fowler]
*0.3*
* First release

View File

@@ -1,123 +0,0 @@
## Rails 3.2.19 (Jul 2, 2014) ##
* No changes.
## Rails 3.2.18 (May 6, 2014) ##
* No changes.
## Rails 3.2.17 (Feb 18, 2014) ##
* No changes.
## Rails 3.2.16 (Dec 3, 2013) ##
* No changes.
## Rails 3.2.15 (Oct 16, 2013) ##
* No changes.
## Rails 3.2.14 (Jul 22, 2013) ##
* No changes.
## Rails 3.2.13 (Mar 18, 2013) ##
* No changes.
## Rails 3.2.12 (Feb 11, 2013) ##
* No changes.
## Rails 3.2.11 (Jan 8, 2013) ##
* No changes.
## Rails 3.2.10 (Jan 2, 2013) ##
* No changes.
## Rails 3.2.9 (Nov 12, 2012) ##
* The return value from mailer methods is no longer relevant. This fixes a bug,
which was introduced with 3.2.9.
Backport #8450
Fix #8448
class ExampleMailer < ActionMailer::Base
# in 3.2.9, returning a falsy value from a mailer action, prevented the email from beeing sent.
# With 3.2.10 the return value is no longer relevant. If you call mail() the email will be sent.
def nil_returning_mailer_action
mail()
nil
end
end
*Yves Senn*
## Rails 3.2.9 (Nov 12, 2012) ##
* Do not render views when mail() isn't called.
Fix #7761
*Yves Senn*
## Rails 3.2.8 (Aug 9, 2012) ##
* No changes.
## Rails 3.2.7 (Jul 26, 2012) ##
* No changes.
## Rails 3.2.6 (Jun 12, 2012) ##
* No changes.
## Rails 3.2.5 (Jun 1, 2012) ##
* No changes.
## Rails 3.2.4 (May 31, 2012) ##
* No changes.
## Rails 3.2.3 (March 30, 2012) ##
* Upgrade mail version to 2.4.3 *ML*
## Rails 3.2.2 (March 1, 2012) ##
* No changes.
## Rails 3.2.1 (January 26, 2012) ##
* No changes.
## Rails 3.2.0 (January 20, 2012) ##
* Upgrade mail version to 2.4.0 *ML*
* Remove Old ActionMailer API *Josh Kalderimis*
Please check [3-1-stable](https://github.com/rails/rails/blob/3-1-stable/actionmailer/CHANGELOG.md) for previous changes.

View File

@@ -1,4 +1,4 @@
Copyright (c) 2004-2011 David Heinemeier Hansson
Copyright (c) 2004-2010 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

View File

@@ -10,7 +10,7 @@ Mail gem. It provides a way to make emails using templates in the same
way that Action Controller renders views using templates.
Additionally, an Action Mailer class can be used to process incoming email,
such as allowing a blog to accept new posts from an email (which could even
such as allowing a weblog to accept new posts from an email (which could even
have been sent from a phone).
== Sending emails
@@ -32,7 +32,7 @@ This can be as simple as:
end
The body of the email is created by using an Action View template (regular
ERB) that has the instance variables that are declared in the mailer action.
ERb) that has the instance variables that are declared in the mailer action.
So the corresponding body template for the method above could look like this:
@@ -59,9 +59,7 @@ generated would look like this:
Mr. david@loudthinking.com
Thank you for signing up!
In previous version of Rails you would call <tt>create_method_name</tt> and
In previous version of rails you would call <tt>create_method_name</tt> and
<tt>deliver_method_name</tt>. Rails 3.0 has a much simpler interface, you
simply call the method and optionally call +deliver+ on the return value.
@@ -74,25 +72,12 @@ Or you can just chain the methods together like:
Notifier.welcome.deliver # Creates the email and sends it immediately
== Setting defaults
It is possible to set default values that will be used in every method in your Action Mailer class. To implement this functionality, you just call the public class method <tt>default</tt> which you get for free from ActionMailer::Base. This method accepts a Hash as the parameter. You can use any of the headers e-mail messages has, like <tt>:from</tt> as the key. You can also pass in a string as the key, like "Content-Type", but Action Mailer does this out of the box for you, so you won't need to worry about that. Finally it is also possible to pass in a Proc that will get evaluated when it is needed.
Note that every value you set with this method will get over written if you use the same key in your mailer method.
Example:
class Authenticationmailer < ActionMailer::Base
default :from => "awesome@application.com", :subject => Proc.new { "E-mail was generated at #{Time.now}" }
.....
end
== Receiving emails
To receive emails, you need to implement a public instance method called <tt>receive</tt> that takes an
email object as its single parameter. The Action Mailer framework has a corresponding class method,
To receive emails, you need to implement a public instance method called <tt>receive</tt> that takes a
tmail object as its single parameter. The Action Mailer framework has a corresponding class method,
which is also called <tt>receive</tt>, that accepts a raw, unprocessed email as a string, which it then turns
into the email object and calls the receive instance method.
into the tmail object and calls the receive instance method.
Example:
@@ -104,7 +89,7 @@ Example:
)
if email.has_attachments?
email.attachments.each do |attachment|
for attachment in email.attachments
page.attachments.create({
:file => attachment, :description => email.subject
})
@@ -119,7 +104,7 @@ trivial case like this:
rails runner 'Mailman.receive(STDIN.read)'
However, invoking Rails in the runner for each mail to be received is very resource intensive. A single
instance of Rails should be run within a daemon, if it is going to be utilized to process more than just
instance of Rails should be run within a daemon if it is going to be utilized to process more than just
a limited number of email.
== Configuration
@@ -137,13 +122,13 @@ The Base class has the full list of configuration options. Here's an example:
== Download and installation
The latest version of Action Mailer can be installed with RubyGems:
The latest version of Action Mailer can be installed with Rubygems:
% [sudo] gem install actionmailer
Source code can be downloaded as part of the Rails project on GitHub
* https://github.com/rails/rails/tree/3-2-stable/actionmailer
* http://github.com/rails/rails/tree/master/actionmailer/
== License
@@ -155,9 +140,8 @@ Action Mailer is released under the MIT license.
API documentation is at
* http://api.rubyonrails.org
* http://api.rubyonrails.com
Bug reports and feature requests can be filed with the rest for the Ruby on Rails project here:
* https://github.com/rails/rails/issues
* https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets

8
actionmailer/Rakefile Executable file → Normal file
View File

@@ -1,7 +1,7 @@
#!/usr/bin/env rake
require 'rake'
require 'rake/testtask'
require 'rake/packagetask'
require 'rubygems/package_task'
require 'rake/gempackagetask'
desc "Default Task"
task :default => [ :test ]
@@ -17,14 +17,14 @@ namespace :test do
task :isolated do
ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
Dir.glob("test/**/*_test.rb").all? do |file|
sh(ruby, '-Ilib:test', file)
system(ruby, '-Ilib:test', file)
end or raise "Failures"
end
end
spec = eval(File.read('actionmailer.gemspec'))
Gem::PackageTask.new(spec) do |p|
Rake::GemPackageTask.new(spec) do |p|
p.gem_spec = spec
end

View File

@@ -6,19 +6,19 @@ Gem::Specification.new do |s|
s.version = version
s.summary = 'Email composition, delivery, and receiving framework (part of Rails).'
s.description = 'Email on Rails. Compose, deliver, receive, and test emails using the familiar controller/view pattern. First-class support for multipart email and attachments.'
s.license = 'MIT'
s.required_ruby_version = '>= 1.8.7'
s.author = 'David Heinemeier Hansson'
s.email = 'david@loudthinking.com'
s.homepage = 'http://www.rubyonrails.org'
s.rubyforge_project = 'actionmailer'
s.files = Dir['CHANGELOG.md', 'README.rdoc', 'MIT-LICENSE', 'lib/**/*']
s.files = Dir['CHANGELOG', 'README.rdoc', 'MIT-LICENSE', 'lib/**/*']
s.require_path = 'lib'
s.requirements << 'none'
s.has_rdoc = true
s.add_dependency('actionpack', version)
s.add_dependency('mail', '~> 2.5.4')
s.add_dependency('mail', '~> 2.2.9')
end

View File

@@ -1,5 +1,5 @@
#--
# Copyright (c) 2004-2011 David Heinemeier Hansson
# Copyright (c) 2004-2010 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -40,10 +40,13 @@ require 'active_support/lazy_load_hooks'
module ActionMailer
extend ::ActiveSupport::Autoload
autoload :AdvAttrAccessor
autoload :Collector
autoload :Base
autoload :DeliveryMethods
autoload :DeprecatedApi
autoload :MailHelper
autoload :OldApi
autoload :TestCase
autoload :TestHelper
end

View File

@@ -0,0 +1,26 @@
module ActionMailer
module AdvAttrAccessor #:nodoc:
def adv_attr_accessor(*names)
names.each do |name|
ivar = "@#{name}"
class_eval <<-ACCESSORS, __FILE__, __LINE__ + 1
def #{name}=(value)
#{ivar} = value
end
def #{name}(*args)
raise ArgumentError, "expected 0 or 1 parameters" unless args.length <= 1
if args.empty?
#{ivar} if instance_variable_names.include?(#{ivar.inspect})
else
#{ivar} = args.first
end
end
ACCESSORS
self.protected_instance_variables << ivar if self.respond_to?(:protected_instance_variables)
end
end
end
end

View File

@@ -1,10 +1,9 @@
require 'mail'
require 'action_mailer/tmail_compat'
require 'action_mailer/collector'
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/inflections'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/module/anonymous'
require 'active_support/core_ext/proc'
require 'action_mailer/log_subscriber'
module ActionMailer #:nodoc:
@@ -22,16 +21,16 @@ module ActionMailer #:nodoc:
#
# Examples:
#
# class Notifier < ActionMailer::Base
# default :from => 'no-reply@example.com',
# class Notifier < ActionMailer::Base
# default :from => 'no-reply@example.com',
# :return_path => 'system@example.com'
#
# def welcome(recipient)
# @account = recipient
# mail(:to => recipient.email_address_with_name,
# :bcc => ["bcc@example.com", "Order Watcher <watcher@example.com>"])
# end
# end
# def welcome(recipient)
# @account = recipient
# mail(:to => recipient.email_address_with_name,
# :bcc => ["bcc@example.com", "Order Watcher <watcher@example.com>"])
# end
# end
#
# Within the mailer method, you have access to the following methods:
#
@@ -57,7 +56,7 @@ module ActionMailer #:nodoc:
# will accept (any valid Email header including optional fields).
#
# The mail method, if not passed a block, will inspect your views and send all the views with
# the same name as the method, so the above action would send the +welcome.text.erb+ view
# the same name as the method, so the above action would send the +welcome.text.plain.erb+ view
# file as well as the +welcome.text.html.erb+ view file in a +multipart/alternative+ email.
#
# If you want to explicitly render only certain templates, pass a block:
@@ -88,7 +87,7 @@ module ActionMailer #:nodoc:
#
# 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
# <tt>app/views/notifier/welcome.text.erb</tt> would be used to generate the email.
# <tt>app/views/notifier/signup_notification.text.plain.erb</tt> would be used to generate the email.
#
# Variables defined in the model are accessible as instance variables in the view.
#
@@ -100,12 +99,12 @@ module ActionMailer #:nodoc:
# You can even use Action Pack helpers in these views. For example:
#
# You got a new note!
# <%= truncate(@note.body, :length => 25) %>
# <%= truncate(@note.body, 25) %>
#
# If you need to access the subject, from or the recipients in the view, you can do that through message object:
#
# You got a new note from <%= message.from %>!
# <%= truncate(@note.body, :length => 25) %>
# <%= truncate(@note.body, 25) %>
#
#
# = Generating URLs
@@ -122,19 +121,21 @@ module ActionMailer #:nodoc:
#
# <%= users_url(:host => "example.com") %>
#
# You should use the <tt>named_route_url</tt> style (which generates absolute URLs) and avoid using the
# <tt>named_route_path</tt> style (which generates relative URLs), since clients reading the mail will
# have no concept of a current URL from which to determine a relative path.
# You want to avoid using the <tt>name_of_route_path</tt> form of named routes because it doesn't
# make sense to generate relative URLs in email messages.
#
# It is also possible to set a default host that will be used in all mailers by setting the <tt>:host</tt>
# option as a configuration option in <tt>config/application.rb</tt>:
#
# config.action_mailer.default_url_options = { :host => "example.com" }
#
# When you decide to set a default <tt>:host</tt> for your mailers, then you need to make sure to use the
# <tt>:only_path => false</tt> option when using <tt>url_for</tt>. Since the <tt>url_for</tt> view helper
# will generate relative URLs by default when a <tt>:host</tt> option isn't explicitly provided, passing
# <tt>:only_path => false</tt> will ensure that absolute URLs are generated.
# Setting <tt>ActionMailer::Base.default_url_options</tt> directly is now deprecated, use the configuration
# option mentioned above to set the default host.
#
# If you do decide to set a default <tt>:host</tt> for your mailers you want to use the
# <tt>:only_path => false</tt> option when using <tt>url_for</tt>. This will ensure that absolute URLs are
# generated because the <tt>url_for</tt> view helper will, by default, generate relative URLs when a
# <tt>:host</tt> option isn't explicitly provided.
#
# = Sending mail
#
@@ -149,12 +150,12 @@ module ActionMailer #:nodoc:
#
# = Multipart Emails
#
# 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 a separate part to the message.
# 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.
#
# For example, if the following templates exist:
# * signup_notification.text.erb
# * signup_notification.text.plain.erb
# * signup_notification.text.html.erb
# * signup_notification.text.xml.builder
# * signup_notification.text.yaml.erb
@@ -179,7 +180,7 @@ module ActionMailer #:nodoc:
# end
# end
#
# Which will (if it had both a <tt>welcome.text.erb</tt> and <tt>welcome.text.html.erb</tt>
# Which will (if it had both a <tt>welcome.text.plain.erb</tt> and <tt>welcome.text.html.erb</tt>
# template in the view directory), send a complete <tt>multipart/mixed</tt> email with two parts,
# the first part being a <tt>multipart/alternative</tt> with the text and HTML email parts inside,
# and the second being a <tt>application/pdf</tt> with a Base64 encoded copy of the file.pdf book
@@ -213,15 +214,15 @@ module ActionMailer #:nodoc:
#
# = Observing and Intercepting Mails
#
# Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to
# register classes that are called during the mail delivery life cycle.
# Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to
# register objects that are called during the mail delivery life cycle.
#
# An observer class must implement the <tt>:delivered_email(message)</tt> method which will be
# An observer object must implement the <tt>:delivered_email(message)</tt> method which will be
# called once for every email sent after the email has been sent.
#
# An interceptor class must implement the <tt>:delivering_email(message)</tt> method which will be
# An interceptor object must implement the <tt>:delivering_email(message)</tt> method which will be
# called before the email is sent, allowing you to make modifications to the email before it hits
# the delivery agents. Your class should make any needed modifications directly to the passed
# the delivery agents. Your object should make and needed modifications directly to the passed
# in Mail::Message instance.
#
# = Default Hash
@@ -233,8 +234,8 @@ module ActionMailer #:nodoc:
# default :sender => 'system@example.com'
# end
#
# You can pass in any header value that a <tt>Mail::Message</tt> accepts. Out of the box,
# <tt>ActionMailer::Base</tt> sets the following:
# You can pass in any header value that a <tt>Mail::Message</tt>, out of the box, <tt>ActionMailer::Base</tt>
# sets the following:
#
# * <tt>:mime_version => "1.0"</tt>
# * <tt>:charset => "UTF-8",</tt>
@@ -245,7 +246,7 @@ module ActionMailer #:nodoc:
# but Action Mailer translates them appropriately and sets the correct values.
#
# As you can pass in any header, you need to either quote the header as a string, or pass it in as
# an underscored symbol, so the following will work:
# an underscorised symbol, so the following will work:
#
# class Notifier < ActionMailer::Base
# default 'Content-Transfer-Encoding' => '7bit',
@@ -272,7 +273,7 @@ module ActionMailer #:nodoc:
# = Configuration options
#
# These options are specified on the class level, like
# <tt>ActionMailer::Base.raise_delivery_errors = true</tt>
# <tt>ActionMailer::Base.template_root = "/my/templates"</tt>
#
# * <tt>default</tt> - You can pass this in at a class level as well as within the class itself as
# per the above section.
@@ -289,19 +290,13 @@ module ActionMailer #:nodoc:
# * <tt>:password</tt> - If your mail server requires authentication, set the password in this setting.
# * <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the
# authentication type here.
# This is a symbol and one of <tt>:plain</tt> (will send the password in the clear), <tt>:login</tt> (will
# send password Base64 encoded) or <tt>:cram_md5</tt> (combines a Challenge/Response mechanism to exchange
# information and a cryptographic Message Digest 5 algorithm to hash important information)
# This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>.
# * <tt>:enable_starttls_auto</tt> - When set to true, detects if STARTTLS is enabled in your SMTP server
# and starts to use it.
# * <tt>:openssl_verify_mode</tt> - When using TLS, you can set how OpenSSL checks the certificate. This is
# really useful if you need to validate a self-signed and/or a wildcard certificate. You can use the name
# of an OpenSSL verify constant ('none', 'peer', 'client_once','fail_if_no_peer_cert') or directly the
# constant (OpenSSL::SSL::VERIFY_NONE, OpenSSL::SSL::VERIFY_PEER,...).
#
# * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method.
# * <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.
# * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt> with <tt>-f sender@address</tt>
# * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt> with <tt>-f sender@addres</tt>
# added automatically before the message is sent.
#
# * <tt>file_settings</tt> - Allows you to override options for the <tt>:file</tt> delivery method.
@@ -312,16 +307,29 @@ module ActionMailer #:nodoc:
#
# * <tt>delivery_method</tt> - Defines a delivery method. Possible values are <tt>:smtp</tt> (default),
# <tt>:sendmail</tt>, <tt>:test</tt>, and <tt>:file</tt>. Or you may provide a custom delivery method
# object eg. MyOwnDeliveryMethodClass.new. See the Mail gem documentation on the interface you need to
# object eg. MyOwnDeliveryMethodClass.new. See the Mail gem documentation on the interface you need to
# implement for a custom delivery agent.
#
# * <tt>perform_deliveries</tt> - Determines whether emails are actually sent from Action Mailer when you
# call <tt>.deliver</tt> on an mail message or on an Action Mailer method. This is on by default but can
# call <tt>.deliver</tt> on an mail message or on an Action Mailer method. This is on by default but can
# be turned off to aid in functional testing.
#
# * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with
# <tt>delivery_method :test</tt>. Most useful for unit and functional testing.
#
# * <tt>default_charset</tt> - This is now deprecated, use the +default+ method above to
# set the default +:charset+.
#
# * <tt>default_content_type</tt> - This is now deprecated, use the +default+ method above
# to set the default +:content_type+.
#
# * <tt>default_mime_version</tt> - This is now deprecated, use the +default+ method above
# to set the default +:mime_version+.
#
# * <tt>default_implicit_parts_order</tt> - This is now deprecated, use the +default+ method above
# to set the default +:parts_order+. Parts Order is used when a message is built implicitly
# (i.e. multiple parts are assembled from templates which specify the content type in their
# filenames) this variable controls how the parts are ordered.
class Base < AbstractController::Base
include DeliveryMethods
abstract!
@@ -333,10 +341,14 @@ module ActionMailer #:nodoc:
include AbstractController::Translation
include AbstractController::AssetPaths
self.protected_instance_variables = %w(@_action_has_layout)
helper ActionMailer::MailHelper
include ActionMailer::OldApi
include ActionMailer::DeprecatedApi
delegate :register_observer, :to => Mail
delegate :register_interceptor, :to => Mail
private_class_method :new #:nodoc:
class_attribute :default_params
@@ -348,34 +360,9 @@ module ActionMailer #:nodoc:
}.freeze
class << self
# Register one or more Observers which will be notified when mail is delivered.
def register_observers(*observers)
observers.flatten.compact.each { |observer| register_observer(observer) }
end
# Register one or more Interceptors which will be called before mail is sent.
def register_interceptors(*interceptors)
interceptors.flatten.compact.each { |interceptor| register_interceptor(interceptor) }
end
# Register an Observer which will be notified when mail is delivered.
# Either a class or a string can be passed in as the Observer. If a string is passed in
# it will be <tt>constantize</tt>d.
def register_observer(observer)
delivery_observer = (observer.is_a?(String) ? observer.constantize : observer)
Mail.register_observer(delivery_observer)
end
# Register an Interceptor which will be called before mail is sent.
# Either a class or a string can be passed in as the Interceptor. If a string is passed in
# it will be <tt>constantize</tt>d.
def register_interceptor(interceptor)
delivery_interceptor = (interceptor.is_a?(String) ? interceptor.constantize : interceptor)
Mail.register_interceptor(delivery_interceptor)
end
def mailer_name
@mailer_name ||= anonymous? ? "anonymous" : name.underscore
@mailer_name ||= name.underscore
end
attr_writer :mailer_name
alias :controller_path :mailer_name
@@ -415,14 +402,14 @@ module ActionMailer #:nodoc:
end
end
def respond_to?(method, include_private = false) #:nodoc:
def respond_to?(method, *args) #:nodoc:
super || action_methods.include?(method.to_s)
end
protected
def set_payload_for_mail(payload, mail) #:nodoc:
payload[:mailer] = name
payload[:mailer] = self.name
payload[:message_id] = mail.message_id
payload[:subject] = mail.subject
payload[:to] = mail.to
@@ -434,8 +421,11 @@ module ActionMailer #:nodoc:
end
def method_missing(method, *args) #:nodoc:
return super unless respond_to?(method)
new(method, *args).message
if action_methods.include?(method.to_s)
new(method, *args).message
else
super
end
end
end
@@ -447,28 +437,40 @@ module ActionMailer #:nodoc:
# method, for instance).
def initialize(method_name=nil, *args)
super()
@mail_was_called = false
@_message = Mail.new
process(method_name, *args) if method_name
end
def process(*args) #:nodoc:
lookup_context.skip_default_locale!
super
@_message = NullMail.new unless @mail_was_called
end
class NullMail #:nodoc:
def body; '' end
def method_missing(*args)
nil
class DeprecatedHeaderProxy < ActiveSupport::BasicObject
def initialize(message)
@message = message
end
end
def mailer_name
self.class.mailer_name
def []=(key, value)
unless value.is_a?(::String)
::ActiveSupport::Deprecation.warn("Using a non-String object for a header's value is deprecated. " \
"You specified #{value.inspect} (a #{value.class}) for #{key}", caller)
value = value.to_s
end
@message[key] = value
end
def headers(hash = {})
hash.each_pair do |k,v|
self[k] = v
end
end
def method_missing(meth, *args, &block)
@message.send(meth, *args, &block)
end
end
# Allows you to pass random and unusual headers to the new +Mail::Message+ object
@@ -487,9 +489,9 @@ module ActionMailer #:nodoc:
# X-Special-Domain-Specific-Header: SecretValue
def headers(args=nil)
if args
@_message.headers(args)
DeprecatedHeaderProxy.new(@_message).headers(args)
else
@_message
DeprecatedHeaderProxy.new(@_message)
end
end
@@ -535,7 +537,7 @@ module ActionMailer #:nodoc:
#
# * <tt>:subject</tt> - The subject of the message, if this is omitted, Action Mailer will
# ask the Rails I18n class for a translated <tt>:subject</tt> in the scope of
# <tt>[mailer_scope, action_name]</tt> or if this is missing, will translate the
# <tt>[:actionmailer, mailer_scope, action_name]</tt> or if this is missing, will translate the
# humanized version of the <tt>action_name</tt>
# * <tt>:to</tt> - Who the message is destined for, can be a string of addresses, or an array
# of addresses.
@@ -561,8 +563,8 @@ module ActionMailer #:nodoc:
# method.
#
# When a <tt>:return_path</tt> is specified as header, that value will be used as the 'envelope from'
# address for the Mail message. Setting this is useful when you want delivery notifications
# sent to a different address than the one in <tt>:from</tt>. Mail will actually use the
# address for the Mail message. Setting this is useful when you want delivery notifications
# sent to a different address than the one in <tt>:from</tt>. Mail will actually use the
# <tt>:return_path</tt> in preference to the <tt>:sender</tt> in preference to the <tt>:from</tt>
# field for the 'envelope from' value.
#
@@ -614,9 +616,8 @@ module ActionMailer #:nodoc:
# end
#
def mail(headers={}, &block)
# Guard flag to prevent both the old and the new API from firing.
# On master this flag was renamed to `@_mail_was_called`.
# On master there is only one API and this flag is no longer used as a guard.
# Guard flag to prevent both the old and the new API from firing
# Should be removed when old API is removed
@mail_was_called = true
m = @_message
@@ -626,7 +627,7 @@ module ActionMailer #:nodoc:
# Call all the procs (if any)
default_values = self.class.default.merge(self.class.default) do |k,v|
v.respond_to?(:call) ? instance_eval(&v) : v
v.respond_to?(:call) ? v.bind(self).call : v
end
# Handle defaults
@@ -680,9 +681,6 @@ module ActionMailer #:nodoc:
end
end
# Translates the +subject+ using Rails I18n class under <tt>[:actionmailer, mailer_scope, action_name]</tt> scope.
# If it does not find a translation for the +subject+ under the specified scope it will default to a
# humanized version of the <tt>action_name</tt>.
def default_i18n_subject #:nodoc:
mailer_scope = self.class.mailer_name.gsub('/', '.')
I18n.t(:subject, :scope => [mailer_scope, action_name], :default => action_name.humanize)
@@ -719,8 +717,15 @@ module ActionMailer #:nodoc:
end
def each_template(paths, name, &block) #:nodoc:
templates = lookup_context.find_all(name, Array.wrap(paths))
templates.uniq_by { |t| t.formats }.each(&block)
Array.wrap(paths).each do |path|
templates = lookup_context.find_all(name, path)
templates = templates.uniq_by { |t| t.formats }
unless templates.empty?
templates.each(&block)
return
end
end
end
def create_parts_from_responses(m, responses) #:nodoc:
@@ -742,7 +747,28 @@ module ActionMailer #:nodoc:
container.add_part(part)
end
module DeprecatedUrlOptions
def default_url_options
deprecated_url_options
end
def default_url_options=(val)
deprecated_url_options
end
def deprecated_url_options
raise "You can no longer call ActionMailer::Base.default_url_options " \
"directly. You need to set config.action_mailer.default_url_options. " \
"If you are using ActionMailer standalone, you need to include the " \
"routing url_helpers directly."
end
end
# This module will complain if the user tries to set default_url_options
# directly instead of through the config object. In Action Mailer's Railtie,
# we include the router's url_helpers, which will override this module.
extend DeprecatedUrlOptions
ActiveSupport.run_load_hooks(:action_mailer, self)
end
end

View File

@@ -22,9 +22,9 @@ module ActionMailer #:nodoc:
def custom(mime, options={})
options.reverse_merge!(:content_type => mime.to_s)
@context.formats = [mime.to_sym]
@context.freeze_formats([mime.to_sym])
options[:body] = block_given? ? yield : @default_render.call
@responses << options
end
end
end
end

View File

@@ -1,7 +1,7 @@
require 'tmpdir'
module ActionMailer
# This module handles everything related to mail delivery, from registering new
# This modules handles everything related to the delivery, from registering new
# delivery methods to configuring the mail object to be sent.
module DeliveryMethods
extend ActiveSupport::Concern

View File

@@ -0,0 +1,147 @@
require 'active_support/core_ext/object/try'
module ActionMailer
# This is the API which is deprecated and is going to be removed on Rails 3.1 release.
# Part of the old API will be deprecated after 3.1, for a smoother deprecation process.
# Check those in OldApi instead.
module DeprecatedApi #:nodoc:
extend ActiveSupport::Concern
included do
[:charset, :content_type, :mime_version, :implicit_parts_order].each do |method|
class_eval <<-FILE, __FILE__, __LINE__ + 1
def self.default_#{method}
@@default_#{method}
end
def self.default_#{method}=(value)
ActiveSupport::Deprecation.warn "ActionMailer::Base.default_#{method}=value is deprecated, " <<
"use default :#{method} => value instead"
@@default_#{method} = value
end
@@default_#{method} = nil
FILE
end
end
module ClassMethods
# Deliver the given mail object directly. This can be used to deliver
# a preconstructed mail object, like:
#
# email = MyMailer.create_some_mail(parameters)
# email.set_some_obscure_header "frobnicate"
# MyMailer.deliver(email)
def deliver(mail, show_warning=true)
if show_warning
ActiveSupport::Deprecation.warn "#{self}.deliver is deprecated, call " <<
"deliver in the mailer instance instead", caller[0,2]
end
raise "no mail object available for delivery!" unless mail
wrap_delivery_behavior(mail)
mail.deliver
mail
end
def template_root
self.view_paths && self.view_paths.first
end
def template_root=(root)
ActiveSupport::Deprecation.warn "template_root= is deprecated, use prepend_view_path instead", caller[0,2]
self.view_paths = ActionView::Base.process_view_paths(root)
end
def respond_to?(method_symbol, include_private = false)
matches_dynamic_method?(method_symbol) || super
end
def method_missing(method_symbol, *parameters)
if match = matches_dynamic_method?(method_symbol)
case match[1]
when 'create'
ActiveSupport::Deprecation.warn "#{self}.create_#{match[2]} is deprecated, " <<
"use #{self}.#{match[2]} instead", caller[0,2]
new(match[2], *parameters).message
when 'deliver'
ActiveSupport::Deprecation.warn "#{self}.deliver_#{match[2]} is deprecated, " <<
"use #{self}.#{match[2]}.deliver instead", caller[0,2]
new(match[2], *parameters).message.deliver
else super
end
else
super
end
end
private
def matches_dynamic_method?(method_name)
method_name = method_name.to_s
/^(create|deliver)_([_a-z]\w*)/.match(method_name) || /^(new)$/.match(method_name)
end
end
# Delivers a Mail object. By default, it delivers the cached mail
# 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 = @_message)
ActiveSupport::Deprecation.warn "Calling deliver in the AM::Base object is deprecated, " <<
"please call deliver in the Mail instance", caller[0,2]
self.class.deliver(mail, false)
end
alias :deliver :deliver!
def render(*args)
options = args.last.is_a?(Hash) ? args.last : {}
if file = options[:file] and !file.index("/")
ActiveSupport::Deprecation.warn("render :file is deprecated except for absolute paths. " \
"Please use render :template instead")
options[:prefix] = _prefix
end
if options[:body].is_a?(Hash)
ActiveSupport::Deprecation.warn(':body in render deprecated. Please use instance ' <<
'variables as assigns instead', caller[0,1])
options[:body].each { |k,v| instance_variable_set(:"@#{k}", v) }
end
super
end
# Render a message but does not set it as mail body. Useful for rendering
# data for part and attachments.
#
# Examples:
#
# render_message "special_message"
# render_message :template => "special_message"
# render_message :inline => "<%= 'Hi!' %>"
#
def render_message(*args)
ActiveSupport::Deprecation.warn "render_message is deprecated, use render instead", caller[0,2]
render(*args)
end
private
def initialize_defaults(*)
@charset ||= self.class.default_charset.try(:dup)
@content_type ||= self.class.default_content_type.try(:dup)
@implicit_parts_order ||= self.class.default_implicit_parts_order.try(:dup)
@mime_version ||= self.class.default_mime_version.try(:dup)
super
end
def create_parts
if @body.is_a?(Hash) && !@body.empty?
ActiveSupport::Deprecation.warn "Giving a hash to body is deprecated, please use instance variables instead", caller[0,2]
@body.each { |k, v| instance_variable_set(:"@#{k}", v) }
end
super
end
end
end

View File

@@ -4,12 +4,12 @@ module ActionMailer
class LogSubscriber < ActiveSupport::LogSubscriber
def deliver(event)
recipients = Array.wrap(event.payload[:to]).join(', ')
info("\nSent mail to #{recipients} (#{format_duration(event.duration)})")
info("\nSent mail to #{recipients} (%1.fms)" % event.duration)
debug(event.payload[:mail])
end
def receive(event)
info("\nReceived mail (#{format_duration(event.duration)})")
info("\nReceived mail (%.1fms)" % event.duration)
debug(event.payload[:mail])
end
@@ -19,4 +19,4 @@ module ActionMailer
end
end
ActionMailer::LogSubscriber.attach_to :action_mailer
ActionMailer::LogSubscriber.attach_to :action_mailer

View File

@@ -3,8 +3,17 @@ module ActionMailer
# Uses Text::Format to take the text and format it, indented two spaces for
# each line, and wrapped at 72 columns.
def block_format(text)
begin
require 'text/format'
rescue LoadError => e
$stderr.puts "You don't have text-format installed in your application. Please add it to your Gemfile and run bundle install"
raise e
end unless defined?(Text::Format)
formatted = text.split(/\n\r\n/).collect { |paragraph|
format_paragraph(paragraph)
Text::Format.new(
:columns => 72, :first_indent => 2, :body_indent => 2, :text => paragraph
).format
}.join("\n")
# Make list points stand on their own line
@@ -28,29 +37,5 @@ module ActionMailer
def attachments
@_message.attachments
end
# Returns +text+ wrapped at +len+ columns and indented +indent+ spaces.
#
# === Examples
#
# my_text = "Here is a sample text with more than 40 characters"
#
# format_paragraph(my_text, 25, 4)
# # => " Here is a sample text with\n more than 40 characters"
def format_paragraph(text, len = 72, indent = 2)
sentences = [[]]
text.split.each do |word|
if (sentences.last + [word]).join(' ').length > len
sentences << [word]
else
sentences.last << word
end
end
sentences.map { |sentence|
"#{" " * indent}#{sentence.join(' ')}"
}.join "\n"
end
end
end

View File

@@ -0,0 +1,259 @@
require 'active_support/concern'
require 'active_support/core_ext/object/try'
require 'active_support/core_ext/object/blank'
module ActionMailer
module OldApi #:nodoc:
extend ActiveSupport::Concern
included do
extend ActionMailer::AdvAttrAccessor
@@protected_instance_variables = %w(@parts)
cattr_reader :protected_instance_variables
# Specify the BCC addresses for the message
adv_attr_accessor :bcc
# Specify the CC addresses for the message.
adv_attr_accessor :cc
# Specify the charset to use for the message. This defaults to the
# +default_charset+ specified for ActionMailer::Base.
adv_attr_accessor :charset
# Specify the content type for the message. This defaults to <tt>text/plain</tt>
# in most cases, but can be automatically set in some situations.
adv_attr_accessor :content_type
# 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 the order in which parts should be sorted, based on content-type.
# This defaults to the value for the +default_implicit_parts_order+.
adv_attr_accessor :implicit_parts_order
# Defaults to "1.0", but may be explicitly given if needed.
adv_attr_accessor :mime_version
# The recipient addresses for the message, either as a string (for a single
# address) or an array (for multiple addresses).
adv_attr_accessor :recipients
# The date on which the message was sent. If not set (the default), the
# header will be set by the delivery agent.
adv_attr_accessor :sent_on
# Specify the subject of the message.
adv_attr_accessor :subject
# Specify the template name to use for current message. This is the "base"
# template name, without the extension or directory, and may be used to
# have multiple mailer methods share the same template.
adv_attr_accessor :template
# Override the mailer name, which defaults to an inflected version of the
# mailer's class name. If you want to use a template in a non-standard
# location, you can use this to specify that location.
adv_attr_accessor :mailer_name
# Define the body of the message. This is either a Hash (in which case it
# specifies the variables to pass to the template when it is rendered),
# or a string, in which case it specifies the actual text of the message.
adv_attr_accessor :body
# Alias controller_path to mailer_name so render :partial in views work.
alias :controller_path :mailer_name
end
def process(method_name, *args)
initialize_defaults(method_name)
super
unless @mail_was_called
create_parts
create_mail
end
@_message
end
# Add a part to a multipart message, with the given content-type. The
# part itself is yielded to the block so that other properties (charset,
# body, headers, etc.) can be set on it.
def part(params)
params = {:content_type => params} if String === params
if custom_headers = params.delete(:headers)
params.merge!(custom_headers)
end
part = Mail::Part.new(params)
yield part if block_given?
@parts << part
end
# Add an attachment to a multipart message. This is simply a part with the
# content-disposition set to "attachment".
def attachment(params, &block)
params = { :content_type => params } if String === params
params[:content] ||= params.delete(:data) || params.delete(:body)
if params[:filename]
params = normalize_file_hash(params)
else
params = normalize_nonfile_hash(params)
end
part(params, &block)
end
protected
def normalize_nonfile_hash(params)
content_disposition = "attachment;"
mime_type = params.delete(:mime_type)
if content_type = params.delete(:content_type)
content_type = "#{mime_type || content_type};"
end
params[:body] = params.delete(:data) if params[:data]
{ :content_type => content_type,
:content_disposition => content_disposition }.merge(params)
end
def normalize_file_hash(params)
filename = File.basename(params.delete(:filename))
content_disposition = "attachment; filename=\"#{File.basename(filename)}\""
mime_type = params.delete(:mime_type)
if (content_type = params.delete(:content_type)) && (content_type !~ /filename=/)
content_type = "#{mime_type || content_type}; filename=\"#{filename}\""
end
params[:body] = params.delete(:data) if params[:data]
{ :content_type => content_type,
:content_disposition => content_disposition }.merge(params)
end
def create_mail
m = @_message
set_fields!({:subject => subject, :to => recipients, :from => from,
:bcc => bcc, :cc => cc, :reply_to => reply_to}, charset)
m.mime_version = mime_version unless mime_version.nil?
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
main_type, sub_type = split_content_type(real_content_type)
if @parts.size == 1 && @parts.first.parts.empty?
m.content_type([main_type, sub_type, ctype_attrs])
m.body = @parts.first.body.encoded
else
@parts.each do |p|
m.add_part(p)
end
m.body.set_sort_order(@implicit_parts_order)
m.body.sort_parts!
if real_content_type =~ /multipart/
ctype_attrs.delete "charset"
m.content_type([main_type, sub_type, ctype_attrs])
end
end
wrap_delivery_behavior!
m.content_transfer_encoding = '8bit' unless m.body.only_us_ascii?
@_message
end
# Set up the default values for the various instance variables of this
# mailer. Subclasses may override this method to provide different
# defaults.
def initialize_defaults(method_name)
@charset ||= self.class.default[:charset].try(:dup)
@content_type ||= self.class.default[:content_type].try(:dup)
@implicit_parts_order ||= self.class.default[:parts_order].try(:dup)
@mime_version ||= self.class.default[:mime_version].try(:dup)
@mailer_name ||= self.class.mailer_name.dup
@template ||= method_name
@mail_was_called = false
@parts ||= []
@headers ||= {}
@sent_on ||= Time.now
@body ||= {}
end
def create_parts
if String === @body
@parts.unshift create_inline_part(@body)
elsif @parts.empty? || @parts.all? { |p| p.content_disposition =~ /^attachment/ }
lookup_context.find_all(@template, @mailer_name).each do |template|
self.formats = template.formats
@parts << create_inline_part(render(:template => template), template.mime_type)
end
if @parts.size > 1
@content_type = "multipart/alternative" if @content_type !~ /^multipart/
end
# If this is a multipart e-mail add the mime_version if it is not
# already set.
@mime_version ||= "1.0" if !@parts.empty?
end
end
def create_inline_part(body, mime_type=nil)
ct = mime_type || "text/plain"
main_type, sub_type = split_content_type(ct.to_s)
Mail::Part.new(
:content_type => [main_type, sub_type, {:charset => charset}],
:content_disposition => "inline",
:body => body
)
end
def set_fields!(headers, charset) #:nodoc:
m = @_message
m.charset = charset
m.subject ||= headers.delete(:subject) if headers[:subject]
m.to ||= headers.delete(:to) if headers[:to]
m.from ||= headers.delete(:from) if headers[:from]
m.cc ||= headers.delete(:cc) if headers[:cc]
m.bcc ||= headers.delete(:bcc) if headers[:bcc]
m.reply_to ||= headers.delete(:reply_to) if headers[:reply_to]
end
def split_content_type(ct)
ct.to_s.split("/")
end
def parse_content_type(defaults=nil)
if @content_type.blank?
[ nil, {} ]
else
ctype, *attrs = @content_type.split(/;\s*/)
attrs = attrs.inject({}) { |h,s| k,v = s.split(/\=/, 2); h[k] = v; h }
[ctype, {"charset" => @charset}.merge(attrs)]
end
end
end
end

View File

@@ -1,6 +1,5 @@
require "action_mailer"
require "rails"
require "abstract_controller/railties/routes_helpers"
module ActionMailer
class Railtie < Rails::Railtie
@@ -14,31 +13,14 @@ module ActionMailer
paths = app.config.paths
options = app.config.action_mailer
options.assets_dir ||= paths["public"].first
options.javascripts_dir ||= paths["public/javascripts"].first
options.stylesheets_dir ||= paths["public/stylesheets"].first
# make sure readers methods get compiled
options.asset_path ||= app.config.asset_path
options.asset_host ||= app.config.asset_host
options.relative_url_root ||= app.config.relative_url_root
options.assets_dir ||= paths.public.to_a.first
options.javascripts_dir ||= paths.public.javascripts.to_a.first
options.stylesheets_dir ||= paths.public.stylesheets.to_a.first
ActiveSupport.on_load(:action_mailer) do
include AbstractController::UrlFor
extend ::AbstractController::Railties::RoutesHelpers.with(app.routes)
include app.routes.mounted_helpers
register_interceptors(options.delete(:interceptors))
register_observers(options.delete(:observers))
include app.routes.url_helpers
options.each { |k,v| send("#{k}=", v) }
end
end
initializer "action_mailer.compile_config_methods" do
ActiveSupport.on_load(:action_mailer) do
config.compile_methods! if config.respond_to?(:compile_methods!)
end
end
end
end
end

View File

@@ -1,5 +1,3 @@
require 'active_support/core_ext/class/attribute'
module ActionMailer
class NonInferrableMailerError < ::StandardError
def initialize(name)
@@ -15,26 +13,13 @@ module ActionMailer
include TestHelper
included do
class_attribute :_mailer_class
setup :initialize_test_deliveries
setup :set_expected_mail
end
module ClassMethods
def tests(mailer)
case mailer
when String, Symbol
self._mailer_class = mailer.to_s.camelize.constantize
when Module
self._mailer_class = mailer
else
raise NonInferrableMailerError.new(mailer)
end
write_inheritable_attribute(:mailer_class, mailer)
end
def mailer_class
if mailer = self._mailer_class
if mailer = read_inheritable_attribute(:mailer_class)
mailer
else
tests determine_default_mailer(name)
@@ -48,6 +33,8 @@ module ActionMailer
end
end
module InstanceMethods
protected
def initialize_test_deliveries
@@ -75,8 +62,15 @@ module ActionMailer
def read_fixture(action)
IO.readlines(File.join(Rails.root, 'test', 'fixtures', self.class.mailer_class.name.underscore, action))
end
end
included do
setup :initialize_test_deliveries
setup :set_expected_mail
end
end
include Behavior
end
end

View File

@@ -0,0 +1,34 @@
module Mail
class Message
def set_content_type(*args)
ActiveSupport::Deprecation.warn('Message#set_content_type is deprecated, please just call ' <<
'Message#content_type with the same arguments', caller[0,2])
content_type(*args)
end
alias :old_transfer_encoding :transfer_encoding
def transfer_encoding(value = nil)
if value
ActiveSupport::Deprecation.warn('Message#transfer_encoding is deprecated, please call ' <<
'Message#content_transfer_encoding with the same arguments', caller[0,2])
content_transfer_encoding(value)
else
old_transfer_encoding
end
end
def transfer_encoding=(value)
ActiveSupport::Deprecation.warn('Message#transfer_encoding= is deprecated, please call ' <<
'Message#content_transfer_encoding= with the same arguments', caller[0,2])
self.content_transfer_encoding = value
end
def original_filename
ActiveSupport::Deprecation.warn('Message#original_filename is deprecated, ' <<
'please call Message#filename', caller[0,2])
filename
end
end
end

View File

@@ -1,10 +1,9 @@
module ActionMailer
module VERSION #:nodoc:
MAJOR = 3
MINOR = 2
TINY = 19
PRE = nil
MINOR = 0
TINY = 2
STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
STRING = [MAJOR, MINOR, TINY].join('.')
end
end

View File

@@ -1,5 +1,4 @@
Description:
============
Stubs out a new mailer and its views. Pass the mailer name, either
CamelCased or under_scored, and an optional list of emails as arguments.
@@ -7,12 +6,10 @@ Description:
engine and test framework generators.
Example:
========
rails generate mailer Notifications signup forgot_password invoice
`rails generate mailer Notifications signup forgot_password invoice`
creates a Notifications mailer class, views, test, and fixtures:
Mailer: app/mailers/notifications.rb
Views: app/views/notifications/signup.erb [...]
Test: test/functional/notifications_test.rb
Fixtures: test/fixtures/notifications/signup [...]

View File

@@ -1,7 +1,6 @@
<% module_namespacing do -%>
class <%= class_name %> < ActionMailer::Base
default <%= key_value :from, '"from@example.com"' %>
<% actions.each do |action| -%>
default :from => "from@example.com"
<% for action in actions -%>
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
@@ -11,8 +10,7 @@ class <%= class_name %> < ActionMailer::Base
def <%= action %>
@greeting = "Hi"
mail <%= key_value :to, '"to@example.org"' %>
mail :to => "to@example.org"
end
<% end -%>
end
<% end -%>

View File

@@ -23,6 +23,12 @@ if "ruby".encoding_aware?
end
end
silence_warnings do
# These external dependencies have warnings :/
require 'text/format'
require 'mail'
end
lib = File.expand_path("#{File.dirname(__FILE__)}/../lib")
$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib)
@@ -30,11 +36,6 @@ require 'test/unit'
require 'action_mailer'
require 'action_mailer/test_case'
silence_warnings do
# These external dependencies have warnings :/
require 'mail'
end
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
@@ -77,5 +78,3 @@ end
def restore_delivery_method
ActionMailer::Base.delivery_method = @old_delivery_method
end
ActiveSupport::Deprecation.silenced = true

View File

@@ -7,6 +7,9 @@ require 'mailers/proc_mailer'
require 'mailers/asset_mailer'
class BaseTest < ActiveSupport::TestCase
# TODO Add some tests for implicity layout render and url helpers
# so we can get rid of old base tests altogether with old base.
def teardown
ActionMailer::Base.asset_host = nil
ActionMailer::Base.assets_dir = nil
@@ -32,21 +35,21 @@ class BaseTest < ActiveSupport::TestCase
end
test "mail() with bcc, cc, content_type, charset, mime_version, reply_to and date" do
time = Time.now.beginning_of_day.to_datetime
@time = Time.now.beginning_of_day.to_datetime
email = BaseMailer.welcome(:bcc => 'bcc@test.lindsaar.net',
:cc => 'cc@test.lindsaar.net',
:content_type => 'multipart/mixed',
:charset => 'iso-8559-1',
:mime_version => '2.0',
:reply_to => 'reply-to@test.lindsaar.net',
:date => time)
:date => @time)
assert_equal(['bcc@test.lindsaar.net'], email.bcc)
assert_equal(['cc@test.lindsaar.net'], email.cc)
assert_equal('multipart/mixed; charset=iso-8559-1', email.content_type)
assert_equal('iso-8559-1', email.charset)
assert_equal('2.0', email.mime_version)
assert_equal(['reply-to@test.lindsaar.net'], email.reply_to)
assert_equal(time, email.date)
assert_equal(@time, email.date)
end
test "mail() renders the template using the method being processed" do
@@ -73,6 +76,11 @@ class BaseTest < ActiveSupport::TestCase
assert_equal("Not SPAM", email['X-SPAM'].decoded)
end
test "deprecated non-String custom headers" do
email = assert_deprecated { BaseMailer.welcome_with_fixnum_header }
assert_equal("2", email['X-SPAM-COUNT'].decoded)
end
test "can pass random headers in as a hash to mail" do
hash = {'X-Special-Domain-Specific-Header' => "SecretValue",
'In-Reply-To' => '1234@mikel.me.com' }
@@ -153,8 +161,8 @@ class BaseTest < ActiveSupport::TestCase
assert_equal(2, email.parts.length)
assert_equal("multipart/related", email.mime_type)
assert_equal("multipart/alternative", email.parts[0].mime_type)
assert_equal("text/plain", email.parts[0].parts[0].mime_type)
assert_equal("text/html", email.parts[0].parts[1].mime_type)
assert_equal("text/plain", email.parts[0].parts[0].mime_type)
assert_equal("text/html", email.parts[0].parts[1].mime_type)
assert_equal("logo.png", email.parts[1].filename)
end
@@ -431,6 +439,13 @@ class BaseTest < ActiveSupport::TestCase
assert_equal("TEXT Implicit Multipart", mail.text_part.body.decoded)
end
test "render :file uses render :template semantics and is deprecated" do
mail = nil
assert_deprecated { mail = BaseMailer.implicit_different_template_with_file('implicit_multipart').deliver }
assert_equal("HTML Implicit Multipart", mail.html_part.body.decoded)
assert_equal("TEXT Implicit Multipart", mail.text_part.body.decoded)
end
test "you can specify a different template for explicit render" do
mail = BaseMailer.explicit_different_template('explicit_multipart_templates').deliver
assert_equal("HTML Explicit Multipart Templates", mail.html_part.body.decoded)
@@ -471,18 +486,6 @@ class BaseTest < ActiveSupport::TestCase
assert_equal(%{<img alt="Dummy" src="http://local.com/images/dummy.png" />}, mail.body.to_s.strip)
end
test 'the view is not rendered when mail was never called' do
mail = BaseMailer.without_mail_call
assert_equal('', mail.body.to_s.strip)
mail.deliver
end
test 'the return value of mailer methods is not relevant' do
mail = BaseMailer.with_nil_as_return_value
assert_equal('Welcome', mail.body.to_s.strip)
mail.deliver
end
# Before and After hooks
class MyObserver
@@ -490,11 +493,6 @@ class BaseTest < ActiveSupport::TestCase
end
end
class MySecondObserver
def self.delivered_email(mail)
end
end
test "you can register an observer to the mail object that gets informed on email delivery" do
ActionMailer::Base.register_observer(MyObserver)
mail = BaseMailer.welcome
@@ -502,31 +500,11 @@ class BaseTest < ActiveSupport::TestCase
mail.deliver
end
test "you can register an observer using its stringified name to the mail object that gets informed on email delivery" do
ActionMailer::Base.register_observer("BaseTest::MyObserver")
mail = BaseMailer.welcome
MyObserver.expects(:delivered_email).with(mail)
mail.deliver
end
test "you can register multiple observers to the mail object that both get informed on email delivery" do
ActionMailer::Base.register_observers("BaseTest::MyObserver", MySecondObserver)
mail = BaseMailer.welcome
MyObserver.expects(:delivered_email).with(mail)
MySecondObserver.expects(:delivered_email).with(mail)
mail.deliver
end
class MyInterceptor
def self.delivering_email(mail)
end
end
class MySecondInterceptor
def self.delivering_email(mail)
end
end
test "you can register an interceptor to the mail object that gets passed the mail object before delivery" do
ActionMailer::Base.register_interceptor(MyInterceptor)
mail = BaseMailer.welcome
@@ -534,21 +512,6 @@ class BaseTest < ActiveSupport::TestCase
mail.deliver
end
test "you can register an interceptor using its stringified name to the mail object that gets passed the mail object before delivery" do
ActionMailer::Base.register_interceptor("BaseTest::MyInterceptor")
mail = BaseMailer.welcome
MyInterceptor.expects(:delivering_email).with(mail)
mail.deliver
end
test "you can register multiple interceptors to the mail object that both get passed the mail object before delivery" do
ActionMailer::Base.register_interceptors("BaseTest::MyInterceptor", MySecondInterceptor)
mail = BaseMailer.welcome
MyInterceptor.expects(:delivering_email).with(mail)
MySecondInterceptor.expects(:delivering_email).with(mail)
mail.deliver
end
test "being able to put proc's into the defaults hash and they get evaluated on mail sending" do
mail1 = ProcMailer.welcome
yesterday = 1.day.ago
@@ -574,19 +537,6 @@ class BaseTest < ActiveSupport::TestCase
assert_equal ["notify"], FooMailer.action_methods
end
test "mailer can be anonymous" do
mailer = Class.new(ActionMailer::Base) do
def welcome
mail
end
end
assert_equal "anonymous", mailer.mailer_name
assert_equal "Welcome", mailer.welcome.subject
assert_equal "Anonymous mailer body", mailer.welcome.body.encoded.strip
end
protected
# Execute the block setting the given values and restoring old values after

View File

@@ -1 +0,0 @@
Anonymous mailer body

View File

@@ -1 +0,0 @@
<% raise 'the template should not be rendered' %>

View File

@@ -1,4 +0,0 @@
Hello there,
Mr. <%= @recipient %>. Be greeted, new member!

View File

@@ -1,46 +0,0 @@
require 'abstract_unit'
require 'action_controller'
class I18nTestMailer < ActionMailer::Base
configure do |c|
c.assets_dir = ''
end
def mail_with_i18n_subject(recipient)
@recipient = recipient
I18n.locale = :de
mail(:to => recipient, :subject => "#{I18n.t :email_subject} #{recipient}",
:from => "system@loudthinking.com", :date => Time.local(2004, 12, 12))
end
end
class TestController < ActionController::Base
def send_mail
I18nTestMailer.mail_with_i18n_subject("test@localhost").deliver
render :text => 'Mail sent'
end
end
class ActionMailerI18nWithControllerTest < ActionDispatch::IntegrationTest
Routes = ActionDispatch::Routing::RouteSet.new
Routes.draw do
match ':controller(/:action(/:id))'
end
def app
Routes
end
def setup
I18n.backend.store_translations('de', :email_subject => '[Signed up] Welcome')
end
def teardown
I18n.locale = :en
end
def test_send_mail
get '/test/send_mail'
assert_equal "Mail sent", @response.body
end
end

View File

@@ -1,5 +1,4 @@
require "abstract_unit"
require 'mailers/base_mailer'
require "active_support/log_subscriber/test_helper"
require "action_mailer/log_subscriber"
@@ -12,6 +11,13 @@ class AMLogSubscriberTest < ActionMailer::TestCase
end
class TestMailer < ActionMailer::Base
def basic
recipients "somewhere@example.com"
subject "basic"
from "basic@example.com"
body "Hello world"
end
def receive(mail)
# Do nothing
end
@@ -22,12 +28,12 @@ class AMLogSubscriberTest < ActionMailer::TestCase
end
def test_deliver_is_notified
BaseMailer.welcome.deliver
TestMailer.basic.deliver
wait
assert_equal(1, @logger.logged(:info).size)
assert_match(/Sent mail to system@test.lindsaar.net/, @logger.logged(:info).first)
assert_match(/Sent mail to somewhere@example.com/, @logger.logged(:info).first)
assert_equal(1, @logger.logged(:debug).size)
assert_match(/Welcome/, @logger.logged(:debug).first)
assert_match(/Hello world/, @logger.logged(:debug).first)
end
def test_receive_is_notified

View File

@@ -14,14 +14,6 @@ class HelperMailer < ActionMailer::Base
end
end
def use_format_paragraph
@text = "But soft! What light through yonder window breaks?"
mail_with_defaults do |format|
format.html { render(:inline => "<%= format_paragraph @text, 15, 1 %>") }
end
end
def use_mailer
mail_with_defaults do |format|
format.html { render(:inline => "<%= mailer.message.subject %>") }
@@ -58,10 +50,5 @@ class MailerHelperTest < ActionMailer::TestCase
mail = HelperMailer.use_message
assert_match "using helpers", mail.body.encoded
end
def test_use_format_paragraph
mail = HelperMailer.use_format_paragraph
assert_match " But soft! What\r\n light through\r\n yonder window\r\n breaks?", mail.body.encoded
end
end

View File

@@ -10,6 +10,11 @@ class BaseMailer < ActionMailer::Base
mail({:subject => "The first email on new API!"}.merge!(hash))
end
def welcome_with_fixnum_header(hash = {})
headers['X-SPAM-COUNT'] = 2
mail({:template_name => "welcome", :subject => "The first email on new API!"}.merge!(hash))
end
def welcome_with_headers(hash = {})
headers hash
mail
@@ -38,7 +43,7 @@ class BaseMailer < ActionMailer::Base
end
def attachment_with_hash
attachments['invoice.jpg'] = { :data => ::Base64.encode64("\312\213\254\232)b"),
attachments['invoice.jpg'] = { :data => "\312\213\254\232)b",
:mime_type => "image/x-jpg",
:transfer_encoding => "base64" }
mail
@@ -98,6 +103,13 @@ class BaseMailer < ActionMailer::Base
mail(:template_name => template_name)
end
def implicit_different_template_with_file(template_name='')
mail do |format|
format.text { render :file => template_name }
format.html { render :file => template_name }
end
end
def explicit_different_template(template_name='')
mail do |format|
format.text { render :template => "#{mailer_name}/#{template_name}" }
@@ -113,14 +125,6 @@ class BaseMailer < ActionMailer::Base
end
def email_with_translations
mail :body => render("email_with_translations", :formats => [:html])
end
def without_mail_call
end
def with_nil_as_return_value(hash = {})
mail(:template_name => "welcome")
nil
body render("email_with_translations.html")
end
end

View File

@@ -0,0 +1,36 @@
require 'abstract_unit'
require 'action_mailer/adv_attr_accessor'
class AdvAttrTest < ActiveSupport::TestCase
class Person
cattr_reader :protected_instance_variables
@@protected_instance_variables = []
extend ActionMailer::AdvAttrAccessor
adv_attr_accessor :name
end
def setup
@person = Person.new
end
def test_adv_attr
assert_nil @person.name
@person.name 'Bob'
assert_equal 'Bob', @person.name
end
def test_adv_attr_writer
assert_nil @person.name
@person.name = 'Bob'
assert_equal 'Bob', @person.name
end
def test_raise_an_error_with_multiple_args
assert_raise(ArgumentError) { @person.name('x', 'y') }
end
def test_ivar_is_added_to_protected_instnace_variables
assert Person.protected_instance_variables.include?('@name')
end
end

View File

@@ -3,9 +3,9 @@ require 'action_controller'
class AssetHostMailer < ActionMailer::Base
def email_with_asset
mail :to => 'test@localhost',
:subject => 'testing email containing asset path while asset_host is set',
:from => 'tester@example.com'
recipients 'test@localhost'
subject "testing email containing asset path while asset_host is set"
from "tester@example.com"
end
end
@@ -29,7 +29,7 @@ class AssetHostTest < Test::Unit::TestCase
assert_equal %Q{<img alt="Somelogo" src="http://www.example.com/images/somelogo.png" />}, mail.body.to_s.strip
end
def test_asset_host_as_one_argument_proc
def test_asset_host_as_one_arguement_proc
AssetHostMailer.config.asset_host = Proc.new { |source|
if source.starts_with?('/images')
"http://images.example.com"
@@ -41,7 +41,7 @@ class AssetHostTest < Test::Unit::TestCase
assert_equal %Q{<img alt="Somelogo" src="http://images.example.com/images/somelogo.png" />}, mail.body.to_s.strip
end
def test_asset_host_as_two_argument_proc
def test_asset_host_as_two_arguement_proc
ActionController::Base.config.asset_host = Proc.new {|source,request|
if request && request.ssl?
"https://www.example.com"

View File

@@ -1,45 +1,53 @@
require 'abstract_unit'
class AutoLayoutMailer < ActionMailer::Base
default :to => 'test@localhost',
:subject => "You have a mail",
:from => "tester@example.com"
def hello
mail()
recipients 'test@localhost'
subject "You have a mail"
from "tester@example.com"
end
def spam
recipients 'test@localhost'
subject "You have a mail"
from "tester@example.com"
@world = "Earth"
mail(:body => render(:inline => "Hello, <%= @world %>", :layout => 'spam'))
body render(:inline => "Hello, <%= @world %>", :layout => 'spam')
end
def nolayout
recipients 'test@localhost'
subject "You have a mail"
from "tester@example.com"
@world = "Earth"
mail(:body => render(:inline => "Hello, <%= @world %>", :layout => false))
body render(:inline => "Hello, <%= @world %>", :layout => false)
end
def multipart(type = nil)
mail(:content_type => type) do |format|
format.text { render }
format.html { render }
end
recipients 'test@localhost'
subject "You have a mail"
from "tester@example.com"
content_type(type) if type
end
end
class ExplicitLayoutMailer < ActionMailer::Base
layout 'spam', :except => [:logout]
default :to => 'test@localhost',
:subject => "You have a mail",
:from => "tester@example.com"
def signup
mail()
recipients 'test@localhost'
subject "You have a mail"
from "tester@example.com"
end
def logout
mail()
recipients 'test@localhost'
subject "You have a mail"
from "tester@example.com"
end
end
@@ -83,6 +91,19 @@ class LayoutMailerTest < Test::Unit::TestCase
assert_equal "Hello from layout text/html multipart", mail.parts.last.body.to_s
end
def test_should_fix_multipart_layout
mail = AutoLayoutMailer.multipart("text/plain")
assert_equal "multipart/alternative", mail.mime_type
assert_equal 2, mail.parts.size
assert_equal 'text/plain', mail.parts.first.mime_type
assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body.to_s
assert_equal 'text/html', mail.parts.last.mime_type
assert_equal "Hello from layout text/html multipart", mail.parts.last.body.to_s
end
def test_should_pickup_layout_given_to_render
mail = AutoLayoutMailer.spam
assert_equal "Spammer layout Hello, Earth", mail.body.to_s.strip

View File

@@ -0,0 +1,167 @@
require 'abstract_unit'
class RenderMailer < ActionMailer::Base
def inline_template
recipients 'test@localhost'
subject "using helpers"
from "tester@example.com"
@world = "Earth"
body render(:inline => "Hello, <%= @world %>")
end
def file_template
recipients 'test@localhost'
subject "using helpers"
from "tester@example.com"
@recipient = 'test@localhost'
body render(:file => "templates/signed_up")
end
def rxml_template
recipients 'test@localhost'
subject "rendering rxml template"
from "tester@example.com"
end
def included_subtemplate
recipients 'test@localhost'
subject "Including another template in the one being rendered"
from "tester@example.com"
end
def no_instance_variable
recipients 'test@localhost'
subject "No Instance Variable"
from "tester@example.com"
silence_warnings do
body render(:inline => "Look, subject.nil? is <%= @subject.nil? %>!")
end
end
def initialize_defaults(method_name)
super
mailer_name "test_mailer"
end
def multipart_alternative
recipients 'test@localhost'
subject 'multipart/alternative'
from 'tester@example.com'
build_multipart_message(:foo => "bar")
end
private
def build_multipart_message(assigns = {})
content_type "multipart/alternative"
part "text/plain" do |p|
p.body = build_body_part('plain', assigns, :layout => false)
end
part "text/html" do |p|
p.body = build_body_part('html', assigns)
end
end
def build_body_part(content_type, assigns, options = {})
ActiveSupport::Deprecation.silence do
render "#{template}.#{content_type}", :body => assigns
end
end
end
class FirstMailer < ActionMailer::Base
def share
recipients 'test@localhost'
subject "using helpers"
from "tester@example.com"
end
end
class SecondMailer < ActionMailer::Base
def share
recipients 'test@localhost'
subject "using helpers"
from "tester@example.com"
end
end
# CHANGED: Those tests were changed because body returns an object now
# Instead of mail.body.strip, we should mail.body.to_s.strip
class RenderHelperTest < Test::Unit::TestCase
def setup
set_delivery_method :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries.clear
@recipient = 'test@localhost'
end
def teardown
restore_delivery_method
end
def test_inline_template
mail = RenderMailer.inline_template
assert_equal "Hello, Earth", mail.body.to_s.strip
end
def test_file_template
mail = RenderMailer.file_template
assert_equal "Hello there,\n\nMr. test@localhost", mail.body.to_s.strip
end
def test_rxml_template
mail = RenderMailer.rxml_template.deliver
assert_equal %(<?xml version="1.0" encoding="UTF-8"?>\n<test/>), mail.body.to_s.strip
end
def test_included_subtemplate
mail = RenderMailer.included_subtemplate.deliver
assert_equal "Hey Ho, let's go!", mail.body.to_s.strip
end
def test_no_instance_variable
mail = RenderMailer.no_instance_variable.deliver
assert_equal "Look, subject.nil? is true!", mail.body.to_s.strip
end
def test_legacy_multipart_alternative
mail = RenderMailer.multipart_alternative.deliver
assert_equal(2, mail.parts.size)
assert_equal("multipart/alternative", mail.mime_type)
assert_equal("text/plain", mail.parts[0].mime_type)
assert_equal("foo: bar", mail.parts[0].body.encoded)
assert_equal("text/html", mail.parts[1].mime_type)
assert_equal("<strong>foo</strong> bar", mail.parts[1].body.encoded)
end
end
class FirstSecondHelperTest < Test::Unit::TestCase
def setup
set_delivery_method :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries.clear
@recipient = 'test@localhost'
end
def teardown
restore_delivery_method
end
def test_ordering
mail = FirstMailer.share
assert_equal "first mail", mail.body.to_s.strip
mail = SecondMailer.share
assert_equal "second mail", mail.body.to_s.strip
mail = FirstMailer.share
assert_equal "first mail", mail.body.to_s.strip
mail = SecondMailer.share
assert_equal "second mail", mail.body.to_s.strip
end
end

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,35 @@
require 'abstract_unit'
class TmailCompatTest < ActiveSupport::TestCase
def test_set_content_type_raises_deprecation_warning
mail = Mail.new
assert_deprecated do
assert_nothing_raised do
mail.set_content_type "text/plain"
end
end
assert_equal mail.mime_type, "text/plain"
end
def test_transfer_encoding_raises_deprecation_warning
mail = Mail.new
assert_deprecated do
assert_nothing_raised do
mail.transfer_encoding "base64"
end
end
assert_equal mail.content_transfer_encoding, "base64"
end
def test_transfer_encoding_setter_raises_deprecation_warning
mail = Mail.new
assert_deprecated do
assert_nothing_raised do
mail.transfer_encoding = "base64"
end
end
assert_equal mail.content_transfer_encoding, "base64"
end
end

View File

@@ -18,10 +18,13 @@ class UrlTestMailer < ActionMailer::Base
end
def signed_up_with_url(recipient)
@recipients = recipient
@subject = "[Signed up] Welcome #{recipient}"
@from = "system@loudthinking.com"
@sent_on = Time.local(2004, 12, 12)
@recipient = recipient
@welcome_url = url_for :host => "example.com", :controller => "welcome", :action => "greeting"
mail(:to => recipient, :subject => "[Signed up] Welcome #{recipient}",
:from => "system@loudthinking.com", :date => Time.local(2004, 12, 12))
end
end
@@ -44,7 +47,6 @@ class ActionMailerUrlTest < ActionMailer::TestCase
set_delivery_method :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries.clear
ActiveSupport::Deprecation.silenced = false
@recipient = 'test@localhost'
end
@@ -56,9 +58,11 @@ class ActionMailerUrlTest < ActionMailer::TestCase
def test_signed_up_with_url
UrlTestMailer.delivery_method = :test
AppRoutes.draw do
match ':controller(/:action(/:id))'
match '/welcome' => "foo#bar", :as => "welcome"
assert_deprecated do
AppRoutes.draw do |map|
map.connect ':controller/:action/:id'
map.welcome 'welcome', :controller=>"foo", :action=>"bar"
end
end
expected = new_mail
@@ -67,7 +71,6 @@ class ActionMailerUrlTest < ActionMailer::TestCase
expected.body = "Hello there,\n\nMr. #{@recipient}. Please see our greeting at http://example.com/welcome/greeting http://www.basecamphq.com/welcome\n\n<img alt=\"Somelogo\" src=\"/images/somelogo.png\" />"
expected.from = "system@loudthinking.com"
expected.date = Time.local(2004, 12, 12)
expected.content_type = "text/html"
created = nil
assert_nothing_raised { created = UrlTestMailer.signed_up_with_url(@recipient) }

View File

@@ -2,10 +2,11 @@ require 'abstract_unit'
class TestHelperMailer < ActionMailer::Base
def test
recipients "test@example.com"
from "tester@example.com"
@world = "Earth"
mail :body => render(:inline => "Hello, <%= @world %>"),
:to => "test@example.com",
:from => "tester@example.com"
render(:inline => "Hello, <%= @world %>")
end
end

View File

@@ -1,28 +0,0 @@
require 'abstract_unit'
class TestTestMailer < ActionMailer::Base
end
class CrazyNameMailerTest < ActionMailer::TestCase
tests TestTestMailer
def test_set_mailer_class_manual
assert_equal TestTestMailer, self.class.mailer_class
end
end
class CrazySymbolNameMailerTest < ActionMailer::TestCase
tests :test_test_mailer
def test_set_mailer_class_manual_using_symbol
assert_equal TestTestMailer, self.class.mailer_class
end
end
class CrazyStringNameMailerTest < ActionMailer::TestCase
tests 'test_test_mailer'
def test_set_mailer_class_manual_using_string
assert_equal TestTestMailer, self.class.mailer_class
end
end

5329
actionpack/CHANGELOG Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,781 +0,0 @@
## Rails 3.2.19 (Jul 2, 2014) ##
* Fix regression when using `ActionView::Helpers::TranslationHelper#translate` with
`options[:raise]`.
This regression was introduced at ec16ba75a5493b9da972eea08bae630eba35b62f.
*Shota Fukumori (sora_h)*
## Rails 3.2.18 (May 6, 2014) ##
* Only accept actions without File::SEPARATOR in the name.
This will avoid directory traversal in implicit render.
Fixes: CVE-2014-0130
*Rafael Mendonça França*
## Rails 3.2.17 (Feb 18, 2014) ##
* Use the reference for the mime type to get the format
Fixes: CVE-2014-0082
* Escape format, negative_format and units options of number helpers
Fixes: CVE-2014-0081
## Rails 3.2.16 (Dec 12, 2013) ##
* Deep Munge the parameters for GET and POST Fixes CVE-2013-6417
* Stop using i18n's built in HTML error handling. Fixes: CVE-2013-4491
* Escape the unit value provided to number_to_currency Fixes CVE-2013-6415
* Only use valid mime type symbols as cache keys CVE-2013-6414
## Rails 3.2.15 (Oct 16, 2013) ##
* Fix `ActionDispatch::RemoteIp::GetIp#calculate_ip` to only check for spoofing
attacks if both `HTTP_CLIENT_IP` and `HTTP_X_FORWARDED_FOR` are set.
Fixes #12410
Backports #10844
*Tamir Duberstein*
* Fix the assert_recognizes test method so that it works when there are
constraints on the querystring.
Issue/Pull Request #9368
Backport #5219
*Brian Hahn*
* Fix to render partial by context(#11605).
*Kassio Borges*
* Fix `ActionDispatch::Assertions::ResponseAssertions#assert_redirected_to`
does not show user-supplied message.
Issue: when `assert_redirected_to` fails due to the response redirect not
matching the expected redirect the user-supplied message (second parameter)
is not shown. This message is only shown if the response is not a redirect.
*Alexey Chernenkov*
## Rails 3.2.14 (Jul 22, 2013) ##
* Merge `:action` from routing scope and assign endpoint if both `:controller`
and `:action` are present. The endpoint assignment only occurs if there is
no `:to` present in the options hash so should only affect routes using the
shorthand syntax (i.e. endpoint is inferred from the the path).
Fixes #9856
*Yves Senn*, *Andrew White*
* Always escape the result of `link_to_unless` method.
Before:
link_to_unless(true, '<b>Showing</b>', 'github.com')
# => "<b>Showing</b>"
After:
link_to_unless(true, '<b>Showing</b>', 'github.com')
# => "&lt;b&gt;Showing&lt;/b&gt;"
*dtaniwaki*
* Use a case insensitive URI Regexp for #asset_path.
This fix a problem where the same asset path using different case are generating
different URIs.
Before:
image_tag("HTTP://google.com")
# => "<img alt=\"Google\" src=\"/assets/HTTP://google.com\" />"
image_tag("http://google.com")
# => "<img alt=\"Google\" src=\"http://google.com\" />"
After:
image_tag("HTTP://google.com")
# => "<img alt=\"Google\" src=\"HTTP://google.com\" />"
image_tag("http://google.com")
# => "<img alt=\"Google\" src=\"http://google.com\" />"
*David Celis + Rafael Mendonça França*
* Fix explicit names on multiple file fields. If a file field tag has
the multiple option, it is turned into an array field (appending `[]`),
but if an explicit name is passed to `file_field` the `[]` is not
appended.
Fixes #9830.
*Ryan McGeary*
* Fix assets loading performance in 3.2.13.
Issue #8756 uses Sprockets for resolving files that already exist on disk,
for those files their extensions don't need to be rewritten.
Fixes #9803.
*Fred Wu*
* Fix `ActionController#action_missing` not being called.
Fixes #9799.
*Janko Luin*
* `ActionView::Helpers::NumberHelper#number_to_human` returns the number unaltered when
the units hash does not contain the needed key, e.g. when the number provided is less
than the largest key provided.
Examples:
number_to_human(123, units: {}) # => 123
number_to_human(123, units: { thousand: 'k' }) # => 123
Fixes #9269.
Backport #9347.
*Michael Hoffman*
* Include I18n locale fallbacks in view lookup.
Fixes GH#3512.
*Juan Barreneche*
* Fix `ActionDispatch::Request#formats` when the Accept request-header is an
empty string. Fix #7774 [Backport #8977, #9541]
*Soylent + Maxime Réty*
## Rails 3.2.13 (Mar 18, 2013) ##
* Fix incorrectly appended square brackets to a multiple select box
if an explicit name has been given and it already ends with "[]".
Before:
select(:category, [], {}, multiple: true, name: "post[category][]")
# => <select name="post[category][][]" ...>
After:
select(:category, [], {}, multiple: true, name: "post[category][]")
# => <select name="post[category][]" ...>
Backport #9616.
*Olek Janiszewski*
* Determine the controller#action from only the matched path when using the
shorthand syntax. Previously the complete path was used, which led
to problems with nesting (scopes and namespaces).
Fixes #7554.
Backport #9361.
Example:
# this will route to questions#new
scope ':locale' do
get 'questions/new'
end
*Yves Senn*
* Fix `assert_template` with `render :stream => true`.
Fix #1743.
Backport #5288.
*Sergey Nartimov*
* Eagerly populate the http method lookup cache so local project inflections do
not interfere with use of underscore method ( and we don't need locks )
*Aditya Sanghi*
* `BestStandardsSupport` no longer duplicates `X-UA-Compatible` values on
each request to prevent header size from blowing up.
*Edward Anderson*
* Fixed JSON params parsing regression for non-object JSON content.
*Dylan Smith*
* Prevent unnecessary asset compilation when using `javascript_include_tag` on
files with non-standard extensions.
*Noah Silas*
* Fixes issue where duplicate assets can be required with sprockets.
*Jeremy Jackson*
* Bump `rack` dependency to 1.4.3, eliminate `Rack::File` headers deprecation warning.
*Sam Ruby + Carlos Antonio da Silva*
* Do not append second slash to `root_url` when using `trailing_slash: true`
Fix #8700.
Backport #8701.
Example:
# before
root_url # => http://test.host//
# after
root_url # => http://test.host/
*Yves Senn*
* Fix a bug in `content_tag_for` that prevents it for work without a block.
*Jasl*
* Clear url helper methods when routes are reloaded by removing the methods
explicitly rather than just clearing the module because it didn't work
properly and could be the source of a memory leak.
*Andrew White*
* Fix a bug in `ActionDispatch::Request#raw_post` that caused `env['rack.input']`
to be read but not rewound.
*Matt Venables*
* More descriptive error messages when calling `render :partial` with
an invalid `:layout` argument.
Fixes #8376.
render :partial => 'partial', :layout => true
# results in ActionView::MissingTemplate: Missing partial /true
*Yves Senn*
* Accept symbols as `#send_data` :disposition value. [Backport #8329] *Elia Schito*
* Add i18n scope to `distance_of_time_in_words`. [Backport #7997] *Steve Klabnik*
* Fix side effect of `url_for` changing the `:controller` string option. [Backport #6003]
Before:
controller = '/projects'
url_for :controller => controller, :action => 'status'
puts controller #=> 'projects'
After
puts controller #=> '/projects'
*Nikita Beloglazov + Andrew White*
* Introduce `ActionView::Template::Handlers::ERB.escape_whitelist`. This is a list
of mime types where template text is not html escaped by default. It prevents `Jack & Joe`
from rendering as `Jack &amp; Joe` for the whitelisted mime types. The default whitelist
contains text/plain. Fix #7976 [Backport #8235]
*Joost Baaij*
* `BestStandardsSupport` middleware now appends it's `X-UA-Compatible` value to app's
returned value if any. Fix #8086 [Backport #8093]
*Nikita Afanasenko*
* prevent double slashes in engine urls when `Rails.application.default_url_options[:trailing_slash] = true` is set
Fix #7842
*Yves Senn*
* Fix input name when `:multiple => true` and `:index` are set.
Before:
check_box("post", "comment_ids", { :multiple => true, :index => "foo" }, 1)
#=> <input name=\"post[foo][comment_ids]\" type=\"hidden\" value=\"0\" /><input id=\"post_foo_comment_ids_1\" name=\"post[foo][comment_ids]\" type=\"checkbox\" value=\"1\" />
After:
check_box("post", "comment_ids", { :multiple => true, :index => "foo" }, 1)
#=> <input name=\"post[foo][comment_ids][]\" type=\"hidden\" value=\"0\" /><input id=\"post_foo_comment_ids_1\" name=\"post[foo][comment_ids][]\" type=\"checkbox\" value=\"1\" />
Fix #8108
*Daniel Fox, Grant Hutchins & Trace Wax*
## Rails 3.2.12 (Feb 11, 2013) ##
* No changes.
## Rails 3.2.11 (Jan 8, 2013) ##
* Strip nils from collections on JSON and XML posts. [CVE-2013-0155]
## Rails 3.2.10 (Jan 2, 2013) ##
* No changes.
## Rails 3.2.9 (Nov 12, 2012) ##
* Clear url helpers when reloading routes.
*Santiago Pastorino*
* Revert the shorthand routes scoped with `:module` option fix
This added a regression since it is changing the URL mapping.
This makes the stable release backward compatible.
*Rafael Mendonça França*
* Revert the `assert_template` fix to not pass with ever string that matches the template name.
This added a regression since people were relying on this buggy behavior.
This will introduce back #3849 but this stable release will be backward compatible.
Fixes #8068.
*Rafael Mendonça França*
* Revert the rename of internal variable on ActionController::TemplateAssertions to prevent
naming collisions. This added a regression related with shoulda-matchers, since it is
expecting the [instance variable @layouts](https://github.com/thoughtbot/shoulda-matchers/blob/9e1188eea68c47d9a56ce6280e45027da6187ab1/lib/shoulda/matchers/action_controller/render_with_layout_matcher.rb#L74).
This will introduce back #7459 but this stable release will be backward compatible.
Fixes #8068.
*Rafael Mendonça França*
* Accept :remote as symbolic option for `link_to` helper. *Riley Lynch*
* Warn when the `:locals` option is passed to `assert_template` outside of a view test case
Fix #3415
*Yves Senn*
* Rename internal variables on ActionController::TemplateAssertions to prevent
naming collisions. @partials, @templates and @layouts are now prefixed with an underscore.
Fix #7459
*Yves Senn*
* `resource` and `resources` don't modify the passed options hash
Fix #7777
*Yves Senn*
* Precompiled assets include aliases from foo.js to foo/index.js and vice versa.
# Precompiles phone-<digest>.css and aliases phone/index.css to phone.css.
config.assets.precompile = [ 'phone.css' ]
# Precompiles phone/index-<digest>.css and aliases phone.css to phone/index.css.
config.assets.precompile = [ 'phone/index.css' ]
# Both of these work with either precompile thanks to their aliases.
<%= stylesheet_link_tag 'phone', media: 'all' %>
<%= stylesheet_link_tag 'phone/index', media: 'all' %>
*Jeremy Kemper*
* `assert_template` is no more passing with what ever string that matches
with the template name.
Before when we have a template `/layout/hello.html.erb`, `assert_template`
was passing with any string that matches. This behavior allowed false
positive like:
assert_template "layout"
assert_template "out/hello"
Now it only passes with:
assert_template "layout/hello"
assert_template "hello"
Fixes #3849.
*Hugolnx*
* Handle `ActionDispatch::Http::UploadedFile` like `Rack::Test::UploadedFile`, don't call to_param on it. Since
`Rack::Test::UploadedFile` isn't API compatible this is needed to test file uploads that rely on `tempfile`
being available.
*Tim Vandecasteele*
* Respect `config.digest = false` for `asset_path`
Previously, the `asset_path` internals only respected the `:digest`
option, but ignored the global config setting. This meant that
`config.digest = false` could not be used in conjunction with
`config.compile = false` this corrects the behavior.
*Peter Wagenet*
* Fix #7646, the log now displays the correct status code when an exception is raised.
*Yves Senn*
* Fix handling of date selects when using both disabled and discard options.
Fixes #7431.
*Vasiliy Ermolovich*
* Fix select_tag when option_tags is nil.
Fixes #7404.
*Sandeep Ravichandran*
* `javascript_include_tag :all` will now not include `application.js` if the file does not exists. *Prem Sichanugrist*
* Support cookie jar options (e.g., domain :all) for all session stores.
Fixes GH#3047, GH#2483.
*Ravil Bayramgalin*
* Performance Improvement to send_file: Avoid having to pass an open file handle as the response body. Rack::Sendfile
will usually intercept the response and just uses the path directly, so no reason to open the file. This performance
improvement also resolves an issue with jRuby encodings, and is the reason for the backport, see issue #6844.
*Jeremy Kemper & Erich Menge*
## Rails 3.2.8 (Aug 9, 2012) ##
* There is an XSS vulnerability in the strip_tags helper in Ruby on Rails, the
helper doesn't correctly handle malformed html. As a result an attacker can
execute arbitrary javascript through the use of specially crafted malformed
html.
*Marek from Nethemba (www.nethemba.com) & Santiago Pastorino*
* When a "prompt" value is supplied to the `select_tag` helper, the "prompt" value is not escaped.
If untrusted data is not escaped, and is supplied as the prompt value, there is a potential for XSS attacks.
Vulnerable code will look something like this:
select_tag("name", options, :prompt => UNTRUSTED_INPUT)
*Santiago Pastorino*
* Reverted the deprecation of `:confirm`. *Rafael Mendonça França*
* Reverted the deprecation of `:disable_with`. *Rafael Mendonça França*
* Reverted the deprecation of `:mouseover` option to `image_tag`. *Rafael Mendonça França*
* Reverted the deprecation of `button_to_function` and `link_to_function` helpers.
*Rafael Mendonça França*
## Rails 3.2.7 (Jul 26, 2012) ##
* Do not convert digest auth strings to symbols. CVE-2012-3424
* Bump Journey requirements to 1.0.4
* Add support for optional root segments containing slashes
* Fixed bug creating invalid HTML in select options
* Show in log correct wrapped keys
* Fix NumberHelper options wrapping to prevent verbatim blocks being rendered instead of line continuations.
* ActionController::Metal doesn't have logger method, check it and then delegate
* ActionController::Caching depends on RackDelegation and AbstractController::Callbacks
## Rails 3.2.6 (Jun 12, 2012) ##
* nil is removed from array parameter values
CVE-2012-2694
* Deprecate `:confirm` in favor of `':data => { :confirm => "Text" }'` option for `button_to`, `button_tag`, `image_submit_tag`, `link_to` and `submit_tag` helpers.
*Carlos Galdino*
* Allow to use mounted_helpers (helpers for accessing mounted engines) in ActionView::TestCase. *Piotr Sarnacki*
* Include mounted_helpers (helpers for accessing mounted engines) in ActionDispatch::IntegrationTest by default. *Piotr Sarnacki*
## Rails 3.2.5 (Jun 1, 2012) ##
* No changes.
## Rails 3.2.4 (May 31, 2012) ##
* Deprecate old APIs for highlight, excerpt and word_wrap *Jeremy Walker*
* Deprecate `:disable_with` in favor of `'data-disable-with'` option for `button_to`, `button_tag` and `submit_tag` helpers.
*Carlos Galdino + Rafael Mendonça França*
* Deprecate `:mouseover` option for `image_tag` helper. *Rafael Mendonça França*
* Deprecate `button_to_function` and `link_to_function` helpers. *Rafael Mendonça França*
* Don't break Haml with textarea newline fix. GH #393, #4000, #5190, #5191
* Fix options handling on labels. GH #2492, #5614
* Added config.action_view.embed_authenticity_token_in_remote_forms to deal
with regression from 16ee611fa
* Set rendered_format when doing render :inline. GH #5632
* Fix the redirect when it receive blocks with arity of 1. Closes #5677
* Strip [nil] from parameters hash. Thanks to Ben Murphy for
reporting this! CVE-2012-2660
## Rails 3.2.3 (March 30, 2012) ##
* Allow to lazy load `default_form_builder` by passing a `String` instead of a constant. *Piotr Sarnacki*
* Fix #5632, render :inline set the proper rendered format. *Santiago Pastorino*
* Fix textarea rendering when using plugins like HAML. Such plugins encode the first newline character in the content. This issue was introduced in https://github.com/rails/rails/pull/5191 *James Coleman*
* Remove the leading \n added by textarea on assert_select. *Santiago Pastorino*
* Add `config.action_view.embed_authenticity_token_in_remote_forms` (defaults to true) which allows to set if authenticity token will be included by default in remote forms. If you change it to false, you can still force authenticity token by passing `:authenticity_token => true` in form options *Piotr Sarnacki*
* Do not include the authenticity token in forms where remote: true as ajax forms use the meta-tag value *DHH*
* Turn off verbose mode of rack-cache, we still have X-Rack-Cache to
check that info. Closes #5245. *Santiago Pastorino*
* Fix #5238, rendered_format is not set when template is not rendered. *Piotr Sarnacki*
* Upgrade rack-cache to 1.2. *José Valim*
* ActionController::SessionManagement is deprecated. *Santiago Pastorino*
* Since the router holds references to many parts of the system like engines, controllers and the application itself, inspecting the route set can actually be really slow, therefore we default alias inspect to to_s. *José Valim*
* Add a new line after the textarea opening tag. Closes #393 *Rafael Mendonça França*
* Always pass a respond block from to responder. We should let the responder to decide what to do with the given overridden response block, and not short circuit it. *sikachu*
* Fixes layout rendering regression from 3.2.2. *José Valim*
## Rails 3.2.2 (March 1, 2012) ##
* Format lookup for partials is derived from the format in which the template is being rendered. Closes #5025 part 2 *Santiago Pastorino*
* Use the right format when a partial is missing. Closes #5025. *Santiago Pastorino*
* Default responder will now always use your overridden block in `respond_with` to render your response. *Prem Sichanugrist*
* check_box helper with :disabled => true will generate a disabled hidden field to conform with the HTML convention where disabled fields are not submitted with the form.
This is a behavior change, previously the hidden tag had a value of the disabled checkbox.
*Tadas Tamosauskas*
## Rails 3.2.1 (January 26, 2012) ##
* Documentation improvements.
* Allow `form.select` to accept ranges (regression). *Jeremy Walker*
* `datetime_select` works with -/+ infinity dates. *Joe Van Dyk*
## Rails 3.2.0 (January 20, 2012) ##
* Setting config.assets.logger to false turn off Sprockets logger *Guillermo Iguaran*
* Add `config.action_dispatch.default_charset` to configure default charset for ActionDispatch::Response. *Carlos Antonio da Silva*
* Deprecate setting default charset at controller level, use the new `config.action_dispatch.default_charset` instead. *Carlos Antonio da Silva*
* Deprecate ActionController::UnknownAction in favour of AbstractController::ActionNotFound. *Carlos Antonio da Silva*
* Deprecate ActionController::DoubleRenderError in favour of AbstractController::DoubleRenderError. *Carlos Antonio da Silva*
* Deprecate method_missing handling for not found actions, use action_missing instead. *Carlos Antonio da Silva*
* Deprecate ActionController#rescue_action, ActionController#initialize_template_class, and ActionController#assign_shortcuts.
These methods were not being used internally anymore and are going to be removed in Rails 4. *Carlos Antonio da Silva*
* Add config.assets.logger to configure Sprockets logger *Rafael França*
* Use a BodyProxy instead of including a Module that responds to
close. Closes #4441 if Active Record is disabled assets are delivered
correctly *Santiago Pastorino*
* Rails initialization with initialize_on_precompile = false should set assets_dir *Santiago Pastorino*
* Add font_path helper method *Santiago Pastorino*
* Depends on rack ~> 1.4.0 *Santiago Pastorino*
* Add :gzip option to `caches_page`. The default option can be configured globally using `page_cache_compression` *Andrey Sitnik*
* The ShowExceptions middleware now accepts a exceptions application that is responsible to render an exception when the application fails. The application is invoked with a copy of the exception in `env["action_dispatch.exception"]` and with the PATH_INFO rewritten to the status code. *José Valim*
* Add `button_tag` support to ActionView::Helpers::FormBuilder.
This support mimics the default behavior of `submit_tag`.
Example:
<%= form_for @post do |f| %>
<%= f.button %>
<% end %>
* Date helpers accept a new option, `:use_two_digit_numbers = true`, that renders select boxes for months and days with a leading zero without changing the respective values.
For example, this is useful for displaying ISO8601-style dates such as '2011-08-01'. *Lennart Fridén and Kim Persson*
* Make ActiveSupport::Benchmarkable a default module for ActionController::Base, so the #benchmark method is once again available in the controller context like it used to be *DHH*
* Deprecated implied layout lookup in controllers whose parent had a explicit layout set:
class ApplicationController
layout "application"
end
class PostsController < ApplicationController
end
In the example above, Posts controller will no longer automatically look up for a posts layout.
If you need this functionality you could either remove `layout "application"` from ApplicationController or explicitly set it to nil in PostsController. *José Valim*
* Rails will now use your default layout (such as "layouts/application") when you specify a layout with `:only` and `:except` condition, and those conditions fail. *Prem Sichanugrist*
For example, consider this snippet:
class CarsController
layout 'single_car', :only => :show
end
Rails will use 'layouts/single_car' when a request comes in `:show` action, and use 'layouts/application' (or 'layouts/cars', if exists) when a request comes in for any other actions.
* form_for with +:as+ option uses "#{action}_#{as}" as css class and id:
Before:
form_for(@user, :as => 'client') # => "<form class="client_new">..."
Now:
form_for(@user, :as => 'client') # => "<form class="new_client">..."
*Vasiliy Ermolovich*
* Allow rescue responses to be configured through a railtie as in `config.action_dispatch.rescue_responses`. Please look at ActiveRecord::Railtie for an example *José Valim*
* Allow fresh_when/stale? to take a record instead of an options hash *DHH*
* Assets should use the request protocol by default or default to relative if no request is available *Jonathan del Strother*
* Log "Filter chain halted as CALLBACKNAME rendered or redirected" every time a before callback halts *José Valim*
* You can provide a namespace for your form to ensure uniqueness of id attributes on form elements.
The namespace attribute will be prefixed with underscore on the generate HTML id. *Vasiliy Ermolovich*
Example:
<%= form_for(@offer, :namespace => 'namespace') do |f| %>
<%= f.label :version, 'Version' %>:
<%= f.text_field :version %>
<% end %>
* Refactor ActionDispatch::ShowExceptions. The controller is responsible for choosing to show exceptions when `consider_all_requests_local` is false.
It's possible to override `show_detailed_exceptions?` in controllers to specify which requests should provide debugging information on errors. The default value is now false, meaning local requests in production will no longer show the detailed exceptions page unless `show_detailed_exceptions?` is overridden and set to `request.local?`.
* Responders now return 204 No Content for API requests without a response body (as in the new scaffold) *José Valim*
* Added ActionDispatch::RequestId middleware that'll make a unique X-Request-Id header available to the response and enables the ActionDispatch::Request#uuid method. This makes it easy to trace requests from end-to-end in the stack and to identify individual requests in mixed logs like Syslog *DHH*
* Limit the number of options for select_year to 1000.
Pass the :max_years_allowed option to set your own limit.
*Libo Cannici*
* Passing formats or handlers to render :template and friends is deprecated. For example: *Nick Sutterer & José Valim*
render :template => "foo.html.erb"
Instead, you can provide :handlers and :formats directly as option:
render :template => "foo", :formats => [:html, :js], :handlers => :erb
* Changed log level of warning for missing CSRF token from :debug to :warn. *Mike Dillon*
* content_tag_for and div_for can now take the collection of records. It will also yield the record as the first argument if you set a receiving argument in your block *Prem Sichanugrist*
So instead of having to do this:
@items.each do |item|
content_tag_for(:li, item) do
Title: <%= item.title %>
end
end
You can now do this:
content_tag_for(:li, @items) do |item|
Title: <%= item.title %>
end
* send_file now guess the mime type *Esad Hajdarevic*
* Mime type entries for PDF, ZIP and other formats were added *Esad Hajdarevic*
* Generate hidden input before select with :multiple option set to true.
This is useful when you rely on the fact that when no options is set,
the state of select will be sent to rails application. Without hidden field
nothing is sent according to HTML spec *Bogdan Gusiev*
* Refactor ActionController::TestCase cookies *Andrew White*
Assigning cookies for test cases should now use cookies[], e.g:
cookies[:email] = 'user@example.com'
get :index
assert_equal 'user@example.com', cookies[:email]
To clear the cookies, use clear, e.g:
cookies.clear
get :index
assert_nil cookies[:email]
We now no longer write out HTTP_COOKIE and the cookie jar is
persistent between requests so if you need to manipulate the environment
for your test you need to do it before the cookie jar is created.
* ActionController::ParamsWrapper on ActiveRecord models now only wrap
attr_accessible attributes if they were set, if not, only the attributes
returned by the class method attribute_names will be wrapped. This fixes
the wrapping of nested attributes by adding them to attr_accessible.
Please check [3-1-stable](https://github.com/rails/rails/blob/3-1-stable/actionpack/CHANGELOG.md) for previous changes.

View File

@@ -1,4 +1,4 @@
Copyright (c) 2004-2011 David Heinemeier Hansson
Copyright (c) 2004-2010 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

View File

@@ -19,8 +19,9 @@ It consists of several modules:
* Action View, which handles view template lookup and rendering, and provides
view helpers that assist when building HTML forms, Atom feeds and more.
Template formats that Action View handles are ERB (embedded Ruby, typically
used to inline short Ruby snippets inside HTML), and XML Builder.
Template formats that Action View handles are ERb (embedded Ruby, typically
used to inline short Ruby snippets inside HTML), XML Builder and RJS
(dynamically generated JavaScript from Ruby code).
With the Ruby on Rails framework, users only directly interface with the
Action Controller module. Necessary Action Dispatch functionality is activated
@@ -33,7 +34,7 @@ A short rundown of some of the major features:
* Actions grouped in controller as methods instead of separate command objects
and can therefore share helper methods
class CustomersController < ActionController::Base
CustomersController < ActionController::Base
def show
@customer = find_customer
end
@@ -56,9 +57,9 @@ A short rundown of some of the major features:
{Learn more}[link:classes/ActionController/Base.html]
* ERB templates (static content mixed with dynamic output from ruby)
* ERb templates (static content mixed with dynamic output from ruby)
<% @posts.each do |post| %>
<% for post in @posts %>
Title: <%= post.title %>
<% end %>
@@ -81,7 +82,7 @@ A short rundown of some of the major features:
xml.language "en-us"
xml.ttl "40"
@recent_items.each do |item|
for item in @recent_items
xml.item do
xml.title(item_title(item))
xml.description(item_description(item))
@@ -218,7 +219,7 @@ A short rundown of some of the major features:
def show
# the output of the method will be cached as
# ActionController::Base.page_cache_directory + "/weblog/show.html"
# ActionController::Base.page_cache_directory + "/weblog/show/n.html"
# and the web server will pick it up without even hitting Rails
end
@@ -261,7 +262,7 @@ methods:
layout "weblog/layout"
def index
@posts = Post.all
@posts = Post.find(:all)
end
def show
@@ -283,7 +284,7 @@ methods:
The last two lines are responsible for telling ActionController where the
template files are located and actually running the controller on a new
request from the web-server (e.g., Apache).
request from the web-server (like to be Apache).
And the templates look like this:
@@ -293,7 +294,7 @@ And the templates look like this:
</body></html>
weblog/index.html.erb:
<% @posts.each do |post| %>
<% for post in @posts %>
<p><%= link_to(post.title, :action => "show", :id => post.id) %></p>
<% end %>
@@ -316,13 +317,13 @@ an URL such as /weblog/5 (where 5 is the id of the post).
== Download and installation
The latest version of Action Pack can be installed with RubyGems:
The latest version of Action Pack can be installed with Rubygems:
% [sudo] gem install actionpack
Source code can be downloaded as part of the Rails project on GitHub
* https://github.com/rails/rails/tree/3-2-stable/actionpack
* http://github.com/rails/rails/tree/master/actionpack/
== License
@@ -334,8 +335,8 @@ Action Pack is released under the MIT license.
API documentation is at
* http://api.rubyonrails.org
* http://api.rubyonrails.com
Bug reports and feature requests can be filed with the rest for the Ruby on Rails project here:
* https://github.com/rails/rails/issues
* https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets

View File

@@ -8,18 +8,15 @@ Rake can be found at http://rake.rubyforge.org
== Running by hand
To run a single test suite
If you only want to run a single test suite, or don't want to bother with Rake,
you can do so with something like:
rake test TEST=path/to/test.rb
ruby -Itest test/controller/base_tests.rb
which can be further narrowed down to one test:
== Dependency on ActiveRecord and database setup
rake test TEST=path/to/test.rb TESTOPTS="--name=test_something"
== Dependency on Active Record and database setup
Test cases in the test/active_record/ directory depend on having
activerecord and sqlite installed. If Active Record is not in
Test cases in the test/controller/active_record/ directory depend on having
activerecord and sqlite installed. If ActiveRecord is not in
actionpack/../activerecord directory, or the sqlite rubygem is not installed,
these tests are skipped.

14
actionpack/Rakefile Executable file → Normal file
View File

@@ -1,7 +1,7 @@
#!/usr/bin/env rake
require 'rake'
require 'rake/testtask'
require 'rake/packagetask'
require 'rubygems/package_task'
require 'rake/gempackagetask'
desc "Default Task"
task :default => :test
@@ -18,19 +18,13 @@ Rake::TestTask.new(:test_action_pack) do |t|
# this will not happen automatically and the tests (as a whole) will error
t.test_files = Dir.glob('test/{abstract,controller,dispatch,template}/**/*_test.rb').sort
t.warning = true
t.verbose = true
# t.warning = true
end
namespace :test do
Rake::TestTask.new(:isolated) do |t|
t.pattern = 'test/ts_isolated.rb'
end
Rake::TestTask.new(:template) do |t|
t.libs << 'test'
t.pattern = 'test/template/**/*.rb'
end
end
desc 'ActiveRecord Integration Tests'
@@ -41,7 +35,7 @@ end
spec = eval(File.read('actionpack.gemspec'))
Gem::PackageTask.new(spec) do |p|
Rake::GemPackageTask.new(spec) do |p|
p.gem_spec = spec
end

View File

@@ -6,27 +6,26 @@ Gem::Specification.new do |s|
s.version = version
s.summary = 'Web-flow and rendering framework putting the VC in MVC (part of Rails).'
s.description = 'Web apps on Rails. Simple, battle-tested conventions for building and testing MVC web applications. Works with any Rack-compatible server.'
s.license = 'MIT'
s.required_ruby_version = '>= 1.8.7'
s.author = 'David Heinemeier Hansson'
s.email = 'david@loudthinking.com'
s.homepage = 'http://www.rubyonrails.org'
s.rubyforge_project = 'actionpack'
s.files = Dir['CHANGELOG.md', 'README.rdoc', 'MIT-LICENSE', 'lib/**/*']
s.files = Dir['CHANGELOG', 'README.rdoc', 'MIT-LICENSE', 'lib/**/*']
s.require_path = 'lib'
s.requirements << 'none'
s.has_rdoc = true
s.add_dependency('activesupport', version)
s.add_dependency('activemodel', version)
s.add_dependency('rack-cache', '~> 1.2')
s.add_dependency('builder', '~> 3.2')
s.add_dependency('rack', '~> 1.4.5')
s.add_dependency('rack-test', '~> 0.6.1')
s.add_dependency('journey', '~> 1.0.4')
s.add_dependency('erubis', '~> 2.7.0')
s.add_development_dependency('tzinfo', '~> 0.3.29')
s.add_dependency('builder', '~> 2.1.2')
s.add_dependency('i18n', '~> 0.4.1')
s.add_dependency('rack', '~> 1.2.1')
s.add_dependency('rack-test', '~> 0.5.6')
s.add_dependency('rack-mount', '~> 0.6.13')
s.add_dependency('tzinfo', '~> 0.3.23')
s.add_dependency('erubis', '~> 2.6.6')
end

View File

@@ -1,185 +0,0 @@
ENV['RAILS_ENV'] ||= 'production'
require File.expand_path('../../../load_paths', __FILE__)
require 'action_pack'
require 'action_controller'
require 'action_view'
require 'active_model'
require 'benchmark'
MyHash = Class.new(Hash)
Hash.class_eval do
extend ActiveModel::Naming
include ActiveModel::Conversion
end
class Runner
def initialize(app, output)
@app, @output = app, output
end
def puts(*)
super if @output
end
def call(env)
env['n'].to_i.times { @app.call(env) }
@app.call(env).tap { |response| report(env, response) }
end
def report(env, response)
return unless ENV["DEBUG"]
out = env['rack.errors']
out.puts response[0], response[1].to_yaml, '---'
response[2].each { |part| out.puts part }
out.puts '---'
end
def self.puts(*)
super if @output
end
def self.print(*)
super if @output
end
def self.app_and_env_for(action, n)
env = Rack::MockRequest.env_for("/")
env.merge!('n' => n, 'rack.input' => StringIO.new(''), 'rack.errors' => $stdout)
app = lambda { |env| BasePostController.action(action).call(env) }
return app, env
end
$ran = []
def self.run(action, n, output = true)
print "."
STDOUT.flush
@output = output
label = action.to_s
app, env = app_and_env_for(action, n)
t = Benchmark.realtime { new(app, output).call(env) }
$ran << [label, (t * 1000).to_i.to_s] if output
end
def self.done
puts
header, content = "", ""
$ran.each do |k,v|
size = [k.size, v.size].max + 1
header << format("%#{size}s", k)
content << format("%#{size}s", v)
end
puts header
puts content
end
end
ActionController::Base.logger = nil
ActionController::Base.config.compile_methods!
ActionView::Resolver.caching = ENV["RAILS_ENV"] == "production"
class BasePostController < ActionController::Base
append_view_path "#{File.dirname(__FILE__)}/views"
def overhead
self.response_body = ''
end
def index
render :text => ''
end
$OBJECT = {:name => "Hello my name is omg", :address => "333 omg"}
def partial
render :partial => "/collection", :object => $OBJECT
end
def partial_10
render :partial => "/ten_partials"
end
def partial_100
render :partial => "/hundred_partials"
end
$COLLECTION1 = []
10.times do |i|
$COLLECTION1 << { :name => "Hello my name is omg", :address => "333 omg" }
end
def coll_10
render :partial => "/collection", :collection => $COLLECTION1
end
$COLLECTION2 = []
100.times do |i|
$COLLECTION2 << { :name => "Hello my name is omg", :address => "333 omg" }
end
def coll_100
render :partial => "/collection", :collection => $COLLECTION2
end
def uniq_100
render :partial => $COLLECTION2
end
$COLLECTION3 = []
50.times do |i|
$COLLECTION3 << {:name => "Hello my name is omg", :address => "333 omg"}
$COLLECTION3 << MyHash.new(:name => "Hello my name is omg", :address => "333 omg")
end
def diff_100
render :partial => $COLLECTION3
end
def template_1
render :template => "template"
end
module Foo
def omg
"omg"
end
end
helper Foo
end
N = (ENV['N'] || 1000).to_i
# ActionController::Base.use_accept_header = false
def run_all!(times, verbose)
Runner.run(:overhead, times, verbose)
Runner.run(:index, times, verbose)
Runner.run(:template_1, times, verbose)
Runner.run(:partial, times, verbose)
Runner.run(:partial_10, times, verbose)
Runner.run(:coll_10, times, verbose)
Runner.run(:partial_100, times, verbose)
Runner.run(:coll_100, times, verbose)
Runner.run(:uniq_100, times, verbose)
Runner.run(:diff_100, times, verbose)
end
unless ENV["PROFILE"]
run_all!(1, false)
(ENV["M"] || 1).to_i.times do
$ran = []
run_all!(N, true)
Runner.done
end
else
Runner.run(ENV["PROFILE"].to_sym, 1, false)
require "ruby-prof"
RubyProf.start
Runner.run(ENV["PROFILE"].to_sym, N, true)
result = RubyProf.stop
printer = RubyProf::CallStackPrinter.new(result)
printer.print(File.open("output.html", "w"))
end

View File

@@ -1,3 +0,0 @@
<%= collection[:name] %>
<%= collection[:address] %>
<%= omg %>

View File

@@ -1 +0,0 @@
Hello

View File

@@ -1,3 +0,0 @@
<% 100.times do %>
<%= render :partial => "/collection", :object => $OBJECT %>
<% end %>

View File

@@ -1,10 +0,0 @@
<%= "Hello" %>
<%= "Hello" %>
<%= "Hello" %>
<%= "Hello" %>
<%= "Hello" %>
<%= "Hello" %>
<%= "Hello" %>
<%= "Hello" %>
<%= "Hello" %>
<%= "Hello" %>

View File

@@ -1,10 +0,0 @@
<%= render :partial => '/collection', :object => $OBJECT %>
<%= render :partial => '/collection', :object => $OBJECT %>
<%= render :partial => '/collection', :object => $OBJECT %>
<%= render :partial => '/collection', :object => $OBJECT %>
<%= render :partial => '/collection', :object => $OBJECT %>
<%= render :partial => '/collection', :object => $OBJECT %>
<%= render :partial => '/collection', :object => $OBJECT %>
<%= render :partial => '/collection', :object => $OBJECT %>
<%= render :partial => '/collection', :object => $OBJECT %>
<%= render :partial => '/collection', :object => $OBJECT %>

View File

@@ -1,3 +0,0 @@
<%= hash[:name] %>
<%= hash[:address] %>
<%= omg %>

View File

@@ -1,3 +0,0 @@
<%= my_hash[:name] %>
<%= my_hash[:address] %>
<%= omg %>

View File

@@ -1 +0,0 @@
Hello

View File

@@ -24,5 +24,4 @@ module AbstractController
autoload :Translation
autoload :AssetPaths
autoload :ViewPaths
autoload :UrlFor
end

View File

@@ -3,8 +3,7 @@ module AbstractController
extend ActiveSupport::Concern
included do
config_accessor :asset_host, :asset_path, :assets_dir, :javascripts_dir,
:stylesheets_dir, :default_asset_host_protocol, :relative_url_root
config_accessor :asset_host, :asset_path, :assets_dir, :javascripts_dir, :stylesheets_dir
end
end
end
end

View File

@@ -1,4 +1,3 @@
require 'erubis'
require 'active_support/configurable'
require 'active_support/descendants_tracker'
require 'active_support/core_ext/module/anonymous'
@@ -10,7 +9,7 @@ module AbstractController
# <tt>AbstractController::Base</tt> is a low-level API. Nobody should be
# using it directly, and subclasses (like ActionController::Base) are
# expected to provide their own +render+ method, since rendering means
# different things depending on the context.
# different things depending on the context.
class Base
attr_internal :response_body
attr_internal :action_name
@@ -19,7 +18,6 @@ module AbstractController
include ActiveSupport::Configurable
extend ActiveSupport::DescendantsTracker
undef_method :not_implemented
class << self
attr_reader :abstract
alias_method :abstract?, :abstract
@@ -33,9 +31,10 @@ module AbstractController
# A list of all internal methods for a controller. This finds the first
# abstract superclass of a controller, and gets a list of all public
# instance methods on that abstract class. Public instance methods of
# a controller would normally be considered action methods, so methods
# declared on abstract classes are being removed.
# (ActionController::Metal and ActionController::Base are defined as abstract)
# a controller would normally be considered action methods, so we
# are removing those methods on classes declared as abstract
# (ActionController::Metal and ActionController::Base are defined
# as abstract)
def internal_methods
controller = self
controller = controller.superclass until controller.abstract?
@@ -63,13 +62,13 @@ module AbstractController
def action_methods
@action_methods ||= begin
# All public instance methods of this class, including ancestors
methods = (public_instance_methods(true) -
methods = public_instance_methods(true).map { |m| m.to_s }.to_set -
# Except for public instance methods of Base and its ancestors
internal_methods +
internal_methods.map { |m| m.to_s } +
# Be sure to include shadowed public instance methods of this class
public_instance_methods(false)).uniq.map { |x| x.to_s } -
public_instance_methods(false).map { |m| m.to_s } -
# And always exclude explicitly hidden actions
hidden_actions.to_a
hidden_actions
# Clear out AS callback method pollution
methods.reject { |method| method =~ /_one_time_conditions/ }
@@ -112,7 +111,7 @@ module AbstractController
def process(action, *args)
@_action_name = action_name = action.to_s
unless action_name = _find_action_name(action_name)
unless action_name = method_for_action(action_name)
raise ActionNotFound, "The action '#{action}' could not be found for #{self.class.name}"
end
@@ -130,29 +129,17 @@ module AbstractController
self.class.action_methods
end
# Returns true if a method for the action is available and
# can be dispatched, false otherwise.
#
# Notice that <tt>action_methods.include?("foo")</tt> may return
# false and <tt>available_action?("foo")</tt> returns true because
# available action consider actions that are also available
# through other means, for example, implicit render ones.
def available_action?(action_name)
_find_action_name(action_name).present?
end
private
# Returns true if the name can be considered an action because
# it has a method defined in the controller.
# Returns true if the name can be considered an action. This can
# be overridden in subclasses to modify the semantics of what
# can be considered an action.
#
# ==== Parameters
# * <tt>name</tt> - The name of an action to be tested
#
# ==== Returns
# * <tt>TrueClass</tt>, <tt>FalseClass</tt>
#
# :api: private
def action_method?(name)
self.class.action_methods.include?(name)
end
@@ -160,9 +147,6 @@ module AbstractController
# Call the action. Override this in a subclass to modify the
# behavior around processing an action. This, and not #process,
# is the intended way to override action dispatching.
#
# Notice that the first argument is the method to be dispatched
# which is *not* necessarily the same as the action name.
def process_action(method_name, *args)
send_action(method_name, *args)
end
@@ -177,25 +161,8 @@ module AbstractController
# If the action name was not found, but a method called "action_missing"
# was found, #method_for_action will return "_handle_action_missing".
# This method calls #action_missing with the current action name.
def _handle_action_missing(*args)
action_missing(@_action_name, *args)
end
# Takes an action name and returns the name of the method that will
# handle the action.
#
# It checks if the action name is valid and returns false otherwise.
#
# See method_for_action for more information.
#
# ==== Parameters
# * <tt>action_name</tt> - An action name to find a method name for
#
# ==== Returns
# * <tt>string</tt> - The name of the method that handles the action
# * false - No valid method name could be found. Raise ActionNotFound.
def _find_action_name(action_name)
_valid_action_name?(action_name) && method_for_action(action_name)
def _handle_action_missing
action_missing(@_action_name)
end
# Takes an action name and returns the name of the method that will
@@ -220,16 +187,11 @@ module AbstractController
#
# ==== Returns
# * <tt>string</tt> - The name of the method that handles the action
# * <tt>nil</tt> - No method name could be found.
# * <tt>nil</tt> - No method name could be found. Raise ActionNotFound.
def method_for_action(action_name)
if action_method?(action_name) then action_name
elsif respond_to?(:action_missing, true) then "_handle_action_missing"
end
end
# Checks if the action name is valid and returns false otherwise.
def _valid_action_name?(action_name)
action_name.to_s !~ Regexp.new(File::SEPARATOR)
end
end
end

View File

@@ -13,8 +13,8 @@ module AbstractController
# Override AbstractController::Base's process_action to run the
# process_action callbacks around the normal behavior.
def process_action(*args)
run_callbacks(:process_action, action_name) do
def process_action(method_name)
run_callbacks(:process_action, method_name) do
super
end
end
@@ -29,7 +29,7 @@ module AbstractController
#
# ==== Options
# * <tt>only</tt> - The callback should be run only for this action
# * <tt>except</tt> - The callback should be run for all actions except this action
# * <tt>except<tt> - The callback should be run for all actions except this action
def _normalize_callback_options(options)
if only = options[:only]
only = Array(only).map {|o| "action_name == '#{o}'"}.join(" || ")
@@ -75,122 +75,38 @@ module AbstractController
end
end
##
# :method: before_filter
#
# :call-seq: before_filter(names, block)
#
# Append a before filter. See _insert_callbacks for parameter details.
##
# :method: prepend_before_filter
#
# :call-seq: prepend_before_filter(names, block)
#
# Prepend a before filter. See _insert_callbacks for parameter details.
##
# :method: skip_before_filter
#
# :call-seq: skip_before_filter(names, block)
#
# Skip a before filter. See _insert_callbacks for parameter details.
##
# :method: append_before_filter
#
# :call-seq: append_before_filter(names, block)
#
# Append a before filter. See _insert_callbacks for parameter details.
##
# :method: after_filter
#
# :call-seq: after_filter(names, block)
#
# Append an after filter. See _insert_callbacks for parameter details.
##
# :method: prepend_after_filter
#
# :call-seq: prepend_after_filter(names, block)
#
# Prepend an after filter. See _insert_callbacks for parameter details.
##
# :method: skip_after_filter
#
# :call-seq: skip_after_filter(names, block)
#
# Skip an after filter. See _insert_callbacks for parameter details.
##
# :method: append_after_filter
#
# :call-seq: append_after_filter(names, block)
#
# Append an after filter. See _insert_callbacks for parameter details.
##
# :method: around_filter
#
# :call-seq: around_filter(names, block)
#
# Append an around filter. See _insert_callbacks for parameter details.
##
# :method: prepend_around_filter
#
# :call-seq: prepend_around_filter(names, block)
#
# Prepend an around filter. See _insert_callbacks for parameter details.
##
# :method: skip_around_filter
#
# :call-seq: skip_around_filter(names, block)
#
# Skip an around filter. See _insert_callbacks for parameter details.
##
# :method: append_around_filter
#
# :call-seq: append_around_filter(names, block)
#
# Append an around filter. See _insert_callbacks for parameter details.
# set up before_filter, prepend_before_filter, skip_before_filter, etc.
# for each of before, after, and around.
[:before, :after, :around].each do |filter|
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
# Append a before, after or around filter. See _insert_callbacks
# for details on the allowed parameters.
def #{filter}_filter(*names, &blk) # def before_filter(*names, &blk)
_insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
options[:if] = (Array.wrap(options[:if]) << "!halted") if #{filter == :after} # options[:if] = (Array.wrap(options[:if]) << "!halted") if false
set_callback(:process_action, :#{filter}, name, options) # set_callback(:process_action, :before, name, options)
end # end
end # end
def #{filter}_filter(*names, &blk) # def before_filter(*names, &blk)
_insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options}
options[:if]=(Array.wrap(options[:if]) << "!halted") if #{filter == :after}
set_callback(:process_action, :#{filter}, name, options) # set_callback(:process_action, :before_filter, name, options)
end # end
end # end
# Prepend a before, after or around filter. See _insert_callbacks
# for details on the allowed parameters.
def prepend_#{filter}_filter(*names, &blk) # def prepend_before_filter(*names, &blk)
_insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
options[:if] = (Array.wrap(options[:if]) << "!halted") if #{filter == :after} # options[:if] = (Array.wrap(options[:if]) << "!halted") if false
options[:if]=(Array.wrap(options[:if]) << "!halted") if #{filter == :after}
set_callback(:process_action, :#{filter}, name, options.merge(:prepend => true)) # set_callback(:process_action, :before, name, options.merge(:prepend => true))
end # end
end # end
# Skip a before, after or around filter. See _insert_callbacks
# for details on the allowed parameters.
def skip_#{filter}_filter(*names, &blk) # def skip_before_filter(*names, &blk)
_insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
skip_callback(:process_action, :#{filter}, name, options) # skip_callback(:process_action, :before, name, options)
end # end
end # end
def skip_#{filter}_filter(*names, &blk) # def skip_before_filter(*names, &blk)
_insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
skip_callback(:process_action, :#{filter}, name, options) # skip_callback(:process_action, :before, name, options)
end # end
end # end
# *_filter is the same as append_*_filter
alias_method :append_#{filter}_filter, :#{filter}_filter # alias_method :append_before_filter, :before_filter
alias_method :append_#{filter}_filter, :#{filter}_filter
RUBY_EVAL
end
end

View File

@@ -4,6 +4,8 @@ module AbstractController
module Helpers
extend ActiveSupport::Concern
include Rendering
included do
class_attribute :_helpers
self._helpers = Module.new
@@ -67,7 +69,7 @@ module AbstractController
# helper FooHelper # => includes FooHelper
#
# 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
# 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
@@ -110,6 +112,17 @@ module AbstractController
default_helper_module! unless anonymous?
end
private
# Makes all the (instance) methods in the helper module available to templates
# rendered through this controller.
#
# ==== Parameters
# * <tt>module</tt> - The module to include into the current helper module
# for the class
def add_template_helper(mod)
_helpers.module_eval { include mod }
end
# Returns a list of modules, normalized from the acceptable kinds of
# helpers with the following behavior:
#
@@ -142,17 +155,6 @@ module AbstractController
end
end
private
# Makes all the (instance) methods in the helper module available to templates
# rendered through this controller.
#
# ==== Parameters
# * <tt>module</tt> - The module to include into the current helper module
# for the class
def add_template_helper(mod)
_helpers.module_eval { include mod }
end
def default_helper_module!
module_name = name.sub(/Controller$/, '')
module_path = module_name.underscore

View File

@@ -66,40 +66,26 @@ module AbstractController
# == Inheritance Examples
#
# class BankController < ActionController::Base
# # bank.html.erb exists
#
# class ExchangeController < BankController
# # exchange.html.erb exists
#
# class CurrencyController < BankController
# layout "bank_standard"
#
# class InformationController < BankController
# layout "information"
#
# class TellerController < InformationController
# class TellerController < BankController
# # teller.html.erb exists
#
# class EmployeeController < InformationController
# # employee.html.erb exists
# layout nil
# class TillController < TellerController
#
# class VaultController < BankController
# layout :access_level_layout
#
# class TillController < BankController
# layout false
# class EmployeeController < BankController
# layout nil
#
# In these examples, we have three implicit lookup scenrios:
# * The BankController uses the "bank" layout.
# * The ExchangeController uses the "exchange" layout.
# * The CurrencyController inherits the layout from BankController.
# The InformationController uses "bank_standard" inherited from the BankController, the VaultController overwrites
# and picks the layout dynamically, and the EmployeeController doesn't want to use a layout at all.
#
# However, when a layout is explicitly set, the explicitly set layout wins:
# * The InformationController uses the "information" layout, explicitly set.
# * The TellerController also uses the "information" layout, because the parent explicitly set it.
# * The EmployeeController uses the "employee" layout, because it set the layout to nil, resetting the parent configuration.
# * The VaultController chooses a layout dynamically by calling the <tt>access_level_layout</tt> method.
# * The TillController does not use a layout at all.
# The TellerController uses +teller.html.erb+, and TillController inherits that layout and
# uses it as well.
#
# == Types of layouts
#
@@ -139,22 +125,6 @@ module AbstractController
# If no directory is specified for the template name, the template will by default be looked for in <tt>app/views/layouts/</tt>.
# Otherwise, it will be looked up relative to the template root.
#
# Setting the layout to nil forces it to be looked up in the filesystem and fallbacks to the parent behavior if none exists.
# Setting it to nil is useful to re-enable template lookup overriding a previous configuration set in the parent:
#
# class ApplicationController < ActionController::Base
# layout "application"
# end
#
# class PostsController < ApplicationController
# # Will use "application" layout
# end
#
# class CommentsController < ApplicationController
# # Will search for "comments" layout and fallback "application" layout
# layout nil
# end
#
# == Conditional layouts
#
# If you have a layout that by default is applied to all the actions of a controller, you still have the option of rendering
@@ -168,8 +138,8 @@ module AbstractController
#
# end
#
# This will assign "weblog_standard" as the WeblogController's layout for all actions except for the +rss+ action, which will
# be rendered directly, without wrapping a layout around the rendered view.
# This will assign "weblog_standard" as the WeblogController's layout except for the +rss+ action, which will not wrap a layout
# around the rendered view.
#
# Both the <tt>:only</tt> and <tt>:except</tt> condition can accept an arbitrary number of method references, so
# #<tt>:except => [ :rss, :text_only ]</tt> is valid, as is <tt>:except => :rss</tt>.
@@ -188,7 +158,7 @@ module AbstractController
# end
# end
#
# This will override the controller-wide "weblog_standard" layout, and will render the help action with the "help" layout instead.
# This will render the help action with the "help" layout instead of the controller-wide "weblog_standard" layout.
module Layouts
extend ActiveSupport::Concern
@@ -196,13 +166,11 @@ module AbstractController
included do
class_attribute :_layout_conditions
remove_possible_method :_layout_conditions
delegate :_layout_conditions, :to => :'self.class'
self._layout_conditions = {}
_write_layout_method
end
delegate :_layout_conditions, :to => "self.class"
module ClassMethods
def inherited(klass)
super
@@ -218,7 +186,7 @@ module AbstractController
#
# ==== Returns
# * <tt> Boolean</tt> - True if the action has a layout, false otherwise.
def conditional_layout?
def action_has_layout?
return unless super
conditions = _layout_conditions
@@ -237,13 +205,13 @@ module AbstractController
#
# If the specified layout is a:
# String:: the String is the template name
# Symbol:: call the method specified by the symbol, which will return the template name
# Symbol:: call the method specified by the symbol, which will return
# the template name
# false:: There is no layout
# true:: raise an ArgumentError
# nil:: Force default layout behavior with inheritance
#
# ==== Parameters
# * <tt>layout</tt> - The layout to use.
# * <tt>String, Symbol, false</tt> - The layout to use.
#
# ==== Options (conditions)
# * :only - A list of actions to apply this layout to.
@@ -254,7 +222,7 @@ module AbstractController
conditions.each {|k, v| conditions[k] = Array(v).map {|a| a.to_s} }
self._layout_conditions = conditions
@_layout = layout
@_layout = layout || false # Converts nil to false
_write_layout_method
end
@@ -267,78 +235,53 @@ module AbstractController
controller_path
end
# Creates a _layout method to be called by _default_layout .
# Takes the specified layout and creates a _layout method to be called
# by _default_layout
#
# If a layout is not explicitly mentioned then look for a layout with the controller's name.
# if nothing is found then try same procedure to find super class's layout.
# If there is no explicit layout specified:
# If a layout is found in the view paths with the controller's
# name, return that string. Otherwise, use the superclass'
# layout (which might also be implied)
def _write_layout_method
remove_possible_method(:_layout)
prefixes = _implied_layout_name =~ /\blayouts/ ? [] : ["layouts"]
name_clause = if name
<<-RUBY
lookup_context.find_all("#{_implied_layout_name}", #{prefixes.inspect}).first || super
RUBY
end
if defined?(@_layout)
layout_definition = case @_layout
when String
@_layout.inspect
when Symbol
<<-RUBY
#{@_layout}.tap do |layout|
unless layout.is_a?(String) || !layout
raise ArgumentError, "Your layout method :#{@_layout} returned \#{layout}. It " \
"should have returned a String, false, or nil"
end
case defined?(@_layout) ? @_layout : nil
when String
self.class_eval %{def _layout; #{@_layout.inspect} end}, __FILE__, __LINE__
when Symbol
self.class_eval <<-ruby_eval, __FILE__, __LINE__ + 1
def _layout
#{@_layout}.tap do |layout|
unless layout.is_a?(String) || !layout
raise ArgumentError, "Your layout method :#{@_layout} returned \#{layout}. It " \
"should have returned a String, false, or nil"
end
RUBY
when Proc
define_method :_layout_from_proc, &@_layout
"_layout_from_proc(self)"
when false
nil
when true
raise ArgumentError, "Layouts must be specified as a String, Symbol, false, or nil"
when nil
name_clause
end
end
else
# Add a deprecation if the parent layout was explicitly set and the child
# still does a dynamic lookup. In next Rails release, we should @_layout
# to be inheritable so we can skip the child lookup if the parent explicitly
# set the layout.
parent = self.superclass.instance_eval { @_layout if defined?(@_layout) }
@_layout = nil
inspect = parent.is_a?(Proc) ? parent.inspect : parent
ruby_eval
when Proc
define_method :_layout_from_proc, &@_layout
self.class_eval %{def _layout; _layout_from_proc(self) end}, __FILE__, __LINE__
when false
self.class_eval %{def _layout; end}, __FILE__, __LINE__
when true
raise ArgumentError, "Layouts must be specified as a String, Symbol, false, or nil"
when nil
if name
_prefix = "layouts" unless _implied_layout_name =~ /\blayouts/
layout_definition = if parent.nil?
name_clause
elsif name
<<-RUBY
if template = lookup_context.find_all("#{_implied_layout_name}", #{prefixes.inspect}).first
ActiveSupport::Deprecation.warn 'Layout found at "#{_implied_layout_name}" for #{name} but parent controller ' \
'set layout to #{inspect.inspect}. Please explicitly set your layout to "#{_implied_layout_name}" ' \
'or set it to nil to force a dynamic lookup.'
template
self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
def _layout
if template_exists?("#{_implied_layout_name}", #{_prefix.inspect})
"#{_implied_layout_name}"
else
super
end
RUBY
end
end
self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
def _layout
if conditional_layout?
#{layout_definition}
else
#{name_clause}
end
end
RUBY
end
private :_layout
RUBY
end
self.class_eval { private :_layout }
end
end
@@ -347,23 +290,20 @@ module AbstractController
if _include_layout?(options)
layout = options.key?(:layout) ? options.delete(:layout) : :default
options[:layout] = _layout_for_option(layout)
value = _layout_for_option(layout)
options[:layout] = (value =~ /\blayouts/ ? value : "layouts/#{value}") if value
end
end
attr_internal_writer :action_has_layout
attr_writer :action_has_layout
def initialize(*)
@_action_has_layout = true
@action_has_layout = true
super
end
def action_has_layout?
@_action_has_layout
end
def conditional_layout?
true
@action_has_layout
end
private
@@ -371,16 +311,19 @@ module AbstractController
# This will be overwritten by _write_layout_method
def _layout; end
# Determine the layout for a given name, taking into account the name type.
# Determine the layout for a given name and details, taking into account
# the name type.
#
# ==== Parameters
# * <tt>name</tt> - The name of the template
# * <tt>details</tt> - A list of details to restrict
# the lookup to. By default, layout lookup is limited to the
# formats specified for the current request.
def _layout_for_option(name)
case name
when String then _normalize_layout(name)
when Proc then name
when true then Proc.new { _default_layout(true) }
when :default then Proc.new { _default_layout(false) }
when String then name
when true then _default_layout(true)
when :default then _default_layout(false)
when false, nil then nil
else
raise ArgumentError,
@@ -388,32 +331,32 @@ module AbstractController
end
end
def _normalize_layout(value)
value.is_a?(String) && value !~ /\blayouts/ ? "layouts/#{value}" : value
end
# Returns the default layout for this controller.
# Returns the default layout for this controller and a given set of details.
# Optionally raises an exception if the layout could not be found.
#
# ==== Parameters
# * <tt>require_layout</tt> - If set to true and layout is not found,
# an ArgumentError exception is raised (defaults to false)
# * <tt>details</tt> - A list of details to restrict the search by. This
# might include details like the format or locale of the template.
# * <tt>require_logout</tt> - If this is true, raise an ArgumentError
# with details about the fact that the exception could not be
# found (defaults to false)
#
# ==== Returns
# * <tt>template</tt> - The template object for the default layout (or nil)
def _default_layout(require_layout = false)
begin
value = _layout if action_has_layout?
layout_name = _layout if action_has_layout?
rescue NameError => e
raise e, "Could not render layout: #{e.message}"
raise NoMethodError,
"You specified #{@_layout.inspect} as the layout, but no such method was found"
end
if require_layout && action_has_layout? && !value
if require_layout && action_has_layout? && !layout_name
raise ArgumentError,
"There was no default layout for #{self.class} in #{view_paths.inspect}"
end
_normalize_layout(value)
layout_name
end
def _include_layout?(options)

View File

@@ -7,7 +7,7 @@ module AbstractController
included do
config_accessor :logger
include ActiveSupport::Benchmarkable
extend ActiveSupport::Benchmarkable
end
end
end

View File

@@ -1,18 +0,0 @@
module AbstractController
module Railties
module RoutesHelpers
def self.with(routes)
Module.new do
define_method(:inherited) do |klass|
super(klass)
if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_routes_url_helpers) }
klass.send(:include, namespace.railtie_routes_url_helpers)
else
klass.send(:include, routes.url_helpers)
end
end
end
end
end
end
end

View File

@@ -1,6 +1,5 @@
require "abstract_controller/base"
require "action_view"
require "active_support/core_ext/object/instance_variables"
module AbstractController
class DoubleRenderError < Error
@@ -13,16 +12,16 @@ module AbstractController
# This is a class to fix I18n global state. Whenever you provide I18n.locale during a request,
# it will trigger the lookup_context and consequently expire the cache.
# TODO Add some deprecation warnings to remove I18n.locale from controllers
class I18nProxy < ::I18n::Config #:nodoc:
attr_reader :original_config, :lookup_context
attr_reader :i18n_config, :lookup_context
def initialize(original_config, lookup_context)
original_config = original_config.original_config if original_config.respond_to?(:original_config)
@original_config, @lookup_context = original_config, lookup_context
def initialize(i18n_config, lookup_context)
@i18n_config, @lookup_context = i18n_config, lookup_context
end
def locale
@original_config.locale
@i18n_config.locale
end
def locale=(value)
@@ -32,12 +31,8 @@ module AbstractController
module Rendering
extend ActiveSupport::Concern
include AbstractController::ViewPaths
included do
class_attribute :protected_instance_variables
self.protected_instance_variables = []
end
include AbstractController::ViewPaths
# Overwrite process to setup I18n proxy.
def process(*) #:nodoc:
@@ -50,17 +45,32 @@ module AbstractController
module ClassMethods
def view_context_class
@view_context_class ||= begin
routes = _routes if respond_to?(:_routes)
helpers = _helpers if respond_to?(:_helpers)
ActionView::Base.prepare(routes, helpers)
controller = self
Class.new(ActionView::Base) do
if controller.respond_to?(:_routes)
include controller._routes.url_helpers
end
if controller.respond_to?(:_helpers)
include controller._helpers
# TODO: Fix RJS to not require this
self.helpers = controller._helpers
end
end
end
end
end
attr_internal_writer :view_context_class
attr_writer :view_context_class
def view_context_class
@_view_context_class ||= self.class.view_context_class
@view_context_class || self.class.view_context_class
end
def initialize(*)
@view_context_class = nil
super
end
# An instance of a view class. The default view class is ActionView::Base
@@ -73,26 +83,21 @@ module AbstractController
#
# Override this method in a module to change the default behavior.
def view_context
view_context_class.new(view_renderer, view_assigns, self)
end
# Returns an object that is able to render templates.
def view_renderer
@_view_renderer ||= ActionView::Renderer.new(lookup_context)
view_context_class.new(lookup_context, view_assigns, self)
end
# Normalize arguments, options and then delegates render_to_body and
# sticks the result in self.response_body.
def render(*args, &block)
options = _normalize_render(*args, &block)
self.response_body = render_to_body(options)
self.response_body = render_to_string(*args, &block)
end
# Raw rendering of a template to a string. Just convert the results of
# render_response into a String.
# render_to_body into a String.
# :api: plugin
def render_to_string(*args, &block)
options = _normalize_render(*args, &block)
options = _normalize_args(*args, &block)
_normalize_options(options)
render_to_body(options)
end
@@ -106,14 +111,15 @@ module AbstractController
# Find and renders a template based on the options given.
# :api: private
def _render_template(options) #:nodoc:
lookup_context.rendered_format = nil if options[:formats]
view_renderer.render(view_context, options)
view_context.render(options)
end
DEFAULT_PROTECTED_INSTANCE_VARIABLES = %w(
@_action_name @_response_body @_formats @_prefixes @_config
@_view_context_class @_view_renderer @_lookup_context
)
# The prefix used in render "foo" shortcuts.
def _prefix
controller_path
end
private
# This method should return a hash with assigns.
# You can overwrite this configuration per controller.
@@ -121,58 +127,42 @@ module AbstractController
def view_assigns
hash = {}
variables = instance_variable_names
variables -= protected_instance_variables
variables -= DEFAULT_PROTECTED_INSTANCE_VARIABLES
variables.each { |name| hash[name.to_s[1, name.length]] = instance_variable_get(name) }
variables -= protected_instance_variables if respond_to?(:protected_instance_variables)
variables.each { |name| hash[name.to_s[1..-1]] = instance_variable_get(name) }
hash
end
private
# Normalize args and options.
# :api: private
def _normalize_render(*args, &block)
options = _normalize_args(*args, &block)
_normalize_options(options)
options
end
# Normalize args by converting render "foo" to render :action => "foo" and
# Normalize options by converting render "foo" to render :action => "foo" and
# render "foo/bar" to render :file => "foo/bar".
# :api: plugin
def _normalize_args(action=nil, options={})
case action
when NilClass
when Hash
options = action
options, action = action, nil
when String, Symbol
action = action.to_s
key = action.include?(?/) ? :file : :action
options[key] = action
else
options[:partial] = action
options.merge!(:partial => action)
end
options
end
# Normalize options.
# :api: plugin
def _normalize_options(options)
if options[:partial] == true
options[:partial] = action_name
end
if (options.keys & [:partial, :file, :template]).empty?
options[:prefixes] ||= _prefixes
options[:prefix] ||= _prefix
end
options[:template] ||= (options[:action] || action_name).to_s
options
end
# Process extra options.
# :api: plugin
def _process_options(options)
end
end

View File

@@ -1,33 +0,0 @@
# Includes +url_for+ into the host class (e.g. an abstract controller or mailer). The class
# has to provide a +RouteSet+ by implementing the <tt>_routes</tt> methods. Otherwise, an
# exception will be raised.
#
# Note that this module is completely decoupled from HTTP - the only requirement is a valid
# <tt>_routes</tt> implementation.
module AbstractController
module UrlFor
extend ActiveSupport::Concern
include ActionDispatch::Routing::UrlFor
def _routes
raise "In order to use #url_for, you must include routing helpers explicitly. " \
"For instance, `include Rails.application.routes.url_helpers"
end
module ClassMethods
def _routes
nil
end
def action_methods
@action_methods ||= begin
if _routes
super - _routes.named_routes.helper_names
else
super
end
end
end
end
end
end

View File

@@ -1,5 +1,3 @@
require 'action_view/base'
module AbstractController
module ViewPaths
extend ActiveSupport::Concern
@@ -10,39 +8,14 @@ module AbstractController
self._view_paths.freeze
end
delegate :template_exists?, :view_paths, :formats, :formats=,
delegate :find_template, :template_exists?, :view_paths, :formats, :formats=,
:locale, :locale=, :to => :lookup_context
module ClassMethods
def parent_prefixes
@parent_prefixes ||= begin
parent_controller = superclass
prefixes = []
until parent_controller.abstract?
prefixes << parent_controller.controller_path
parent_controller = parent_controller.superclass
end
prefixes
end
end
end
# The prefixes used in render "foo" shortcuts.
def _prefixes
@_prefixes ||= begin
parent_prefixes = self.class.parent_prefixes
parent_prefixes.dup.unshift(controller_path)
end
end
# LookupContext is the object responsible to hold all information required to lookup
# templates, i.e. view paths and details. Check ActionView::LookupContext for more
# information.
def lookup_context
@_lookup_context ||=
ActionView::LookupContext.new(self.class._view_paths, details_for_lookup, _prefixes)
@lookup_context ||= ActionView::LookupContext.new(self.class._view_paths, details_for_lookup)
end
def details_for_lookup
@@ -63,9 +36,9 @@ module AbstractController
# ==== Parameters
# * <tt>path</tt> - If a String is provided, it gets converted into
# the default view path. You may also provide a custom view path
# (see ActionView::PathSet for more information)
# (see ActionView::ViewPathSet for more information)
def append_view_path(path)
self._view_paths = view_paths + Array(path)
self.view_paths = view_paths.dup + Array(path)
end
# Prepend a path to the list of view paths for this controller.
@@ -73,9 +46,9 @@ module AbstractController
# ==== Parameters
# * <tt>path</tt> - If a String is provided, it gets converted into
# the default view path. You may also provide a custom view path
# (see ActionView::PathSet for more information)
# (see ActionView::ViewPathSet for more information)
def prepend_view_path(path)
self._view_paths = ActionView::PathSet.new(Array(path) + view_paths)
self.view_paths = Array(path) + view_paths.dup
end
# A list of all of the default view paths for this controller.
@@ -86,11 +59,12 @@ module AbstractController
# Set the view paths.
#
# ==== Parameters
# * <tt>paths</tt> - If a PathSet is provided, use that;
# otherwise, process the parameter into a PathSet.
# * <tt>paths</tt> - If a ViewPathSet is provided, use that;
# otherwise, process the parameter into a ViewPathSet.
def view_paths=(paths)
self._view_paths = ActionView::PathSet.new(Array.wrap(paths))
self._view_paths = ActionView::Base.process_view_paths(paths)
self._view_paths.freeze
end
end
end
end
end

View File

@@ -13,9 +13,7 @@ module ActionController
autoload :Compatibility
autoload :ConditionalGet
autoload :Cookies
autoload :DataStreaming
autoload :Flash
autoload :ForceSSL
autoload :Head
autoload :Helpers
autoload :HideActions
@@ -23,7 +21,6 @@ module ActionController
autoload :ImplicitRender
autoload :Instrumentation
autoload :MimeResponds
autoload :ParamsWrapper
autoload :RackDelegation
autoload :Redirecting
autoload :Renderers
@@ -37,16 +34,32 @@ module ActionController
autoload :UrlFor
end
autoload :Integration, 'action_controller/deprecated/integration_test'
autoload :IntegrationTest, 'action_controller/deprecated/integration_test'
autoload :PerformanceTest, 'action_controller/deprecated/performance_test'
autoload :UrlWriter, 'action_controller/deprecated'
autoload :Routing, 'action_controller/deprecated'
autoload :TestCase, 'action_controller/test_case'
autoload :TemplateAssertions, 'action_controller/test_case'
autoload :Dispatcher, 'action_controller/deprecated/dispatcher'
autoload :UrlWriter, 'action_controller/deprecated/url_writer'
autoload :UrlRewriter, 'action_controller/deprecated/url_writer'
autoload :Integration, 'action_controller/deprecated/integration_test'
autoload :IntegrationTest, 'action_controller/deprecated/integration_test'
autoload :PerformanceTest, 'action_controller/deprecated/performance_test'
autoload :Routing, 'action_controller/deprecated'
autoload :TestCase, 'action_controller/test_case'
eager_autoload do
autoload :RecordIdentifier
# TODO: Don't autoload exceptions, setup explicit
# requires for files that need them
autoload_at "action_controller/metal/exceptions" do
autoload :ActionControllerError
autoload :RenderError
autoload :RoutingError
autoload :MethodNotAllowed
autoload :NotImplemented
autoload :UnknownController
autoload :MissingFile
autoload :RenderError
autoload :SessionOverflowError
autoload :UnknownHttpMethod
end
end
end
@@ -61,5 +74,4 @@ require 'active_support/core_ext/load_error'
require 'active_support/core_ext/module/attr_internal'
require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/name_error'
require 'active_support/core_ext/uri'
require 'active_support/inflector'

View File

@@ -24,14 +24,14 @@ module ActionController
#
# 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 PostsController would render the
# template <tt>app/views/posts/index.html.erb</tt> by default after populating the <tt>@posts</tt> instance variable.
# template <tt>app/views/posts/index.erb</tt> by default after populating the <tt>@posts</tt> instance variable.
#
# Unlike index, the create action will not render a template. After performing its main purpose (creating a
# new post), it initiates a redirect instead. This redirect works by returning an external
# "302 Moved" HTTP response that takes the user to the index action.
#
# These two methods represent the two basic action archetypes used in Action Controllers. Get-and-show and do-and-redirect.
# Most actions are variations on these themes.
# Most actions are variations of these themes.
#
# == Requests
#
@@ -50,7 +50,7 @@ module ActionController
#
# All request parameters, whether they come from a GET or POST request, or from the URL, are available through the params method
# which returns a hash. For example, an action that was performed through <tt>/posts?category=All&limit=5</tt> will include
# <tt>{ "category" => "All", "limit" => "5" }</tt> in params.
# <tt>{ "category" => "All", "limit" => 5 }</tt> in params.
#
# It's also possible to construct multi-dimensional parameter hashes by specifying keys using brackets, such as:
#
@@ -63,7 +63,7 @@ module ActionController
#
# == Sessions
#
# Sessions allow you to store objects in between requests. This is useful for objects that are not yet ready to be persisted,
# Sessions allows you to store objects in between requests. This is useful for objects that are not yet ready to be persisted,
# such as a Signup object constructed in a multi-paged process, or objects that don't change much and are needed all the time, such
# as a User object for a system that requires login. The session should not be used, however, as a cache for objects where it's likely
# they could be changed unknowingly. It's usually too much work to keep it all synchronized -- something databases already excel at.
@@ -93,9 +93,9 @@ module ActionController
# * ActiveRecord::SessionStore - Sessions are stored in your database, which works better than PStore with multiple app servers and,
# unlike CookieStore, hides your session contents from the user. To use ActiveRecord::SessionStore, set
#
# MyApplication::Application.config.session_store :active_record_store
# config.action_controller.session_store = :active_record_store
#
# in your <tt>config/initializers/session_store.rb</tt> and run <tt>script/rails g session_migration</tt>.
# in your <tt>config/environment.rb</tt> and run <tt>rake db:sessions:create</tt>.
#
# == Responses
#
@@ -105,7 +105,7 @@ module ActionController
# == Renders
#
# Action Controller sends content to the user by using one of five rendering methods. The most versatile and common is the rendering
# of a template. Included in the Action Pack is the Action View, which enables rendering of ERB templates. It's automatically configured.
# of a template. Included in the Action Pack is the Action View, which enables rendering of ERb templates. It's automatically configured.
# The controller passes objects to the view by assigning instance variables:
#
# def show
@@ -116,25 +116,25 @@ module ActionController
#
# Title: <%= @post.title %>
#
# You don't have to rely on the automated rendering. For example, actions that could result in the rendering of different templates
# will use the manual rendering methods:
# You don't have to rely on the automated rendering. Especially actions that could result in the rendering of different templates will use
# the manual rendering methods:
#
# def search
# @results = Search.find(params[:query])
# case @results.count
# case @results
# when 0 then render :action => "no_results"
# when 1 then render :action => "show"
# when 2..10 then render :action => "show_many"
# end
# end
#
# Read more about writing ERB and Builder templates in ActionView::Base.
# Read more about writing ERb and Builder templates in ActionView::Base.
#
# == Redirects
#
# Redirects are used to move from one action to another. For example, after a <tt>create</tt> action, which stores a blog entry to the
# database, we might like to show the user the new entry. Because we're following good DRY principles (Don't Repeat Yourself), we're
# going to reuse (and redirect to) a <tt>show</tt> action that we'll assume has already been created. The code might look like this:
# Redirects are used to move from one action to another. For example, after a <tt>create</tt> action, which stores a blog entry to a database,
# we might like to show the user the new entry. Because we're following good DRY principles (Don't Repeat Yourself), we're going to reuse (and redirect to)
# a <tt>show</tt> action that we'll assume has already been created. The code might look like this:
#
# def create
# @entry = Entry.new(params[:entry])
@@ -146,9 +146,7 @@ module ActionController
# end
# end
#
# In this case, after saving our new entry to the database, the user is redirected to the <tt>show</tt> method, which is then executed.
# Note that this is an external HTTP-level redirection which will cause the browser to make a second request (a GET to the show action),
# and not some internal re-routing which calls both "create" and then "show" within one request.
# In this case, after saving our new entry to the database, the user is redirected to the <tt>show</tt> method which is then executed.
#
# Learn more about <tt>redirect_to</tt> and what options you have in ActionController::Redirecting.
#
@@ -192,6 +190,7 @@ module ActionController
Renderers::All,
ConditionalGet,
RackDelegation,
SessionManagement,
Caching,
MimeResponds,
ImplicitRender,
@@ -199,28 +198,22 @@ module ActionController
Cookies,
Flash,
RequestForgeryProtection,
ForceSSL,
Streaming,
DataStreaming,
RecordIdentifier,
HttpAuthentication::Basic::ControllerMethods,
HttpAuthentication::Digest::ControllerMethods,
HttpAuthentication::Token::ControllerMethods,
# Before callbacks should also be executed the earliest as possible, so
# also include them at the bottom.
AbstractController::Callbacks,
# Append rescue at the bottom to wrap as much as possible.
Rescue,
# Add instrumentations hooks at the bottom, to ensure they instrument
# all the methods properly.
Instrumentation,
# Params wrapper should come before instrumentation so they are
# properly showed in logs
ParamsWrapper
# Before callbacks should also be executed the earliest as possible, so
# also include them at the bottom.
AbstractController::Callbacks,
# The same with rescue, append it at the end to wrap as much as possible.
Rescue
]
MODULES.each do |mod|
@@ -230,6 +223,13 @@ module ActionController
# Rails 2.x compatibility
include ActionController::Compatibility
def self.inherited(klass)
super
klass.helper :all if klass.superclass == ActionController::Base
end
require "action_controller/deprecated/base"
ActiveSupport.run_load_hooks(:action_controller, self)
end
end

View File

@@ -3,7 +3,7 @@ require 'uri'
require 'set'
module ActionController #:nodoc:
# \Caching is a cheap way of speeding up slow applications by keeping the result of
# Caching is a cheap way of speeding up slow applications by keeping the result of
# calculations, renderings, and database calls around for subsequent requests.
# Action Controller affords you three approaches in varying levels of granularity:
# Page, Action, Fragment.
@@ -14,7 +14,7 @@ module ActionController #:nodoc:
# Note: To turn off all caching and sweeping, set
# config.action_controller.perform_caching = false.
#
# == \Caching stores
# == Caching stores
#
# All the caching stores from ActiveSupport::Cache are available to be used as backends
# for Action Controller caching. This setting only affects action and fragment caching
@@ -24,6 +24,7 @@ module ActionController #:nodoc:
#
# config.action_controller.cache_store = :memory_store
# config.action_controller.cache_store = :file_store, "/path/to/cache/directory"
# config.action_controller.cache_store = :drb_store, "druby://localhost:9192"
# config.action_controller.cache_store = :mem_cache_store, "localhost"
# config.action_controller.cache_store = :mem_cache_store, Memcached::Rails.new("localhost:11211")
# config.action_controller.cache_store = MyOwnStore.new("parameter")
@@ -55,9 +56,6 @@ module ActionController #:nodoc:
end
end
include RackDelegation
include AbstractController::Callbacks
include ConfigMethods
include Pages, Actions, Fragments
include Sweeping if defined?(ActiveRecord)

View File

@@ -4,86 +4,73 @@ module ActionController #:nodoc:
module Caching
# Action caching is similar to page caching by the fact that the entire
# output of the response is cached, but unlike page caching, every
# request still goes through Action Pack. The key benefit of this is
# that filters run before the cache is served, which allows for
# authentication and other restrictions on whether someone is allowed
# to execute such action. Example:
# request still goes through the Action Pack. The key benefit
# of this is that filters are run before the cache is served, which
# allows for authentication and other restrictions on whether someone
# is allowed to see the cache. Example:
#
# class ListsController < ApplicationController
# before_filter :authenticate, :except => :public
#
# caches_page :public
# caches_action :index, :show
# caches_action :index, :show, :feed
# end
#
# In this example, the +public+ action doesn't require authentication
# so it's possible to use the faster page caching. On the other hand
# +index+ and +show+ require authentication. They can still be cached,
# but we need action caching for them.
# In this example, the public action doesn't require authentication,
# so it's possible to use the faster page caching method. But both
# the show and feed action are to be shielded behind the authenticate
# filter, so we need to implement those as action caches.
#
# Action caching uses fragment caching internally and an around
# filter to do the job. The fragment cache is named according to
# the host and path of the request. A page that is accessed at
# <tt>http://david.example.com/lists/show/1</tt> will result in a fragment named
# <tt>david.example.com/lists/show/1</tt>. This allows the cacher to
# differentiate between <tt>david.example.com/lists/</tt> and
# <tt>jamis.example.com/lists/</tt> -- which is a helpful way of assisting
# Action caching internally uses the fragment caching and an around
# filter to do the job. The fragment cache is named according to both
# the current host and the path. So a page that is accessed at
# http://david.somewhere.com/lists/show/1 will result in a fragment named
# "david.somewhere.com/lists/show/1". This allows the cacher to
# differentiate between "david.somewhere.com/lists/" and
# "jamis.somewhere.com/lists/" -- which is a helpful way of assisting
# the subdomain-as-account-key pattern.
#
# Different representations of the same resource, e.g.
# <tt>http://david.example.com/lists</tt> and
# <tt>http://david.example.com/lists.xml</tt>
# <tt>http://david.somewhere.com/lists</tt> and
# <tt>http://david.somewhere.com/lists.xml</tt>
# are treated like separate requests and so are cached separately.
# Keep in mind when expiring an action cache that
# <tt>:action => 'lists'</tt> is not the same as
# <tt>:action => 'list', :format => :xml</tt>.
#
# You can modify the default action cache path by passing a
# <tt>:cache_path</tt> option. This will be passed directly to
# <tt>ActionCachePath.path_for</tt>. This is handy for actions with
# multiple possible routes that should be cached differently. If a
# block is given, it is called with the current controller instance.
# You can set modify the default action cache path by passing a
# :cache_path option. This will be passed directly to
# ActionCachePath.path_for. This is handy for actions with multiple
# possible routes that should be cached differently. If a block is
# given, it is called with the current controller instance.
#
# And you can also use <tt>:if</tt> (or <tt>:unless</tt>) to pass a
# proc that specifies when the action should be cached.
# And you can also use :if (or :unless) to pass a Proc that
# specifies when the action should be cached.
#
# Finally, if you are using memcached, you can also pass <tt>:expires_in</tt>.
#
# The following example depicts some of the points made above:
# Finally, if you are using memcached, you can also pass :expires_in.
#
# class ListsController < ApplicationController
# before_filter :authenticate, :except => :public
#
# caches_page :public
#
# caches_action :index, :if => proc do
# !request.format.json? # cache if is not a JSON request
# caches_page :public
# caches_action :index, :if => proc do |c|
# !c.request.format.json? # cache if is not a JSON request
# end
#
# caches_action :show, :cache_path => { :project => 1 },
# :expires_in => 1.hour
#
# caches_action :feed, :cache_path => proc do
# if params[:user_id]
# user_list_url(params[:user_id, params[:id])
# caches_action :feed, :cache_path => proc do |controller|
# if controller.params[:user_id]
# controller.send(:user_list_url,
# controller.params[:user_id], controller.params[:id])
# else
# list_url(params[:id])
# controller.send(:list_url, controller.params[:id])
# end
# end
# end
#
# If you pass <tt>:layout => false</tt>, it will only cache your action
# content. That's useful when your layout has dynamic information.
# If you pass :layout => false, it will only cache your action
# content. It is useful when your layout has dynamic information.
#
# Warning: If the format of the request is determined by the Accept HTTP
# header the Content-Type of the cached response could be wrong because
# no information about the MIME type is stored in the cache key. So, if
# you first ask for MIME type M in the Accept header, a cache entry is
# created, and then perform a second request to the same resource asking
# for a different MIME type, you'd get the content cached for M.
#
# The <tt>:format</tt> parameter is taken into account though. The safest
# way to cache by MIME type is to pass the format in the route.
module Actions
extend ActiveSupport::Concern
@@ -102,24 +89,21 @@ module ActionController #:nodoc:
end
def _save_fragment(name, options)
content = ""
response_body.each do |parts|
content << parts
end
return unless caching_allowed?
if caching_allowed?
write_fragment(name, content, options)
else
content
end
content = response_body
content = content.join if content.is_a?(Array)
write_fragment(name, content, options)
end
protected
def expire_action(options = {})
return unless cache_configured?
if options.is_a?(Hash) && options[:action].is_a?(Array)
options[:action].each {|action| expire_action(options.merge(:action => action)) }
actions = options[:action]
if actions.is_a?(Array)
actions.each {|action| expire_action(options.merge(:action => action)) }
else
expire_fragment(ActionCachePath.new(self, options, false).path)
end
@@ -160,7 +144,7 @@ module ActionController #:nodoc:
attr_reader :path, :extension
# If +infer_extension+ is true, the cache path extension is looked up from the request's
# path and format. This is desirable when reading and writing the cache, but not when
# path & format. This is desirable when reading and writing the cache, but not when
# expiring the cache - expire_action should expire the same files regardless of the
# request format.
def initialize(controller, options = {}, infer_extension = true)
@@ -176,8 +160,8 @@ module ActionController #:nodoc:
private
def normalize!(path)
path << 'index' if path[-1] == ?/
path << ".#{extension}" if extension and !path.split('?').first.ends_with?(".#{extension}")
URI.parser.unescape(path)
path << ".#{extension}" if extension and !path.ends_with?(extension)
URI.unescape(path)
end
end
end

View File

@@ -1,72 +1,52 @@
module ActionController #:nodoc:
module Caching
# Fragment caching is used for caching various blocks within
# views 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 done using
# the <tt>cache</tt> helper available in the Action View. A
# template with fragment caching might look like:
# 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 done using the cache helper available in the Action View. A template with caching might look something like:
#
# <b>Hello <%= @name %></b>
#
# <% cache do %>
# All the topics in the system:
# <%= render :partial => "topic", :collection => Topic.all %>
# <%= render :partial => "topic", :collection => Topic.find(:all) %>
# <% end %>
#
# This cache will bind the name of the action that called it, so if
# this code was part of the view for the topics/list action, you
# would be able to invalidate it using:
# This cache will bind to the name of the action that called it, so if this code was part of the view for the topics/list action, you would
# be able to invalidate it using <tt>expire_fragment(:controller => "topics", :action => "list")</tt>.
#
# expire_fragment(:controller => "topics", :action => "list")
#
# This default behavior is limited if you need to cache multiple
# fragments per action or if the action itself is cached using
# <tt>caches_action</tt>. To remedy this, there is an option to
# qualify the name of the cached fragment by using the
# <tt>:action_suffix</tt> option:
# This default behavior is of limited use if you need to cache multiple fragments per action or if the action itself is cached using
# <tt>caches_action</tt>, so we also have the option to qualify the name of the cached fragment with something like:
#
# <% cache(:action => "list", :action_suffix => "all_topics") do %>
#
# That would result in a name such as
# <tt>/topics/list/all_topics</tt>, avoiding conflicts with the
# action cache and with any fragments that use a different suffix.
# Note that the URL doesn't have to really exist or be callable
# - the url_for system is just used to generate unique cache names
# that we can refer to when we need to expire the cache.
# That would result in a name such as "/topics/list/all_topics", avoiding conflicts with the action cache and with any fragments that use a
# different suffix. Note that the URL doesn't have to really exist or be callable - the url_for system is just used to generate unique
# cache names that we can refer to when we need to expire the cache.
#
# The expiration call for this example is:
#
# expire_fragment(:controller => "topics",
# :action => "list",
# :action_suffix => "all_topics")
# expire_fragment(:controller => "topics", :action => "list", :action_suffix => "all_topics")
module Fragments
# Given a key (as described in <tt>expire_fragment</tt>), returns
# a key suitable for use in reading, writing, or expiring a
# cached fragment. If the key is a hash, the generated key is the
# return value of url_for on that hash (without the protocol).
# All keys are prefixed with <tt>views/</tt> and uses
# Given a key (as described in <tt>expire_fragment</tt>), returns a key suitable for use in reading,
# writing, or expiring a cached fragment. If the key is a hash, the generated key is the return
# value of url_for on that hash (without the protocol). All keys are prefixed with "views/" and uses
# ActiveSupport::Cache.expand_cache_key for the expansion.
def fragment_cache_key(key)
ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views)
end
# Writes <tt>content</tt> to the location signified by
# <tt>key</tt> (see <tt>expire_fragment</tt> for acceptable formats).
# Writes <tt>content</tt> to the location signified by <tt>key</tt> (see <tt>expire_fragment</tt> for acceptable formats)
def write_fragment(key, content, options = nil)
return content unless cache_configured?
key = fragment_cache_key(key)
instrument_fragment_cache :write_fragment, key do
content = content.to_str
content = content.html_safe.to_str if content.respond_to?(:html_safe)
cache_store.write(key, content, options)
end
content
end
# Reads a cached fragment from the location signified by <tt>key</tt>
# (see <tt>expire_fragment</tt> for acceptable formats).
# Reads a cached fragment from the location signified by <tt>key</tt> (see <tt>expire_fragment</tt> for acceptable formats)
def read_fragment(key, options = nil)
return unless cache_configured?
@@ -77,8 +57,7 @@ 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)
# 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)
@@ -91,9 +70,8 @@ module ActionController #:nodoc:
# Removes fragments from the cache.
#
# +key+ can take one of three forms:
#
# * String - This would normally take the form of a path, like
# <tt>pages/45/notes</tt>.
# <tt>"pages/45/notes"</tt>.
# * Hash - Treated as an implicit call to +url_for+, like
# <tt>{:controller => "pages", :action => "notes", :id => 45}</tt>
# * Regexp - Will remove any fragment that matches, so
@@ -109,6 +87,7 @@ module ActionController #:nodoc:
def expire_fragment(key, options = nil)
return unless cache_configured?
key = fragment_cache_key(key) unless key.is_a?(Regexp)
message = nil
instrument_fragment_cache :expire_fragment, key do
if key.is_a?(Regexp)

View File

@@ -1,4 +1,5 @@
require 'fileutils'
require 'uri'
require 'active_support/core_ext/class/attribute_accessors'
module ActionController #:nodoc:
@@ -16,10 +17,9 @@ module ActionController #:nodoc:
# caches_page :show, :new
# end
#
# This will generate cache files such as <tt>weblog/show/5.html</tt> and <tt>weblog/new.html</tt>, which match the URLs used
# that would normally trigger dynamic page generation. Page caching works by configuring a web server to first check for the
# existence of files on disk, and to serve them directly when found, without passing the request through to Action Pack.
# This is much faster than handling the full dynamic request in the usual way.
# This will generate cache files such as <tt>weblog/show/5.html</tt> and <tt>weblog/new.html</tt>,
# which match the URLs used to trigger the dynamic generation. This is how the web server is able
# pick up a cache file when it exists and otherwise let the request pass on to Action Pack to generate it.
#
# Expiration of the cache is handled by deleting the cached file, which results in a lazy regeneration approach where the cache
# is not restored before another hit is made against it. The API for doing so mimics the options from +url_for+ and friends:
@@ -38,25 +38,23 @@ module ActionController #:nodoc:
extend ActiveSupport::Concern
included do
##
# :singleton-method:
# The cache directory should be the document root for the web server and is set using <tt>Base.page_cache_directory = "/document/root"</tt>.
# For Rails, this directory has already been set to Rails.public_path (which is usually set to <tt>Rails.root + "/public"</tt>). Changing
# this setting can be useful to avoid naming conflicts with files in <tt>public/</tt>, but doing so will likely require configuring your
# web server to look in the new location for cached files.
class_attribute :page_cache_directory
config_accessor :page_cache_directory
self.page_cache_directory ||= ''
##
# :singleton-method:
# Most Rails requests do not have an extension, such as <tt>/weblog/new</tt>. In these cases, the page caching mechanism will add one in
# order to make it easy for the cached files to be picked up properly by the web server. By default, this cache extension is <tt>.html</tt>.
# If you want something else, like <tt>.php</tt> or <tt>.shtml</tt>, just set Base.page_cache_extension. In cases where a request already has an
# extension, such as <tt>.xml</tt> or <tt>.rss</tt>, page caching will not add an extension. This allows it to work well with RESTful apps.
class_attribute :page_cache_extension
config_accessor :page_cache_extension
self.page_cache_extension ||= '.html'
# The compression used for gzip. If false (default), the page is not compressed.
# If can be a symbol showing the ZLib compression method, for example, :best_compression
# or :best_speed or an integer configuring the compression level.
class_attribute :page_cache_compression
self.page_cache_compression ||= false
end
module ClassMethods
@@ -68,31 +66,24 @@ module ActionController #:nodoc:
instrument_page_cache :expire_page, path do
File.delete(path) if File.exist?(path)
File.delete(path + '.gz') if File.exist?(path + '.gz')
end
end
# Manually cache the +content+ in the key determined by +path+. Example:
# cache_page "I'm the cached content", "/lists/show"
def cache_page(content, path, extension = nil, gzip = Zlib::BEST_COMPRESSION)
def cache_page(content, path)
return unless perform_caching
path = page_cache_path(path, extension)
path = page_cache_path(path)
instrument_page_cache :write_page, path do
FileUtils.makedirs(File.dirname(path))
File.open(path, "wb+") { |f| f.write(content) }
if gzip
Zlib::GzipWriter.open(path + '.gz', gzip) { |f| f.write(content) }
end
end
end
# Caches the +actions+ using the page-caching approach that'll store
# the cache in a path within the page_cache_directory that
# Caches the +actions+ using the page-caching approach that'll store the cache in a path within the page_cache_directory that
# matches the triggering url.
#
# You can also pass a :gzip option to override the class configuration one.
#
# Usage:
#
# # cache the index action
@@ -100,41 +91,21 @@ module ActionController #:nodoc:
#
# # cache the index action except for JSON requests
# caches_page :index, :if => Proc.new { |c| !c.request.format.json? }
#
# # don't gzip images
# caches_page :image, :gzip => false
def caches_page(*actions)
return unless perform_caching
options = actions.extract_options!
gzip_level = options.fetch(:gzip, page_cache_compression)
gzip_level = case gzip_level
when Symbol
Zlib.const_get(gzip_level.to_s.upcase)
when Fixnum
gzip_level
when false
nil
else
Zlib::BEST_COMPRESSION
end
after_filter({:only => actions}.merge(options)) do |c|
c.cache_page(nil, nil, gzip_level)
end
after_filter({:only => actions}.merge(options)) { |c| c.cache_page }
end
private
def page_cache_file(path, extension)
name = (path.empty? || path == "/") ? "/index" : URI.parser.unescape(path.chomp('/'))
unless (name.split('/').last || name).include? '.'
name << (extension || self.page_cache_extension)
end
def page_cache_file(path)
name = (path.empty? || path == "/") ? "/index" : URI.unescape(path.chomp('/'))
name << page_cache_extension unless (name.split('/').last || name).include? '.'
return name
end
def page_cache_path(path, extension = nil)
page_cache_directory.to_s + page_cache_file(path, extension)
def page_cache_path(path)
page_cache_directory + page_cache_file(path)
end
def instrument_page_cache(name, path)
@@ -149,7 +120,7 @@ module ActionController #:nodoc:
if options.is_a?(Hash)
if options[:action].is_a?(Array)
options[:action].each do |action|
options[:action].dup.each do |action|
self.class.expire_page(url_for(options.merge(:only_path => true, :action => action)))
end
else
@@ -160,11 +131,11 @@ module ActionController #:nodoc:
end
end
# Manually cache the +content+ in the key determined by +options+. If no content is provided, the contents of response.body is used.
# If no options are provided, the url of the current request being handled is used. Example:
# Manually cache the +content+ in the key determined by +options+. If no content is provided, the contents of response.body is used
# If no options are provided, the requested url is used. Example:
# cache_page "I'm the cached content", :controller => "lists", :action => "show"
def cache_page(content = nil, options = nil, gzip = Zlib::BEST_COMPRESSION)
return unless self.class.perform_caching && caching_allowed?
def cache_page(content = nil, options = nil)
return unless self.class.perform_caching && caching_allowed
path = case options
when Hash
@@ -175,13 +146,13 @@ module ActionController #:nodoc:
request.path
end
if (type = Mime::LOOKUP[self.content_type]) && (type_symbol = type.symbol).present?
extension = ".#{type_symbol}"
end
self.class.cache_page(content || response.body, path, extension, gzip)
self.class.cache_page(content || response.body, path)
end
private
def caching_allowed
request.get? && response.status.to_i == 200
end
end
end
end

View File

@@ -61,7 +61,6 @@ module ActionController #:nodoc:
end
def after(controller)
self.controller = controller
callback(:after) if controller.perform_caching
# Clean up, so that the controller can be collected after this request
self.controller = nil
@@ -88,7 +87,7 @@ module ActionController #:nodoc:
end
def method_missing(method, *arguments, &block)
return unless @controller
return if @controller.nil?
@controller.__send__(method, *arguments, &block)
end
end

View File

@@ -1,3 +1,3 @@
ActionController::AbstractRequest = ActionController::Request = ActionDispatch::Request
ActionController::AbstractResponse = ActionController::Response = ActionDispatch::Response
ActionController::Routing = ActionDispatch::Routing
ActionController::Routing = ActionDispatch::Routing

View File

@@ -0,0 +1,143 @@
module ActionController
class Base
# Deprecated methods. Wrap them in a module so they can be overwritten by plugins
# (like the verify method.)
module DeprecatedBehavior #:nodoc:
def relative_url_root
ActiveSupport::Deprecation.warn "ActionController::Base.relative_url_root is ineffective. " <<
"Please stop using it.", caller
end
def relative_url_root=
ActiveSupport::Deprecation.warn "ActionController::Base.relative_url_root= is ineffective. " <<
"Please stop using it.", caller
end
def consider_all_requests_local
ActiveSupport::Deprecation.warn "ActionController::Base.consider_all_requests_local is deprecated, " <<
"use Rails.application.config.consider_all_requests_local instead", caller
Rails.application.config.consider_all_requests_local
end
def consider_all_requests_local=(value)
ActiveSupport::Deprecation.warn "ActionController::Base.consider_all_requests_local= is deprecated. " <<
"Please configure it on your application with config.consider_all_requests_local=", caller
Rails.application.config.consider_all_requests_local = value
end
def allow_concurrency
ActiveSupport::Deprecation.warn "ActionController::Base.allow_concurrency is deprecated, " <<
"use Rails.application.config.allow_concurrency instead", caller
Rails.application.config.allow_concurrency
end
def allow_concurrency=(value)
ActiveSupport::Deprecation.warn "ActionController::Base.allow_concurrency= is deprecated. " <<
"Please configure it on your application with config.allow_concurrency=", caller
Rails.application.config.allow_concurrency = value
end
def ip_spoofing_check=(value)
ActiveSupport::Deprecation.warn "ActionController::Base.ip_spoofing_check= is deprecated. " <<
"Please configure it on your application with config.action_dispatch.ip_spoofing_check=", caller
Rails.application.config.action_dispatch.ip_spoofing_check = value
end
def ip_spoofing_check
ActiveSupport::Deprecation.warn "ActionController::Base.ip_spoofing_check is deprecated. " <<
"Configuring ip_spoofing_check on the application configures a middleware.", caller
Rails.application.config.action_dispatch.ip_spoofing_check
end
def cookie_verifier_secret=(value)
ActiveSupport::Deprecation.warn "ActionController::Base.cookie_verifier_secret= is deprecated. " <<
"Please configure it on your application with config.secret_token=", caller
end
def cookie_verifier_secret
ActiveSupport::Deprecation.warn "ActionController::Base.cookie_verifier_secret is deprecated.", caller
end
def trusted_proxies=(value)
ActiveSupport::Deprecation.warn "ActionController::Base.trusted_proxies= is deprecated. " <<
"Please configure it on your application with config.action_dispatch.trusted_proxies=", caller
Rails.application.config.action_dispatch.ip_spoofing_check = value
end
def trusted_proxies
ActiveSupport::Deprecation.warn "ActionController::Base.trusted_proxies is deprecated. " <<
"Configuring trusted_proxies on the application configures a middleware.", caller
Rails.application.config.action_dispatch.ip_spoofing_check = value
end
def session(*args)
ActiveSupport::Deprecation.warn(
"Disabling sessions for a single controller has been deprecated. " +
"Sessions are now lazy loaded. So if you don't access them, " +
"consider them off. You can still modify the session cookie " +
"options with request.session_options.", caller)
end
def session=(value)
ActiveSupport::Deprecation.warn "ActionController::Base.session= is deprecated. " <<
"Please configure it on your application with config.session_store :cookie_store, :key => '....'", caller
if secret = value.delete(:secret)
Rails.application.config.secret_token = secret
end
if value.delete(:disabled)
Rails.application.config.session_store :disabled
else
store = Rails.application.config.session_store
Rails.application.config.session_store store, value
end
end
# Controls the resource action separator
def resource_action_separator
@resource_action_separator ||= "/"
end
def resource_action_separator=(val)
ActiveSupport::Deprecation.warn "ActionController::Base.resource_action_separator is deprecated and only " \
"works with the deprecated router DSL."
@resource_action_separator = val
end
def use_accept_header
ActiveSupport::Deprecation.warn "ActionController::Base.use_accept_header doesn't do anything anymore. " \
"The accept header is always taken into account."
end
def use_accept_header=(val)
use_accept_header
end
# This method has been moved to ActionDispatch::Request.filter_parameters
def filter_parameter_logging(*args, &block)
ActiveSupport::Deprecation.warn("Setting filter_parameter_logging in ActionController is deprecated and has no longer effect, please set 'config.filter_parameters' in config/application.rb instead", caller)
filter = Rails.application.config.filter_parameters
filter.concat(args)
filter << block if block
filter
end
# This was moved to a plugin
def verify(*args)
ActiveSupport::Deprecation.warn "verify was removed from Rails and is now available as a plugin. " \
"Please install it with `rails plugin install git://github.com/rails/verification.git`.", caller
end
def exempt_from_layout(*)
ActiveSupport::Deprecation.warn "exempt_from_layout is no longer needed, because layouts in Rails 3 " \
"are restricted to the content-type of the template that was rendered.", caller
end
end
extend DeprecatedBehavior
delegate :consider_all_requests_local, :consider_all_requests_local=,
:allow_concurrency, :allow_concurrency=, :to => :"self.class"
end
end

View File

@@ -0,0 +1,28 @@
module ActionController
class Dispatcher
class << self
def before_dispatch(*args, &block)
ActiveSupport::Deprecation.warn "ActionController::Dispatcher.before_dispatch is deprecated. " <<
"Please use ActionDispatch::Callbacks.before instead.", caller
ActionDispatch::Callbacks.before(*args, &block)
end
def after_dispatch(*args, &block)
ActiveSupport::Deprecation.warn "ActionController::Dispatcher.after_dispatch is deprecated. " <<
"Please use ActionDispatch::Callbacks.after instead.", caller
ActionDispatch::Callbacks.after(*args, &block)
end
def to_prepare(*args, &block)
ActiveSupport::Deprecation.warn "ActionController::Dispatcher.to_prepare is deprecated. " <<
"Please use config.to_prepare instead", caller
ActionDispatch::Callbacks.after(*args, &block)
end
def new
ActiveSupport::Deprecation.warn "ActionController::Dispatcher.new is deprecated, use Rails.application instead."
Rails.application
end
end
end
end

View File

@@ -0,0 +1,14 @@
module ActionController
module UrlWriter
def self.included(klass)
ActiveSupport::Deprecation.warn "include ActionController::UrlWriter is deprecated. Instead, " \
"include Rails.application.routes.url_helpers"
klass.class_eval { include Rails.application.routes.url_helpers }
end
end
class UrlRewriter
def initialize(*)
end
end
end

View File

@@ -7,10 +7,8 @@ module ActionController
def start_processing(event)
payload = event.payload
params = payload[:params].except(*INTERNAL_PARAMS)
format = payload[:format]
format = format.to_s.upcase if format.is_a?(Symbol)
info "Processing by #{payload[:controller]}##{payload[:action]} as #{format}"
info " Processing by #{payload[:controller]}##{payload[:action]} as #{payload[:formats].first.to_s.upcase}"
info " Parameters: #{params.inspect}" unless params.empty?
end
@@ -18,23 +16,16 @@ module ActionController
payload = event.payload
additions = ActionController::Base.log_process_action(payload)
status = payload[:status]
if status.nil? && payload[:exception].present?
exception_class_name = payload[:exception].first
status = ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class_name)
end
message = "Completed #{status} #{Rack::Utils::HTTP_STATUS_CODES[status]} in #{format_duration(event.duration)}"
message = "Completed #{payload[:status]} #{Rack::Utils::HTTP_STATUS_CODES[payload[:status]]} in %.0fms" % event.duration
message << " (#{additions.join(" | ")})" unless additions.blank?
info(message)
end
def halted_callback(event)
info "Filter chain halted as #{event.payload[:filter]} rendered or redirected"
end
def send_file(event)
info("Sent file #{event.payload[:path]} (#{format_duration(event.duration)})")
message = "Sent file %s"
message << " (%.1fms)"
info(message % [event.payload[:path], event.duration])
end
def redirect_to(event)
@@ -42,7 +33,7 @@ module ActionController
end
def send_data(event)
info("Sent data #{event.payload[:filename]} (#{format_duration(event.duration)})")
info("Sent data %s (%.1fms)" % [event.payload[:filename], event.duration])
end
%w(write_fragment read_fragment exist_fragment?
@@ -51,8 +42,7 @@ module ActionController
def #{method}(event)
key_or_path = event.payload[:key] || event.payload[:path]
human_name = #{method.to_s.humanize.inspect}
duration = format_duration(event.duration)
info("\#{human_name} \#{key_or_path} \#{duration}")
info("\#{human_name} \#{key_or_path} (%.1fms)" % event.duration)
end
METHOD
end
@@ -63,4 +53,4 @@ module ActionController
end
end
ActionController::LogSubscriber.attach_to :action_controller
ActionController::LogSubscriber.attach_to :action_controller

View File

@@ -36,88 +36,35 @@ module ActionController
action = action.to_s
raise "MiddlewareStack#build requires an app" unless app
middlewares.reverse.inject(app) do |a, middleware|
reverse.inject(app) do |a, middleware|
middleware.valid?(action) ?
middleware.build(a) : a
end
end
end
# <tt>ActionController::Metal</tt> is the simplest possible controller, providing a
# valid Rack interface without the additional niceties provided by
# <tt>ActionController::Base</tt>.
#
# A sample metal controller might look like this:
#
# class HelloController < ActionController::Metal
# def index
# self.response_body = "Hello World!"
# end
# end
#
# And then to route requests to your metal controller, you would add
# something like this to <tt>config/routes.rb</tt>:
#
# match 'hello', :to => HelloController.action(:index)
#
# The +action+ method returns a valid Rack application for the \Rails
# router to dispatch to.
#
# == Rendering Helpers
#
# <tt>ActionController::Metal</tt> by default provides no utilities for rendering
# views, partials, or other responses aside from explicitly calling of
# <tt>response_body=</tt>, <tt>content_type=</tt>, and <tt>status=</tt>. To
# add the render helpers you're used to having in a normal controller, you
# can do the following:
#
# class HelloController < ActionController::Metal
# include ActionController::Rendering
# append_view_path "#{Rails.root}/app/views"
#
# def index
# render "hello/index"
# end
# end
#
# == Redirection Helpers
#
# To add redirection helpers to your metal controller, do the following:
#
# class HelloController < ActionController::Metal
# include ActionController::Redirecting
# include Rails.application.routes.url_helpers
#
# def index
# redirect_to root_url
# end
# end
#
# == Other Helpers
#
# You can refer to the modules included in <tt>ActionController::Base</tt> to see
# other features you can bring into your metal controller.
# ActionController::Metal provides a way to get a valid Rack application from a controller.
#
# In AbstractController, dispatching is triggered directly by calling #process on a new controller.
# ActionController::Metal provides an #action method that returns a valid Rack application for a
# given action. Other rack builders, such as Rack::Builder, Rack::URLMap, and the Rails router,
# can dispatch directly to the action returned by FooController.action(:index).
class Metal < AbstractController::Base
abstract!
attr_internal_writer :env
def env
@_env ||= {}
end
attr_internal :env
# Returns the last part of the controller's name, underscored, without the ending
# <tt>Controller</tt>. For instance, PostsController returns <tt>posts</tt>.
# Namespaces are left out, so Admin::PostsController returns <tt>posts</tt> as well.
# "Controller". For instance, MyApp::MyPostsController would return "my_posts" for
# controller_name
#
# ==== Returns
# * <tt>string</tt>
# String
def self.controller_name
@controller_name ||= self.name.demodulize.sub(/Controller$/, '').underscore
end
# Delegates to the class' <tt>controller_name</tt>
# Delegates to the class' #controller_name
def controller_name
self.class.controller_name
end
@@ -131,12 +78,9 @@ module ActionController
attr_internal :headers, :response, :request
delegate :session, :to => "@_request"
def initialize
def initialize(*)
@_headers = {"Content-Type" => "text/html"}
@_status = 200
@_request = nil
@_response = nil
@_routes = nil
super
end
@@ -182,21 +126,12 @@ module ActionController
end
def response_body=(val)
body = if val.is_a?(String)
[val]
elsif val.nil? || val.respond_to?(:each)
val
else
[val]
end
body = val.respond_to?(:each) ? val : [val]
super body
end
def performed?
response_body
end
def dispatch(name, request) #:nodoc:
# :api: private
def dispatch(name, request)
@_request = request
@_env = request.env
@_env['action_controller.instance'] = self
@@ -204,30 +139,27 @@ module ActionController
to_a
end
def to_a #:nodoc:
# :api: private
def to_a
response ? response.to_a : [status, headers, response_body]
end
class_attribute :middleware_stack
self.middleware_stack = ActionController::MiddlewareStack.new
def self.inherited(base) #nodoc:
def self.inherited(base)
base.middleware_stack = self.middleware_stack.dup
super
end
# Adds given middleware class and its args to bottom of middleware_stack
def self.use(*args, &block)
middleware_stack.use(*args, &block)
end
# Alias for middleware_stack
def self.middleware
middleware_stack
end
# Makes the controller a rack endpoint that points to the action in
# the given env's action_dispatch.request.path_parameters key.
def self.call(env)
action(env['action_dispatch.request.path_parameters'][:action]).call(env)
end
@@ -237,10 +169,10 @@ module ActionController
# for the same action.
#
# ==== Parameters
# * <tt>action</tt> - An action name
# action<#to_s>:: An action name
#
# ==== Returns
# * <tt>proc</tt> - A rack application
# Proc:: A rack application
def self.action(name, klass = ActionDispatch::Request)
middleware_stack.build(name.to_s) do |env|
new.dispatch(name, klass.new(env))

View File

@@ -1,45 +1,50 @@
require 'active_support/deprecation'
module ActionController
module Compatibility
extend ActiveSupport::Concern
class ::ActionController::ActionControllerError < StandardError #:nodoc:
end
module ClassMethods
end
# Temporary hax
included do
::ActionController::UnknownAction = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('ActionController::UnknownAction', '::AbstractController::ActionNotFound')
::ActionController::DoubleRenderError = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('ActionController::DoubleRenderError', '::AbstractController::DoubleRenderError')
::ActionController::UnknownAction = ::AbstractController::ActionNotFound
::ActionController::DoubleRenderError = ::AbstractController::DoubleRenderError
# ROUTES TODO: This should be handled by a middleware and route generation
# should be able to handle SCRIPT_NAME
self.config.relative_url_root = ENV['RAILS_RELATIVE_URL_ROOT']
def self.default_charset=(new_charset)
ActiveSupport::Deprecation.warn "Setting default charset at controller level" \
" is deprecated, please use `config.action_dispatch.default_charset` instead", caller
ActionDispatch::Response.default_charset = new_charset
class << self
delegate :default_charset=, :to => "ActionDispatch::Response"
end
self.protected_instance_variables = %w(
@_status @_headers @_params @_env @_response @_request
@_view_runtime @_stream @_url_options @_action_has_layout
)
# TODO: Update protected instance variables list
config_accessor :protected_instance_variables
self.protected_instance_variables = %w(@assigns @performed_redirect @performed_render
@variables_added @request_origin @url
@parent_controller @action_name
@before_filter_chain_aborted @_headers @_params
@_response)
def rescue_action(env)
ActiveSupport::Deprecation.warn "Calling `rescue_action` is deprecated and will be removed in Rails 4.0.", caller
raise env["action_dispatch.rescue.exception"]
end
end
# For old tests
def initialize_template_class(*)
ActiveSupport::Deprecation.warn "Calling `initialize_template_class` is deprecated and has no effect anymore.", caller
end
def assign_shortcuts(*)
ActiveSupport::Deprecation.warn "Calling `assign_shortcuts` is deprecated and has no effect anymore.", caller
end
def initialize_template_class(*) end
def assign_shortcuts(*) end
def _normalize_options(options)
if options[:action] && options[:action].to_s.include?(?/)
ActiveSupport::Deprecation.warn "Giving a path to render :action is deprecated. " <<
"Please use render :template instead", caller
options[:template] = options.delete(:action)
end
options[:text] = nil if options.delete(:nothing) == true
options[:text] = " " if options.key?(:text) && options[:text].nil?
super
@@ -51,15 +56,15 @@ module ActionController
end
def _handle_method_missing
ActiveSupport::Deprecation.warn "Using `method_missing` to handle non" \
" existing actions is deprecated and will be removed in Rails 4.0, " \
" please use `action_missing` instead.", caller
method_missing(@_action_name.to_sym)
end
def method_for_action(action_name)
super || ((self.class.public_method_defined?(:method_missing) ||
self.class.protected_method_defined?(:method_missing)) && "_handle_method_missing")
super || (respond_to?(:method_missing) && "_handle_method_missing")
end
def performed?
response_body
end
end
end

View File

@@ -6,7 +6,7 @@ module ActionController
include Head
# Sets the etag, last_modified, or both on the response and renders a
# <tt>304 Not Modified</tt> response if the request is already fresh.
# "304 Not Modified" response if the request is already fresh.
#
# Parameters:
# * <tt>:etag</tt>
@@ -17,33 +17,14 @@ module ActionController
#
# def show
# @article = Article.find(params[:id])
# fresh_when(:etag => @article, :last_modified => @article.created_at, :public => true)
# fresh_when(:etag => @article, :last_modified => @article.created_at.utc, :public => true)
# end
#
# This will render the show template if the request isn't sending a matching etag or
# If-Modified-Since header and just a <tt>304 Not Modified</tt> response if there's a match.
# If-Modified-Since header and just a "304 Not Modified" response if there's a match.
#
# You can also just pass a record where last_modified will be set by calling updated_at and the etag by passing the object itself. Example:
#
# def show
# @article = Article.find(params[:id])
# fresh_when(@article)
# end
#
# When passing a record, you can still set whether the public header:
#
# def show
# @article = Article.find(params[:id])
# fresh_when(@article, :public => true)
# end
def fresh_when(record_or_options, additional_options = {})
if record_or_options.is_a? Hash
options = record_or_options
options.assert_valid_keys(:etag, :last_modified, :public)
else
record = record_or_options
options = { :etag => record, :last_modified => record.try(:updated_at) }.merge(additional_options)
end
def fresh_when(options)
options.assert_valid_keys(:etag, :last_modified, :public)
response.etag = options[:etag] if options[:etag]
response.last_modified = options[:last_modified] if options[:last_modified]
@@ -55,7 +36,7 @@ module ActionController
# Sets the etag and/or last_modified on the response and checks it against
# the client request. If the request doesn't match the options provided, the
# request is considered stale and should be generated from scratch. Otherwise,
# it's fresh and we don't need to generate anything and a reply of <tt>304 Not Modified</tt> is sent.
# it's fresh and we don't need to generate anything and a reply of "304 Not Modified" is sent.
#
# Parameters:
# * <tt>:etag</tt>
@@ -67,51 +48,25 @@ module ActionController
# def show
# @article = Article.find(params[:id])
#
# if stale?(:etag => @article, :last_modified => @article.created_at)
# if stale?(:etag => @article, :last_modified => @article.created_at.utc)
# @statistics = @article.really_expensive_call
# respond_to do |format|
# # all the supported formats
# end
# end
# end
#
# You can also just pass a record where last_modified will be set by calling updated_at and the etag by passing the object itself. Example:
#
# def show
# @article = Article.find(params[:id])
#
# if stale?(@article)
# @statistics = @article.really_expensive_call
# respond_to do |format|
# # all the supported formats
# end
# end
# end
#
# When passing a record, you can still set whether the public header:
#
# def show
# @article = Article.find(params[:id])
#
# if stale?(@article, :public => true)
# @statistics = @article.really_expensive_call
# respond_to do |format|
# # all the supported formats
# end
# end
# end
def stale?(record_or_options, additional_options = {})
fresh_when(record_or_options, additional_options)
def stale?(options)
fresh_when(options)
!request.fresh?(response)
end
# Sets a HTTP 1.1 Cache-Control header. Defaults to issuing a <tt>private</tt> instruction, so that
# intermediate caches must not cache the response.
# Sets a HTTP 1.1 Cache-Control header. Defaults to issuing a "private" instruction, so that
# intermediate caches shouldn't cache the response.
#
# Examples:
# expires_in 20.minutes
# expires_in 3.hours, :public => true
# expires_in 3.hours, 'max-stale' => 5.hours, :public => true
# expires in 3.hours, 'max-stale' => 5.hours, :public => true
#
# This method will overwrite an existing Cache-Control header.
# See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html for more possibilities.
@@ -122,7 +77,7 @@ module ActionController
response.cache_control[:extras] = options.map {|k,v| "#{k}=#{v}"}
end
# Sets a HTTP 1.1 Cache-Control header of <tt>no-cache</tt> so no caching should occur by the browser or
# Sets a HTTP 1.1 Cache-Control header of "no-cache" so no caching should occur by the browser or
# intermediate caches (like caching proxy servers).
def expires_now #:doc:
response.cache_control.replace(:no_cache => true)

View File

@@ -1,177 +0,0 @@
require 'active_support/core_ext/file/path'
require 'action_controller/metal/exceptions'
module ActionController #:nodoc:
# Methods for sending arbitrary data and for streaming files to the browser,
# instead of rendering.
module DataStreaming
extend ActiveSupport::Concern
include ActionController::Rendering
DEFAULT_SEND_FILE_OPTIONS = {
:type => 'application/octet-stream'.freeze,
:disposition => 'attachment'.freeze,
}.freeze
protected
# Sends the file. This uses a server-appropriate method (such as X-Sendfile)
# via the Rack::Sendfile middleware. The header to use is set via
# config.action_dispatch.x_sendfile_header.
# Your server can also configure this for you by setting the X-Sendfile-Type header.
#
# Be careful to sanitize the path parameter if it is coming from a web
# page. <tt>send_file(params[:path])</tt> allows a malicious user to
# download any file on your server.
#
# Options:
# * <tt>:filename</tt> - suggests a filename for the browser to use.
# Defaults to <tt>File.basename(path)</tt>.
# * <tt>:type</tt> - specifies an HTTP content type.
# You can specify either a string or a symbol for a registered type register with
# <tt>Mime::Type.register</tt>, for example :json
# If omitted, type will be guessed from the file extension specified in <tt>:filename</tt>.
# If no content type is registered for the extension, default type 'application/octet-stream' will be used.
# * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
# Valid values are 'inline' and 'attachment' (default).
# * <tt>:status</tt> - specifies the status code to send with the response. Defaults to 200.
# * <tt>:url_based_filename</tt> - set to +true+ if you want the browser guess the filename from
# the URL, which is necessary for i18n filenames on certain browsers
# (setting <tt>:filename</tt> overrides this option).
#
# The default Content-Type and Content-Disposition headers are
# set to download arbitrary binary files in as many browsers as
# possible. IE versions 4, 5, 5.5, and 6 are all known to have
# a variety of quirks (especially when downloading over SSL).
#
# Simple download:
#
# send_file '/path/to.zip'
#
# Show a JPEG in the browser:
#
# send_file '/path/to.jpeg', :type => 'image/jpeg', :disposition => 'inline'
#
# Show a 404 page in the browser:
#
# send_file '/path/to/404.html', :type => 'text/html; charset=utf-8', :status => 404
#
# Read about the other Content-* HTTP headers if you'd like to
# provide the user with more information (such as Content-Description) in
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11.
#
# Also be aware that the document may be cached by proxies and browsers.
# The Pragma and Cache-Control headers declare how the file may be cached
# by intermediaries. They default to require clients to validate with
# the server before releasing cached responses. See
# http://www.mnot.net/cache_docs/ for an overview of web caching and
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
# for the Cache-Control header spec.
def send_file(path, options = {}) #:doc:
raise MissingFile, "Cannot read file #{path}" unless File.file?(path) and File.readable?(path)
options[:filename] ||= File.basename(path) unless options[:url_based_filename]
send_file_headers! options
self.status = options[:status] || 200
self.content_type = options[:content_type] if options.key?(:content_type)
self.response_body = FileBody.new(path)
end
# Avoid having to pass an open file handle as the response body.
# Rack::Sendfile will usually intercept the response and uses
# the path directly, so there is no reason to open the file.
class FileBody #:nodoc:
attr_reader :to_path
def initialize(path)
@to_path = path
end
# Stream the file's contents if Rack::Sendfile isn't present.
def each
File.open(to_path, 'rb') do |file|
while chunk = file.read(16384)
yield chunk
end
end
end
end
# Sends the given binary data to the browser. This method is similar to
# <tt>render :text => data</tt>, but also allows you to specify whether
# the browser should display the response as a file attachment (i.e. in a
# download dialog) or as inline data. You may also set the content type,
# the apparent file name, and other things.
#
# Options:
# * <tt>:filename</tt> - suggests a filename for the browser to use.
# * <tt>:type</tt> - specifies an HTTP content type. Defaults to 'application/octet-stream'. You can specify
# either a string or a symbol for a registered type register with <tt>Mime::Type.register</tt>, for example :json
# If omitted, type will be guessed from the file extension specified in <tt>:filename</tt>.
# If no content type is registered for the extension, default type 'application/octet-stream' will be used.
# * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
# Valid values are 'inline' and 'attachment' (default).
# * <tt>:status</tt> - specifies the status code to send with the response. Defaults to 200.
#
# Generic data download:
#
# send_data buffer
#
# Download a dynamically-generated tarball:
#
# send_data generate_tgz('dir'), :filename => 'dir.tgz'
#
# Display an image Active Record in the browser:
#
# send_data image.data, :type => image.content_type, :disposition => 'inline'
#
# See +send_file+ for more information on HTTP Content-* headers and caching.
def send_data(data, options = {}) #:doc:
send_file_headers! options.dup
render options.slice(:status, :content_type).merge(:text => data)
end
private
def send_file_headers!(options)
type_provided = options.has_key?(:type)
options.update(DEFAULT_SEND_FILE_OPTIONS.merge(options))
[:type, :disposition].each do |arg|
raise ArgumentError, ":#{arg} option required" if options[arg].nil?
end
disposition = options[:disposition].to_s
disposition += %(; filename="#{options[:filename]}") if options[:filename]
content_type = options[:type]
if content_type.is_a?(Symbol)
extension = Mime[content_type]
raise ArgumentError, "Unknown MIME type #{options[:type]}" unless extension
self.content_type = extension
else
if !type_provided && options[:filename]
# If type wasn't provided, try guessing from file extension.
content_type = Mime::Type.lookup_by_extension(File.extname(options[:filename]).downcase.tr('.','')) || content_type
end
self.content_type = content_type
end
headers.merge!(
'Content-Disposition' => disposition,
'Content-Transfer-Encoding' => 'binary'
)
response.sending_file = true
# Fix a problem with IE 6.0 on opening downloaded files:
# If Cache-Control: no-cache is set (which Rails does by default),
# IE removes the file it just downloaded from its cache immediately
# after it displays the "open/save" dialog, which means that if you
# hit "open" the file isn't there anymore when the application that
# is called for handling the download is run, so let's workaround that
response.cache_control[:public] ||= false
end
end
end

View File

@@ -1,39 +0,0 @@
module ActionController
# This module provides a method which will redirect browser to use HTTPS
# protocol. This will ensure that user's sensitive information will be
# transferred safely over the internet. You _should_ always force browser
# to use HTTPS when you're transferring sensitive information such as
# user authentication, account information, or credit card information.
#
# Note that if you are really concerned about your application security,
# you might consider using +config.force_ssl+ in your config file instead.
# That will ensure all the data transferred via HTTPS protocol and prevent
# user from getting session hijacked when accessing the site under unsecured
# HTTP protocol.
module ForceSSL
extend ActiveSupport::Concern
include AbstractController::Callbacks
module ClassMethods
# Force the request to this particular controller or specified actions to be
# under HTTPS protocol.
#
# Note that this method will not be effective on development environment.
#
# ==== Options
# * <tt>only</tt> - The callback should be run only for this action
# * <tt>except</tt> - The callback should be run for all actions except this action
def force_ssl(options = {})
host = options.delete(:host)
before_filter(options) do
if !request.ssl? && !Rails.env.development?
redirect_options = {:protocol => 'https://', :status => :moved_permanently}
redirect_options.merge!(:host => host) if host
redirect_options.merge!(:params => request.query_parameters)
redirect_to redirect_options
end
end
end
end
end
end

View File

@@ -9,8 +9,6 @@ module ActionController
#
# head :created, :location => person_path(@person)
#
# head :created, :location => @person
#
# It can also be used to return exceptional conditions:
#
# return head(:method_not_allowed) unless request.post?
@@ -20,15 +18,14 @@ module ActionController
options, status = status, nil if status.is_a?(Hash)
status ||= options.delete(:status) || :ok
location = options.delete(:location)
content_type = options.delete(:content_type)
options.each do |key, value|
headers[key.to_s.dasherize.split('-').each { |v| v[0] = v[0].chr.upcase }.join('-')] = value.to_s
headers[key.to_s.dasherize.split(/-/).map { |v| v.capitalize }.join("-")] = value.to_s
end
self.status = status
self.location = url_for(location) if location
self.content_type = content_type || (Mime[formats.first] if formats)
self.content_type = Mime[formats.first] if formats
self.response_body = " "
end
end

View File

@@ -2,24 +2,21 @@ require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/class/attribute'
module ActionController
# The \Rails framework provides a large number of helpers for working with assets, dates, forms,
# numbers and model objects, to name a few. These helpers are available to all templates
# The Rails framework provides a large number of helpers for working with +assets+, +dates+, +forms+,
# +numbers+ and model objects, to name a few. These helpers are available to all templates
# by default.
#
# In addition to using the standard template helpers provided, creating custom helpers to
# extract complicated logic or reusable functionality is strongly encouraged. By default, each controller
# will include all helpers.
# In addition to using the standard template helpers provided in the Rails framework, creating custom helpers to
# extract complicated logic or reusable functionality is strongly encouraged. By default, the controller will
# include a helper whose name matches that of the controller, e.g., <tt>MyController</tt> will automatically
# include <tt>MyHelper</tt>.
#
# In previous versions of \Rails the controller will include a helper whose
# name matches that of the controller, e.g., <tt>MyController</tt> will automatically
# include <tt>MyHelper</tt>. To return old behavior set +config.action_controller.include_all_helpers+ to +false+.
#
# Additional helpers can be specified using the +helper+ class method in ActionController::Base or any
# Additional helpers can be specified using the +helper+ class method in <tt>ActionController::Base</tt> or any
# 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
# a \Time object is blank:
# 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
# def format_time(time, format=:long, blank_message="&nbsp;")
@@ -32,7 +29,7 @@ module ActionController
# class EventsController < ActionController::Base
# helper FormattedTimeHelper
# def index
# @events = Event.all
# @events = Event.find(:all)
# end
# end
#
@@ -56,20 +53,30 @@ module ActionController
include AbstractController::Helpers
included do
class_attribute :helpers_path, :include_all_helpers
config_accessor :helpers_path
self.helpers_path ||= []
self.include_all_helpers = true
end
module ClassMethods
def helpers_dir
ActiveSupport::Deprecation.warn "helpers_dir is deprecated, use helpers_path instead", caller
self.helpers_path
end
def helpers_dir=(value)
ActiveSupport::Deprecation.warn "helpers_dir= is deprecated, use helpers_path= instead", caller
self.helpers_path = Array.wrap(value)
end
# Declares helper accessors for controller attributes. For example, the
# following adds new +name+ and <tt>name=</tt> instance methods to a
# controller and makes them available to the view:
# attr_accessor :name
# helper_attr :name
# attr_accessor :name
#
# ==== Parameters
# * <tt>attrs</tt> - Names of attributes to be converted into helpers.
# *attrs<Array[String, Symbol]>:: Names of attributes to be converted
# into helpers.
def helper_attr(*attrs)
attrs.flatten.each { |attr| helper_method(attr, "#{attr}=") }
end
@@ -79,35 +86,32 @@ module ActionController
@helper_proxy ||= ActionView::Base.new.extend(_helpers)
end
# Overwrite modules_for_helpers to accept :all as argument, which loads
# all helpers in helpers_path.
#
# ==== Parameters
# * <tt>args</tt> - A list of helpers
#
# ==== Returns
# * <tt>array</tt> - A normalized list of modules for the list of helpers provided.
def modules_for_helpers(args)
args += all_application_helpers if args.delete(:all)
super(args)
end
def all_helpers_from_path(path)
helpers = []
Array.wrap(path).each do |_path|
extract = /^#{Regexp.quote(_path.to_s)}\/?(.*)_helper.rb$/
helpers += Dir["#{_path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1') }
end
helpers.sort!
helpers.uniq!
helpers
end
private
# Extract helper names from files in <tt>app/helpers/**/*_helper.rb</tt>
def all_application_helpers
all_helpers_from_path(helpers_path)
end
# Overwrite modules_for_helpers to accept :all as argument, which loads
# all helpers in helpers_dir.
#
# ==== Parameters
# args<Array[String, Symbol, Module, all]>:: A list of helpers
#
# ==== Returns
# Array[Module]:: A normalized list of modules for the list of
# helpers provided.
def modules_for_helpers(args)
args += all_application_helpers if args.delete(:all)
super(args)
end
# Extract helper names from files in app/helpers/**/*_helper.rb
def all_application_helpers
helpers = []
Array.wrap(helpers_path).each do |path|
extract = /^#{Regexp.quote(path.to_s)}\/?(.*)_helper.rb$/
helpers += Dir["#{path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1') }
end
helpers.sort!
helpers.uniq!
helpers
end
end
end
end

View File

@@ -1,7 +1,8 @@
require 'active_support/core_ext/class/attribute'
module ActionController
# Adds the ability to prevent public methods on a controller to be called as actions.
# ActionController::HideActions adds the ability to prevent public methods on a controller
# to be called as actions.
module HideActions
extend ActiveSupport::Concern
@@ -22,19 +23,25 @@ module ActionController
# Sets all of the actions passed in as hidden actions.
#
# ==== Parameters
# * <tt>args</tt> - A list of actions
# *args<#to_s>:: A list of actions
def hide_action(*args)
self.hidden_actions = hidden_actions.dup.merge(args.map(&:to_s)).freeze
end
def inherited(klass)
klass.class_eval { @visible_actions = {} }
super
end
def visible_action?(action_name)
not hidden_actions.include?(action_name)
return @visible_actions[action_name] if @visible_actions.key?(action_name)
@visible_actions[action_name] = !hidden_actions.include?(action_name)
end
# Overrides AbstractController::Base#action_methods to remove any methods
# that are listed as hidden methods.
def action_methods
@action_methods ||= Set.new(super.reject { |name| hidden_actions.include?(name) }).freeze
@action_methods ||= Set.new(super.reject { |name| hidden_actions.include?(name) })
end
end
end

View File

@@ -3,12 +3,14 @@ require 'active_support/core_ext/object/blank'
module ActionController
module HttpAuthentication
# Makes it dead easy to do HTTP \Basic and \Digest authentication.
# Makes it dead easy to do HTTP Basic authentication.
#
# === Simple \Basic example
# Simple Basic example:
#
# class PostsController < ApplicationController
# http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index
# USER_NAME, PASSWORD = "dhh", "secret"
#
# before_filter :authenticate, :except => [ :index ]
#
# def index
# render :text => "Everyone can see me!"
@@ -17,11 +19,17 @@ module ActionController
# def edit
# render :text => "I'm only accessible if you know the password"
# end
# end
#
# === Advanced \Basic example
# private
# def authenticate
# authenticate_or_request_with_http_basic do |user_name, password|
# user_name == USER_NAME && password == PASSWORD
# end
# end
# end
#
# Here is a more advanced \Basic example where only Atom feeds and the XML API is protected by HTTP authentication,
#
# Here is a more advanced Basic example where only Atom feeds and the XML API is protected by HTTP authentication,
# the regular HTML interface is protected by a session approach:
#
# class ApplicationController < ActionController::Base
@@ -61,13 +69,13 @@ module ActionController
# assert_equal 200, status
# end
#
# === Simple \Digest example
# Simple Digest example:
#
# require 'digest/md5'
# class PostsController < ApplicationController
# REALM = "SuperSecret"
# USERS = {"dhh" => "secret", #plain text password
# "dap" => Digest::MD5.hexdigest(["dap",REALM,"secret"].join(":"))} #ha1 digest password
# "dap" => Digest:MD5::hexdigest(["dap",REALM,"secret"].join(":")) #ha1 digest password
#
# before_filter :authenticate, :except => [:index]
#
@@ -93,30 +101,15 @@ module ActionController
# or the ha1 digest hash so the framework can appropriately hash to check the user's
# credentials. Returning +nil+ will cause authentication to fail.
#
# Storing the ha1 hash: MD5(username:realm:password), is better than storing a plain password. If
# the password file or database is compromised, the attacker would be able to use the ha1 hash to
# authenticate as the user at this +realm+, but would not have the user's password to try using at
# other sites.
# On shared hosts, Apache sometimes doesn't pass authentication headers to
# FCGI instances. If your environment matches this description and you cannot
# authenticate, try this rule in your Apache setup:
#
# In rare instances, web servers or front proxies strip authorization headers before
# they reach your application. You can debug this situation by logging all environment
# variables, and check for HTTP_AUTHORIZATION, amongst others.
# RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
module Basic
extend self
module ControllerMethods
extend ActiveSupport::Concern
module ClassMethods
def http_basic_authenticate_with(options = {})
before_filter(options.except(:name, :password, :realm)) do
authenticate_or_request_with_http_basic(options[:realm] || "Application") do |name, password|
name == options[:name] && password == options[:password]
end
end
end
end
def authenticate_or_request_with_http_basic(realm = "Application", &login_procedure)
authenticate_with_http_basic(&login_procedure) || request_http_basic_authentication(realm)
end
@@ -141,11 +134,11 @@ module ActionController
end
def decode_credentials(request)
::Base64.decode64(request.authorization.split(' ', 2).last || '')
ActiveSupport::Base64.decode64(request.authorization.split(' ', 2).last || '')
end
def encode_credentials(user_name, password)
"Basic #{::Base64.strict_encode64("#{user_name}:#{password}")}"
"Basic #{ActiveSupport::Base64.encode64("#{user_name}:#{password}")}"
end
def authentication_request(controller, realm)
@@ -192,15 +185,12 @@ module ActionController
return false unless password
method = request.env['rack.methodoverride.original_method'] || request.env['REQUEST_METHOD']
uri = credentials[:uri][0,1] == '/' ? request.original_fullpath : request.original_url
uri = credentials[:uri][0,1] == '/' ? request.fullpath : request.url
[true, false].any? do |trailing_question_mark|
[true, false].any? do |password_is_ha1|
_uri = trailing_question_mark ? uri + "?" : uri
expected = expected_response(method, _uri, credentials, password, password_is_ha1)
expected == credentials[:response]
end
end
[true, false].any? do |password_is_ha1|
expected = expected_response(method, uri, credentials, password, password_is_ha1)
expected == credentials[:response]
end
end
end
@@ -219,7 +209,7 @@ module ActionController
def encode_credentials(http_method, credentials, password, password_is_ha1)
credentials[:response] = expected_response(http_method, credentials[:uri], credentials, password, password_is_ha1)
"Digest " + credentials.sort_by {|x| x[0].to_s }.map {|v| "#{v[0]}='#{v[1]}'" }.join(', ')
"Digest " + credentials.sort_by {|x| x[0].to_s }.inject([]) {|a, v| a << "#{v[0]}='#{v[1]}'" }.join(', ')
end
def decode_credentials_header(request)
@@ -227,9 +217,9 @@ module ActionController
end
def decode_credentials(header)
HashWithIndifferentAccess[header.to_s.gsub(/^Digest\s+/,'').split(',').map do |pair|
Hash[header.to_s.gsub(/^Digest\s+/,'').split(',').map do |pair|
key, value = pair.split('=', 2)
[key.strip, value.to_s.gsub(/^"|"$/,'').delete('\'')]
[key.strip.to_sym, value.to_s.gsub(/^"|"$/,'').gsub(/'/, '')]
end]
end
@@ -289,7 +279,7 @@ module ActionController
t = time.to_i
hashed = [t, secret_key]
digest = ::Digest::MD5.hexdigest(hashed.join(":"))
::Base64.encode64("#{t}:#{digest}").gsub("\n", '')
ActiveSupport::Base64.encode64("#{t}:#{digest}").gsub("\n", '')
end
# Might want a shorter timeout depending on whether the request
@@ -298,7 +288,7 @@ module ActionController
# allow a user to use new nonce without prompting user again for their
# username and password.
def validate_nonce(secret_key, request, value, seconds_to_timeout=5*60)
t = ::Base64.decode64(value).split(":").first.to_i
t = ActiveSupport::Base64.decode64(value).split(":").first.to_i
nonce(secret_key, t) == value && (t - Time.now.to_i).abs <= seconds_to_timeout
end
@@ -383,6 +373,7 @@ module ActionController
#
# RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
module Token
extend self
module ControllerMethods
@@ -403,7 +394,7 @@ module ActionController
# the present token and options.
#
# controller - ActionController::Base instance for the current request.
# login_procedure - Proc to call if a token is present. The Proc should
# login_procedure - Proc to call if a token is present. The Proc should
# take 2 arguments:
# authenticate(controller) { |token, options| ... }
#
@@ -411,29 +402,30 @@ module ActionController
# Returns nil if no token is found.
def authenticate(controller, &login_procedure)
token, options = token_and_options(controller.request)
unless token.blank?
if !token.blank?
login_procedure.call(token, options)
end
end
# Parses the token and options out of the token authorization header. If
# Parses the token and options out of the token authorization header. If
# the header looks like this:
# Authorization: Token token="abc", nonce="def"
# Then the returned token is "abc", and the options is {:nonce => "def"}
#
# request - ActionDispatch::Request instance with the current headers.
# request - ActionController::Request instance with the current headers.
#
# Returns an Array of [String, Hash] if a token is present.
# Returns nil if no token is found.
def token_and_options(request)
if request.authorization.to_s[/^Token (.*)/]
values = Hash[$1.split(',').map do |value|
value.strip! # remove any spaces between commas and values
key, value = value.split(/\=\"?/) # split key=value pairs
value.chomp!('"') # chomp trailing " in value
value.gsub!(/\\\"/, '"') # unescape remaining quotes
[key, value]
end]
if header = request.authorization.to_s[/^Token (.*)/]
values = $1.split(',').
inject({}) do |memo, value|
value.strip! # remove any spaces between commas and values
key, value = value.split(/\=\"?/) # split key=value pairs
value.chomp!('"') # chomp trailing " in value
value.gsub!(/\\\"/, '"') # unescape remaining quotes
memo.update(key => value)
end
[values.delete("token"), values.with_indifferent_access]
end
end
@@ -445,8 +437,9 @@ module ActionController
#
# Returns String.
def encode_credentials(token, options = {})
values = ["token=#{token.to_s.inspect}"] + options.map do |key, value|
"#{key}=#{value.to_s.inspect}"
values = ["token=#{token.to_s.inspect}"]
options.each do |key, value|
values << "#{key}=#{value.to_s.inspect}"
end
"Token #{values * ", "}"
end
@@ -462,5 +455,6 @@ module ActionController
controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized
end
end
end
end

View File

@@ -1,19 +1,21 @@
module ActionController
module ImplicitRender
def send_action(method, *args)
def send_action(*)
ret = super
default_render unless response_body
ret
end
def default_render(*args)
render(*args)
def default_render
render
end
def method_for_action(action_name)
super || if template_exists?(action_name.to_s, _prefixes)
"default_render"
super || begin
if template_exists?(action_name.to_s, _prefix)
"default_render"
end
end
end
end
end
end

View File

@@ -14,12 +14,12 @@ module ActionController
attr_internal :view_runtime
def process_action(*args)
def process_action(action, *args)
raw_payload = {
:controller => self.class.name,
:action => self.action_name,
:params => request.filtered_parameters,
:format => request.format.try(:ref),
:formats => request.formats.map(&:to_sym),
:method => request.method,
:path => (request.fullpath rescue "unknown")
}
@@ -58,18 +58,13 @@ module ActionController
def redirect_to(*args)
ActiveSupport::Notifications.instrument("redirect_to.action_controller") do |payload|
result = super
payload[:status] = response.status
payload[:location] = response.location
payload[:status] = self.status
payload[:location] = self.location
result
end
end
private
# A hook invoked everytime a before callback is halted.
def halted_callback_hook(filter)
ActiveSupport::Notifications.instrument("halted_callback.action_controller", :filter => filter)
end
protected
# A hook which allows you to clean up any time taken into account in
# views wrongly, like database querying time.
@@ -83,7 +78,7 @@ module ActionController
yield
end
# Every time after an action is processed, this method is invoked
# Everytime after an action is processed, this method is invoked
# with the payload, so you can add more information.
# :api: plugin
def append_info_to_payload(payload) #:nodoc:
@@ -102,4 +97,4 @@ module ActionController
end
end
end
end
end

View File

@@ -1,13 +1,10 @@
require 'abstract_controller/collector'
require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/object/inclusion'
module ActionController #:nodoc:
module MimeResponds
module MimeResponds #:nodoc:
extend ActiveSupport::Concern
include ActionController::ImplicitRender
included do
class_attribute :responder, :mimes_for_respond_to
self.responder = ActionController::Responder
@@ -35,15 +32,15 @@ module ActionController #:nodoc:
# and all actions except <tt>:edit</tt> respond to <tt>:xml</tt> and
# <tt>:json</tt>.
#
# respond_to :json, :only => :create
# respond_to :rjs, :only => :create
#
# This specifies that the <tt>:create</tt> action and no other responds
# to <tt>:json</tt>.
# to <tt>:rjs</tt>.
def respond_to(*mimes)
options = mimes.extract_options!
only_actions = Array(options.delete(:only)).map(&:to_s)
except_actions = Array(options.delete(:except)).map(&:to_s)
only_actions = Array(options.delete(:only))
except_actions = Array(options.delete(:except))
new = mimes_for_respond_to.dup
mimes.each do |mime|
@@ -66,13 +63,13 @@ module ActionController #:nodoc:
# might look something like this:
#
# def index
# @people = Person.all
# @people = Person.find(:all)
# end
#
# Here's the same action, with web-service support baked in:
#
# def index
# @people = Person.all
# @people = Person.find(:all)
#
# respond_to do |format|
# format.html
@@ -108,8 +105,8 @@ module ActionController #:nodoc:
# end
# end
#
# If the client wants HTML, we just redirect them back to the person list. If they want JavaScript,
# then it is an Ajax request and we render the JavaScript template associated with this action.
# If the client wants HTML, we just redirect them back to the person list. If they want Javascript
# (format.js), then it is an RJS request and we render the RJS template associated with this action.
# Lastly, if the client wants XML, we render the created person as XML, but with a twist: we also
# include the person's company in the rendered XML, so you get something like this:
#
@@ -158,7 +155,7 @@ module ActionController #:nodoc:
# Respond to also allows you to specify a common block for different formats by using any:
#
# def index
# @people = Person.all
# @people = Person.find(:all)
#
# respond_to do |format|
# format.html
@@ -181,8 +178,8 @@ module ActionController #:nodoc:
# respond_to :html, :xml, :json
#
# def index
# @people = Person.all
# respond_with(@people)
# @people = Person.find(:all)
# respond_with(@person)
# end
# end
#
@@ -191,9 +188,8 @@ module ActionController #:nodoc:
def respond_to(*mimes, &block)
raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given?
if collector = retrieve_collector_from_mimes(mimes, &block)
response = collector.response
response ? response.call : default_render({})
if response = retrieve_response_from_mimes(mimes, &block)
response.call
end
end
@@ -212,8 +208,8 @@ module ActionController #:nodoc:
# It also accepts a block to be given. It's used to overwrite a default
# response:
#
# def create
# @user = User.new(params[:user])
# def destroy
# @user = User.find(params[:id])
# flash[:notice] = "User was successfully created." if @user.save
#
# respond_with(@user) do |format|
@@ -226,16 +222,13 @@ module ActionController #:nodoc:
# is quite simple (it just needs to respond to call), you can even give
# a proc to it.
#
# In order to use respond_with, first you need to declare the formats your
# controller responds to in the class level with a call to <tt>respond_to</tt>.
#
def respond_with(*resources, &block)
raise "In order to use respond_with, first you need to declare the formats your " <<
"controller responds to in the class level" if self.class.mimes_for_respond_to.empty?
if collector = retrieve_collector_from_mimes(&block)
if response = retrieve_response_from_mimes(&block)
options = resources.size == 1 ? {} : resources.extract_options!
options[:default_response] = collector.response
options.merge!(:default_response => response)
(options.delete(:responder) || self.class.responder).call(self, resources, options)
end
end
@@ -246,15 +239,15 @@ module ActionController #:nodoc:
# current action.
#
def collect_mimes_from_class_level #:nodoc:
action = action_name.to_s
action = action_name.to_sym
self.class.mimes_for_respond_to.keys.select do |mime|
config = self.class.mimes_for_respond_to[mime]
if config[:except]
!action.in?(config[:except])
!config[:except].include?(action)
elsif config[:only]
action.in?(config[:only])
config[:only].include?(action)
else
true
end
@@ -264,17 +257,16 @@ module ActionController #:nodoc:
# Collects mimes and return the response for the negotiated format. Returns
# nil if :not_acceptable was sent to the client.
#
def retrieve_collector_from_mimes(mimes=nil, &block) #:nodoc:
def retrieve_response_from_mimes(mimes=nil, &block)
collector = Collector.new { default_render }
mimes ||= collect_mimes_from_class_level
collector = Collector.new(mimes)
mimes.each { |mime| collector.send(mime) }
block.call(collector) if block_given?
format = collector.negotiate_format(request)
if format
if format = request.negotiate_mime(collector.order)
self.content_type ||= format.to_s
lookup_context.formats = [format.to_sym]
lookup_context.rendered_format = lookup_context.formats.first
collector
lookup_context.freeze_formats([format.to_sym])
collector.response_for(format)
else
head :not_acceptable
nil
@@ -283,11 +275,10 @@ module ActionController #:nodoc:
class Collector #:nodoc:
include AbstractController::Collector
attr_accessor :order, :format
attr_accessor :order
def initialize(mimes)
@order, @responses = [], {}
mimes.each { |mime| send(mime) }
def initialize(&block)
@order, @responses, @default_response = [], {}, block
end
def any(*args, &block)
@@ -300,17 +291,13 @@ module ActionController #:nodoc:
alias :all :any
def custom(mime_type, &block)
mime_type = Mime::Type.lookup(mime_type.to_s) unless mime_type.is_a?(Mime::Type)
mime_type = mime_type.is_a?(Mime::Type) ? mime_type : Mime::Type.lookup(mime_type.to_s)
@order << mime_type
@responses[mime_type] ||= block
end
def response
@responses[format] || @responses[Mime::ALL]
end
def negotiate_format(request)
@format = request.negotiate_mime(order)
def response_for(mime)
@responses[mime] || @responses[Mime::ALL] || @default_response
end
end
end

View File

@@ -1,240 +0,0 @@
require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/module/anonymous'
require 'action_dispatch/http/mime_types'
module ActionController
# Wraps the parameters hash into a nested hash. This will allow clients to submit
# POST requests without having to specify any root elements.
#
# This functionality is enabled in +config/initializers/wrap_parameters.rb+
# and can be customized. If you are upgrading to \Rails 3.1, this file will
# need to be created for the functionality to be enabled.
#
# You could also turn it on per controller by setting the format array to
# a non-empty array:
#
# class UsersController < ApplicationController
# wrap_parameters :format => [:json, :xml]
# end
#
# If you enable +ParamsWrapper+ for +:json+ format, instead of having to
# send JSON parameters like this:
#
# {"user": {"name": "Konata"}}
#
# You can send parameters like this:
#
# {"name": "Konata"}
#
# And it will be wrapped into a nested hash with the key name matching the
# controller's name. For example, if you're posting to +UsersController+,
# your new +params+ hash will look like this:
#
# {"name" => "Konata", "user" => {"name" => "Konata"}}
#
# You can also specify the key in which the parameters should be wrapped to,
# and also the list of attributes it should wrap by using either +:include+ or
# +:exclude+ options like this:
#
# class UsersController < ApplicationController
# wrap_parameters :person, :include => [:username, :password]
# end
#
# On ActiveRecord models with no +:include+ or +:exclude+ option set,
# if attr_accessible is set on that model, it will only wrap the accessible
# parameters, else it will only wrap the parameters returned by the class
# method attribute_names.
#
# If you're going to pass the parameters to an +ActiveModel+ object (such as
# +User.new(params[:user])+), you might consider passing the model class to
# the method instead. The +ParamsWrapper+ will actually try to determine the
# list of attribute names from the model and only wrap those attributes:
#
# class UsersController < ApplicationController
# wrap_parameters Person
# end
#
# You still could pass +:include+ and +:exclude+ to set the list of attributes
# you want to wrap.
#
# By default, if you don't specify the key in which the parameters would be
# wrapped to, +ParamsWrapper+ will actually try to determine if there's
# a model related to it or not. This controller, for example:
#
# class Admin::UsersController < ApplicationController
# end
#
# will try to check if +Admin::User+ or +User+ model exists, and use it to
# determine the wrapper key respectively. If both models don't exist,
# it will then fallback to use +user+ as the key.
module ParamsWrapper
extend ActiveSupport::Concern
EXCLUDE_PARAMETERS = %w(authenticity_token _method utf8)
included do
class_attribute :_wrapper_options
self._wrapper_options = { :format => [] }
end
module ClassMethods
# Sets the name of the wrapper key, or the model which +ParamsWrapper+
# would use to determine the attribute names from.
#
# ==== Examples
# wrap_parameters :format => :xml
# # enables the parameter wrapper for XML format
#
# wrap_parameters :person
# # wraps parameters into +params[:person]+ hash
#
# wrap_parameters Person
# # wraps parameters by determining the wrapper key from Person class
# (+person+, in this case) and the list of attribute names
#
# wrap_parameters :include => [:username, :title]
# # wraps only +:username+ and +:title+ attributes from parameters.
#
# wrap_parameters false
# # disables parameters wrapping for this controller altogether.
#
# ==== Options
# * <tt>:format</tt> - The list of formats in which the parameters wrapper
# will be enabled.
# * <tt>:include</tt> - The list of attribute names which parameters wrapper
# will wrap into a nested hash.
# * <tt>:exclude</tt> - The list of attribute names which parameters wrapper
# will exclude from a nested hash.
def wrap_parameters(name_or_model_or_options, options = {})
model = nil
case name_or_model_or_options
when Hash
options = name_or_model_or_options
when false
options = options.merge(:format => [])
when Symbol, String
options = options.merge(:name => name_or_model_or_options)
else
model = name_or_model_or_options
end
_set_wrapper_defaults(_wrapper_options.slice(:format).merge(options), model)
end
# Sets the default wrapper key or model which will be used to determine
# wrapper key and attribute names. Will be called automatically when the
# module is inherited.
def inherited(klass)
if klass._wrapper_options[:format].present?
klass._set_wrapper_defaults(klass._wrapper_options.slice(:format))
end
super
end
protected
# Determine the wrapper model from the controller's name. By convention,
# this could be done by trying to find the defined model that has the
# same singularize name as the controller. For example, +UsersController+
# will try to find if the +User+ model exists.
#
# This method also does namespace lookup. Foo::Bar::UsersController will
# try to find Foo::Bar::User, Foo::User and finally User.
def _default_wrap_model #:nodoc:
return nil if self.anonymous?
model_name = self.name.sub(/Controller$/, '').classify
begin
if model_klass = model_name.safe_constantize
model_klass
else
namespaces = model_name.split("::")
namespaces.delete_at(-2)
break if namespaces.last == model_name
model_name = namespaces.join("::")
end
end until model_klass
model_klass
end
def _set_wrapper_defaults(options, model=nil)
options = options.dup
unless options[:include] || options[:exclude]
model ||= _default_wrap_model
role = options.has_key?(:as) ? options[:as] : :default
if model.respond_to?(:accessible_attributes) && model.accessible_attributes(role).present?
options[:include] = model.accessible_attributes(role).to_a
elsif model.respond_to?(:attribute_names) && model.attribute_names.present?
options[:include] = model.attribute_names
end
end
unless options[:name] || self.anonymous?
model ||= _default_wrap_model
options[:name] = model ? model.to_s.demodulize.underscore :
controller_name.singularize
end
options[:include] = Array.wrap(options[:include]).collect(&:to_s) if options[:include]
options[:exclude] = Array.wrap(options[:exclude]).collect(&:to_s) if options[:exclude]
options[:format] = Array.wrap(options[:format])
self._wrapper_options = options
end
end
# Performs parameters wrapping upon the request. Will be called automatically
# by the metal call stack.
def process_action(*args)
if _wrapper_enabled?
wrapped_hash = _wrap_parameters request.request_parameters
wrapped_keys = request.request_parameters.keys
wrapped_filtered_hash = _wrap_parameters request.filtered_parameters.slice(*wrapped_keys)
# This will make the wrapped hash accessible from controller and view
request.parameters.merge! wrapped_hash
request.request_parameters.merge! wrapped_hash
# This will make the wrapped hash displayed in the log file
request.filtered_parameters.merge! wrapped_filtered_hash
end
super
end
private
# Returns the wrapper key which will use to stored wrapped parameters.
def _wrapper_key
_wrapper_options[:name]
end
# Returns the list of enabled formats.
def _wrapper_formats
_wrapper_options[:format]
end
# Returns the list of parameters which will be selected for wrapped.
def _wrap_parameters(parameters)
value = if include_only = _wrapper_options[:include]
parameters.slice(*include_only)
else
exclude = _wrapper_options[:exclude] || []
parameters.except(*(exclude + EXCLUDE_PARAMETERS))
end
{ _wrapper_key => value }
end
# Checks if we should perform parameters wrapping.
def _wrapper_enabled?
ref = request.content_mime_type.try(:ref)
_wrapper_formats.include?(ref) && _wrapper_key && !request.request_parameters[_wrapper_key]
end
end
end

Some files were not shown because too many files have changed in this diff Show More