mirror of
https://github.com/github/rails.git
synced 2026-01-12 08:08:31 -05:00
Compare commits
202 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5988aaa50e | ||
|
|
025f895415 | ||
|
|
e9e86fd134 | ||
|
|
81b94c2f10 | ||
|
|
a3dafb07ec | ||
|
|
cc99f3fc18 | ||
|
|
d25ae9b6e1 | ||
|
|
517628d028 | ||
|
|
5d0fd52305 | ||
|
|
aa30fc7914 | ||
|
|
5f114177ce | ||
|
|
143cc0ec2f | ||
|
|
5385859dcf | ||
|
|
2d5bf4bbed | ||
|
|
2b6954aa8a | ||
|
|
68849e3239 | ||
|
|
debaf20803 | ||
|
|
8f84165cb4 | ||
|
|
18857ca2cb | ||
|
|
06c7584fba | ||
|
|
dd605e937f | ||
|
|
d12bcdac9d | ||
|
|
52923c9b55 | ||
|
|
1a7ce06e90 | ||
|
|
34603e7faf | ||
|
|
f7d25950f0 | ||
|
|
0ac6b5077f | ||
|
|
fd2b14c046 | ||
|
|
86f78cd8b6 | ||
|
|
398c1a504c | ||
|
|
5bf40f7b79 | ||
|
|
e76eae612f | ||
|
|
25c3ee407d | ||
|
|
de9ccd8848 | ||
|
|
9cc2e0f2f4 | ||
|
|
1696c1f68d | ||
|
|
2c1d0e2979 | ||
|
|
f1a4c44726 | ||
|
|
382547dcbe | ||
|
|
376dcb8e02 | ||
|
|
ab3f6bcfaa | ||
|
|
04383b974d | ||
|
|
fde811e2f6 | ||
|
|
83a21f75cf | ||
|
|
e9a7b233f6 | ||
|
|
21e4825596 | ||
|
|
622d70a11e | ||
|
|
c26cca3f45 | ||
|
|
b0303e1ac2 | ||
|
|
bdd09f50f8 | ||
|
|
6dc5756d39 | ||
|
|
0120b226ba | ||
|
|
b6af22ec82 | ||
|
|
4870becaeb | ||
|
|
a68d1d35f8 | ||
|
|
a4e70d3e91 | ||
|
|
ba29222851 | ||
|
|
0ff4ede7ca | ||
|
|
7269ee2da9 | ||
|
|
59be73a1e7 | ||
|
|
ce8e54e236 | ||
|
|
155dcff431 | ||
|
|
df27fb873c | ||
|
|
4aa93358fa | ||
|
|
3054a742df | ||
|
|
1fb2f21d1a | ||
|
|
da8a896d86 | ||
|
|
debd9ea2ce | ||
|
|
8ec9f4d2a0 | ||
|
|
4dcdf0834e | ||
|
|
a451fd1fbf | ||
|
|
c7e2b03424 | ||
|
|
6ccbef5862 | ||
|
|
498bca8ae8 | ||
|
|
c3c7648d20 | ||
|
|
fe2e51b047 | ||
|
|
67cda1f54e | ||
|
|
cda3d89983 | ||
|
|
0ae462a82d | ||
|
|
d5ca9a5814 | ||
|
|
72d556a391 | ||
|
|
34bc074441 | ||
|
|
6df67f5607 | ||
|
|
590b192e02 | ||
|
|
67ac59afc8 | ||
|
|
3d5fb40bb0 | ||
|
|
0c483d0c8d | ||
|
|
8804b7aeb7 | ||
|
|
2876efb784 | ||
|
|
762fc5447f | ||
|
|
bd261ffd1f | ||
|
|
ffb17e89ef | ||
|
|
2a08c4547a | ||
|
|
2b68762f5a | ||
|
|
de3ec6c008 | ||
|
|
2890b9648e | ||
|
|
98a0440a56 | ||
|
|
f09c8c4529 | ||
|
|
25d7ea8ad2 | ||
|
|
91cd8890c7 | ||
|
|
87ef365a49 | ||
|
|
d6c28bfaed | ||
|
|
b2ae346484 | ||
|
|
fb6cd55de7 | ||
|
|
c4d4660de3 | ||
|
|
205ae50d3f | ||
|
|
5b8bfc40e0 | ||
|
|
f83eedd440 | ||
|
|
691c439129 | ||
|
|
8f3e81ed53 | ||
|
|
fd8ee0a253 | ||
|
|
509c920d35 | ||
|
|
cef81e71eb | ||
|
|
3ee809655e | ||
|
|
c3cbd6b806 | ||
|
|
fe1e771222 | ||
|
|
694957ce5a | ||
|
|
12949bbc13 | ||
|
|
82e5ff7c6e | ||
|
|
783c16bd61 | ||
|
|
34a3d04af1 | ||
|
|
766ca17c91 | ||
|
|
ffa2c5fda5 | ||
|
|
87ecb782e6 | ||
|
|
2043513f4c | ||
|
|
ef6c3c4289 | ||
|
|
af43e87f38 | ||
|
|
f2fd22c2d4 | ||
|
|
17921bafcb | ||
|
|
36b3cb2c36 | ||
|
|
b93e4692b2 | ||
|
|
30e5436a3e | ||
|
|
9ba96771c3 | ||
|
|
97d9dca26f | ||
|
|
2a70f6f0a2 | ||
|
|
1e532f6606 | ||
|
|
fb60a469c0 | ||
|
|
ac2295137c | ||
|
|
acfe119cb5 | ||
|
|
004a28de81 | ||
|
|
0497868531 | ||
|
|
23569d83b2 | ||
|
|
bef626e2b1 | ||
|
|
b7f094e65e | ||
|
|
6baf9489d1 | ||
|
|
af33784698 | ||
|
|
a5631a5674 | ||
|
|
629b2ac36c | ||
|
|
dd1dc5e819 | ||
|
|
b8ff216f49 | ||
|
|
924f5cdb61 | ||
|
|
86bd0da7d0 | ||
|
|
35240ba66e | ||
|
|
b8a5d398b9 | ||
|
|
85c45051be | ||
|
|
f7c94e977b | ||
|
|
69ada0e26e | ||
|
|
9eaad14e8e | ||
|
|
9f8c805f5d | ||
|
|
46b845e784 | ||
|
|
118764e47d | ||
|
|
bcd50f1a37 | ||
|
|
5aced86de6 | ||
|
|
792780a80c | ||
|
|
5e677b67b5 | ||
|
|
dfa070aab9 | ||
|
|
ba086a4fc0 | ||
|
|
cc299d1b94 | ||
|
|
cbffafb497 | ||
|
|
84668af330 | ||
|
|
013004b592 | ||
|
|
5f5d8c224b | ||
|
|
5887b183ce | ||
|
|
320875ad77 | ||
|
|
4aa358dd86 | ||
|
|
6439d0cd3e | ||
|
|
7953eb170d | ||
|
|
5350fda95d | ||
|
|
5fac326020 | ||
|
|
17e445813b | ||
|
|
a2edd4381e | ||
|
|
2029b8a8f5 | ||
|
|
53c49036ea | ||
|
|
855e0f6f09 | ||
|
|
e4e1d2afa3 | ||
|
|
526afd3ae2 | ||
|
|
31b901aa65 | ||
|
|
a746e39584 | ||
|
|
f4d88039fd | ||
|
|
9f26164d37 | ||
|
|
c7f28e01c8 | ||
|
|
3311953d3f | ||
|
|
ce0653b1c6 | ||
|
|
229e197ac7 | ||
|
|
503c7c0afd | ||
|
|
8e01efee02 | ||
|
|
e09f224a5c | ||
|
|
6eb941ee6c | ||
|
|
7e8dd0322c | ||
|
|
159411f580 | ||
|
|
746cfb3ded | ||
|
|
2227a178ee |
@@ -1,4 +1,4 @@
|
||||
*SVN*
|
||||
*1.3.0* (January 16th, 2007)
|
||||
|
||||
* Make mime version default to 1.0. closes #2323 [ror@andreas-s.net]
|
||||
|
||||
@@ -14,8 +14,6 @@
|
||||
|
||||
* 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.]
|
||||
@@ -24,8 +22,30 @@
|
||||
|
||||
* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.]
|
||||
|
||||
|
||||
*1.2.5* (August 10th, 2006)
|
||||
|
||||
* Depend on Action Pack 1.12.5
|
||||
|
||||
|
||||
*1.2.4* (August 8th, 2006)
|
||||
|
||||
* Backport of documentation enhancements. [Kevin Clark, Marcel Molina Jr]
|
||||
|
||||
* Correct spurious documentation example code which results in a SyntaxError. [Marcel Molina Jr.]
|
||||
|
||||
* Mailer template root applies to a class and its subclasses rather than acting globally. #5555 [somekool@gmail.com]
|
||||
|
||||
|
||||
*1.2.3* (June 29th, 2006)
|
||||
|
||||
* Depend on Action Pack 1.12.3
|
||||
|
||||
|
||||
*1.2.2* (June 27th, 2006)
|
||||
|
||||
* Depend on Action Pack 1.12.2
|
||||
|
||||
|
||||
*1.2.1* (April 6th, 2006)
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ spec = Gem::Specification.new do |s|
|
||||
s.rubyforge_project = "actionmailer"
|
||||
s.homepage = "http://www.rubyonrails.org"
|
||||
|
||||
s.add_dependency('actionpack', '= 1.12.5' + PKG_BUILD)
|
||||
s.add_dependency('actionpack', '= 1.13.0' + PKG_BUILD)
|
||||
|
||||
s.has_rdoc = true
|
||||
s.requirements << 'none'
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
module ActionMailer
|
||||
module VERSION #:nodoc:
|
||||
MAJOR = 1
|
||||
MINOR = 2
|
||||
TINY = 5
|
||||
MINOR = 3
|
||||
TINY = 0
|
||||
|
||||
STRING = [MAJOR, MINOR, TINY].join('.')
|
||||
end
|
||||
|
||||
@@ -1,4 +1,110 @@
|
||||
*SVN*
|
||||
*1.13.0* (January 16th, 2007)
|
||||
|
||||
* Modernize cookie testing code, and increase coverage (Heckle++) #7101 [Kevin Clark]
|
||||
|
||||
* Heckling ActionController::Resources::Resource revealed that set_prefixes didn't break when :name_prefix was munged. #7081 [Kevin Clark]
|
||||
|
||||
* Update to Prototype 1.5.0. [Sam Stephenson]
|
||||
|
||||
* Allow exempt_from_layout :rhtml. #6742, #7026 [dcmanges, Squeegy]
|
||||
|
||||
* Fix parsing of array[] CGI parameters so extra empty values aren't included. #6252 [Nicholas Seckar, aiwilliams, brentrowland]
|
||||
|
||||
* link_to_unless_current works with full URLs as well as paths. #6891 [Jarkko Laine, manfred, idrifter]
|
||||
|
||||
* Fix HTML::Node to output double quotes instead of single quotes. Closes #6845 [mitreandy]
|
||||
|
||||
* Fix no method error with error_messages_on. Closes #6935 [nik.wakelin Koz]
|
||||
|
||||
* Slight doc tweak to the ActionView::Helpers::PrototypeHelper#replace docs. Closes #6922 [Steven Bristol]
|
||||
|
||||
* Slight doc tweak to #prepend_filter. Closes #6493 [Jeremy Voorhis]
|
||||
|
||||
* Add more extensive documentation to the AssetTagHelper. Closes #6452 [Bob Silva]
|
||||
|
||||
* Clean up multiple calls to #stringify_keys in TagHelper, add better documentation and testing for TagHelper. Closes #6394 [Bob Silva]
|
||||
|
||||
* [DOCS] fix reference to ActionController::Macros::AutoComplete for #text_field_with_auto_complete. Closes #2578 [Jan Prill]
|
||||
|
||||
* Make sure html_document is reset between integration test requests. [ctm]
|
||||
|
||||
* Set session to an empty hash if :new_session => false and no session cookie or param is present. CGI::Session was raising an unrescued ArgumentError. [Josh Susser]
|
||||
|
||||
* Fix assert_redirected_to bug where redirecting from a nested to to a top-level controller incorrectly added the current controller's nesting. Closes #6128. [Rick Olson]
|
||||
|
||||
* Ensure render :json => ... skips the layout. #6808 [Josh Peek]
|
||||
|
||||
* Silence log_error deprecation warnings from inspecting deprecated instance variables. [Nate Wiger]
|
||||
|
||||
* Only cache GET requests with a 200 OK response. #6514, #6743 [RSL, anamba]
|
||||
|
||||
* Correctly report which filter halted the chain. #6699 [Martin Emde]
|
||||
|
||||
* respond_to recognizes JSON. render :json => @person.to_json automatically sets the content type and takes a :callback option to specify a client-side function to call using the rendered JSON as an argument. #4185 [Scott Raymond, eventualbuddha]
|
||||
# application/json response with body 'Element.show({:name: "David"})'
|
||||
respond_to do |format|
|
||||
format.json { render :json => { :name => "David" }.to_json, :callback => 'Element.show' }
|
||||
end
|
||||
|
||||
* Makes :discard_year work without breaking multi-attribute parsing in AR. #1260, #3800 [sean@ardismg.com, jmartin@desertflood.com, stephen@touset.org, Bob Silva]
|
||||
|
||||
* Adds html id attribute to date helper elements. #1050, #1382 [mortonda@dgrmm.net, David North, Bob Silva]
|
||||
|
||||
* Add :index and @auto_index capability to model driven date/time selects. #847, #2655 [moriq, Doug Fales, Bob Silva]
|
||||
|
||||
* Add :order to datetime_select, select_datetime, and select_date. #1427 [Timothee Peignier, patrick@lenz.sh, Bob Silva]
|
||||
|
||||
* Added time_select to work with time values in models. Update scaffolding. #2489, #2833 [Justin Palmer, Andre Caum, Bob Silva]
|
||||
|
||||
* Added :include_seconds to select_datetime, datetime_select and time_select. #2998 [csn, Bob Silva]
|
||||
|
||||
* All date/datetime selects can now accept an array of month names with :use_month_names. Allows for localization. #363 [tomasj, Bob Silva]
|
||||
|
||||
* Adds :time_separator to select_time and :date_separator to select_datetime. Preserves BC. #3811 [Bob Silva]
|
||||
|
||||
* @response.redirect_url works with 201 Created responses: just return headers['Location'] rather than checking the response status. [Jeremy Kemper]
|
||||
|
||||
* Fixed that HEAD should return the proper Content-Length header (that is, actually use @body.size, not just 0) [DHH]
|
||||
|
||||
* Added GET-masquarading for HEAD, so request.method will return :get even for HEADs. This will help anyone relying on case request.method to automatically work with HEAD and map.resources will also allow HEADs to all GET actions. Rails automatically throws away the response content in a reply to HEAD, so you don't even need to worry about that. If you, for whatever reason, still need to distinguish between GET and HEAD in some edge case, you can use Request#head? and even Request.headers["REQUEST_METHOD"] for get the "real" answer. Closes #6694 [DHH]
|
||||
|
||||
|
||||
*1.13.0 RC1* (r5619, November 22nd, 2006)
|
||||
|
||||
* Update Routing to complain when :controller is not specified by a route. Closes #6669. [Nicholas Seckar]
|
||||
|
||||
* Ensure render_to_string cleans up after itself when an exception is raised. #6658 [rsanheim]
|
||||
|
||||
* Update to Prototype and script.aculo.us [5579]. [Sam Stephenson, Thomas Fuchs]
|
||||
|
||||
* simple_format helper doesn't choke on nil. #6644 [jerry426]
|
||||
|
||||
* Reuse named route helper module between Routing reloads. Use remove_method to delete named route methods after each load. Since the module is never collected, this fixes a significant memory leak. [Nicholas Seckar]
|
||||
|
||||
* Deprecate standalone components. [Jeremy Kemper]
|
||||
|
||||
* Always clear model associations from session. #4795 [sd@notso.net, andylien@gmail.com]
|
||||
|
||||
* Remove JavaScriptLiteral in favor of ActiveSupport::JSON::Variable. [Sam Stephenson]
|
||||
|
||||
* Sync ActionController::StatusCodes::STATUS_CODES with http://www.iana.org/assignments/http-status-codes. #6586 [dkubb]
|
||||
|
||||
* Multipart form values may have a content type without being treated as uploaded files if they do not provide a filename. #6401 [Andreas Schwarz, Jeremy Kemper]
|
||||
|
||||
* assert_response supports symbolic status codes. #6569 [Kevin Clark]
|
||||
assert_response :ok
|
||||
assert_response :not_found
|
||||
assert_response :forbidden
|
||||
|
||||
* Cache parsed query parameters. #6559 [Stefan Kaes]
|
||||
|
||||
* Deprecate JavaScriptHelper#update_element_function, which is superseeded by RJS [Thomas Fuchs]
|
||||
|
||||
* Fix invalid test fixture exposed by stricter Ruby 1.8.5 multipart parsing. #6524 [Bob Silva]
|
||||
|
||||
* Set ActionView::Base.default_form_builder once rather than passing the :builder option to every form or overriding the form helper methods. [Jeremy Kemper]
|
||||
|
||||
* Deprecate expire_matched_fragments. Use expire_fragment instead. #6535 [Bob Silva]
|
||||
|
||||
* Deprecate start_form_tag and end_form_tag. Use form_tag / '</form>' from now on. [Rick]
|
||||
|
||||
@@ -35,8 +141,6 @@
|
||||
|
||||
* Fix double-escaped entities, such as &amp;, &#123;, etc. [Rick]
|
||||
|
||||
* Fix deprecation warnings when rendering the template error template. [Nicholas Seckar]
|
||||
|
||||
* Fix routing to correctly determine when generation fails. Closes #6300. [psross].
|
||||
|
||||
* Fix broken assert_generates when extra keys are being checked. [Jamis Buck]
|
||||
@@ -47,10 +151,6 @@
|
||||
|
||||
* Use String#chars in TextHelper::excerpt. Closes #6386 [Manfred Stienstra]
|
||||
|
||||
* Install named routes into ActionView::Base instead of proxying them to the view via helper_method. Closes #5932. [Nicholas Seckar]
|
||||
|
||||
* Update to latest Prototype and script.aculo.us trunk versions [Thomas Fuchs]
|
||||
|
||||
* Fix relative URL root matching problems. [Mark Imbriaco]
|
||||
|
||||
* Fix filter skipping in controller subclasses. #5949, #6297, #6299 [Martin Emde]
|
||||
@@ -106,8 +206,6 @@
|
||||
|
||||
* Filters overhaul including meantime filter support using around filters + blocks. #5949 [Martin Emde, Roman Le Negrate, Stefan Kaes, Jeremy Kemper]
|
||||
|
||||
* Update RJS render tests. [sam]
|
||||
|
||||
* Update CGI process to allow sessions to contain namespaced models. Closes #4638. [dfelstead@site5.com]
|
||||
|
||||
* Fix routing to respect user provided requirements and defaults when assigning default routing options (such as :action => 'index'). Closes #5950. [Nicholas Seckar]
|
||||
@@ -133,12 +231,6 @@
|
||||
response.content_type = Mime::ATOM
|
||||
response.charset = "utf-8"
|
||||
|
||||
* Updated prototype.js to 1.5.0_rc1 with latest fixes. [Rick Olson]
|
||||
|
||||
- XPATH support
|
||||
- Make Form.getElements() return elements in the correct order
|
||||
- fix broken Form.serialize return
|
||||
|
||||
* Declare file extensions exempt from layouts. #6219 [brandon]
|
||||
Example: ActionController::Base.exempt_from_layout 'rpdf'
|
||||
|
||||
@@ -163,8 +255,6 @@
|
||||
|
||||
* Fix assert_tag so that :content => "foo" does not match substrings, but only exact strings. Use :content => /foo/ to match substrings. #2799 [Eric Hodel]
|
||||
|
||||
* Add descriptive messages to the exceptions thrown by cgi_methods. #6091, #6103 [Nicholas Seckar, Bob Silva]
|
||||
|
||||
* Update JavaScriptGenerator#show/hide/toggle/remove to new Prototype syntax for multiple ids, #6068 [petermichaux@gmail.com]
|
||||
|
||||
* Update UrlWriter to support :only_path. [Nicholas Seckar, Dave Thomas]
|
||||
@@ -177,10 +267,6 @@
|
||||
|
||||
link_to("Hider", :class => "hider_link") { |p| p[:something].hide }
|
||||
|
||||
* Update to script.aculo.us 1.6.3 [Thomas Fuchs]
|
||||
|
||||
* Update to Prototype 1.5.0_rc1 [sam]
|
||||
|
||||
* Added access to nested attributes in RJS #4548 [richcollins@gmail.com]. Examples:
|
||||
|
||||
page['foo']['style'] # => $('foo').style;
|
||||
@@ -202,9 +288,6 @@
|
||||
|
||||
* Changed that uncaught exceptions raised any where in the application will cause RAILS_ROOT/public/500.html to be read and shown instead of just the static "Application error (Rails)" [DHH]
|
||||
|
||||
* Integration tests: thoroughly test ActionController::Integration::Session. #6022 [Kevin Clark]
|
||||
(tests skipped unless you `gem install mocha`)
|
||||
|
||||
* Added deprecation language for pagination which will become a plugin by Rails 2.0 [DHH]
|
||||
|
||||
* Added deprecation language for in_place_editor and auto_complete_field that both pieces will become plugins by Rails 2.0 [DHH]
|
||||
@@ -215,7 +298,7 @@
|
||||
|
||||
* radio_button_tag generates unique id attributes. #3353 [Bob Silva, somekool@gmail.com]
|
||||
|
||||
* strip_tags returns nil for a blank arg such as nil or "". #2229 [duncan@whomwah.com]
|
||||
* strip_tags passes through blank args such as nil or "". #2229, #6702 [duncan@whomwah.com, dharana]
|
||||
|
||||
* Cleanup assert_tag :children counting. #2181 [jamie@bravenet.com]
|
||||
|
||||
@@ -223,20 +306,12 @@
|
||||
|
||||
* Update sanitize text helper to strip plaintext tags, and <img src="javascript:bang">. [Rick Olson]
|
||||
|
||||
* Update routing documentation. Closes #6017 [Nathan Witmer]
|
||||
|
||||
* Add routing tests to assert that RoutingError is raised when conditions aren't met. Closes #6016 [Nathan Witmer]
|
||||
|
||||
* Deprecation: update docs. #5998 [jakob@mentalized.net, Kevin Clark]
|
||||
|
||||
* Make auto_link parse a greater subset of valid url formats. [Jamis Buck]
|
||||
|
||||
* Integration tests: headers beginning with X aren't excluded from the HTTP_ prefix, so X-Requested-With becomes HTTP_X_REQUESTED_WITH as expected. [Mike Clark]
|
||||
|
||||
* Tighten rescue clauses. #5985 [james@grayproductions.net]
|
||||
|
||||
* Fix send_data documentation typo. #5982 [brad@madriska.com]
|
||||
|
||||
* Switch to using FormEncodedPairParser for parsing request parameters. [Nicholas Seckar, DHH]
|
||||
|
||||
* respond_to .html now always renders #{action_name}.rhtml so that registered custom template handlers do not override it in priority. Custom mime types require a block and throw proper error now. [Tobias Luetke]
|
||||
@@ -245,12 +320,6 @@
|
||||
|
||||
* Add UrlWriter to allow writing urls from Mailers and scripts. [Nicholas Seckar]
|
||||
|
||||
* Clean up and run the Active Record integration tests by default. #5854 [kevin.clark@gmail.com, Jeremy Kemper]
|
||||
|
||||
* Correct example in cookies docs. #5832 [jessemerriman@warpmail.net]
|
||||
|
||||
* Updated to script.aculo.us 1.6.2 [Thomas Fuchs]
|
||||
|
||||
* Relax Routing's anchor pattern warning; it was preventing use of [^/] inside restrictions. [Nicholas Seckar]
|
||||
|
||||
* Add controller_paths variable to Routing. [Nicholas Seckar]
|
||||
@@ -261,8 +330,6 @@
|
||||
|
||||
* Invoke method_missing directly on hidden actions. Closes #3030. [Nicholas Seckar]
|
||||
|
||||
* Require Tempfile explicitly for TestUploadedFile due to changes in class auto loading. [Rick Olson]
|
||||
|
||||
* Add RoutingError exception when RouteSet fails to generate a path from a Named Route. [Rick Olson]
|
||||
|
||||
* Replace Reloadable with Reloadable::Deprecated. [Nicholas Seckar]
|
||||
@@ -277,8 +344,6 @@
|
||||
|
||||
* Added months and years to the resolution of DateHelper#distance_of_time_in_words, such that "60 days ago" becomes "2 months ago" #5611 [pjhyett@gmail.com]
|
||||
|
||||
* Short documentation to mention use of Mime::Type.register. #5710 [choonkeat@gmail.com]
|
||||
|
||||
* Make controller_path available as an instance method. #5724 [jmckible@gmail.com]
|
||||
|
||||
* Update query parser to support adjacent hashes. [Nicholas Seckar]
|
||||
@@ -287,10 +352,6 @@
|
||||
|
||||
* Restrict Request Method hacking with ?_method to POST requests. [Rick Olson]
|
||||
|
||||
* Fix bug when passing multiple options to SimplyRestful, like :new => { :preview => :get, :draft => :get }. [Rick Olson, Josh Susser, Lars Pind]
|
||||
|
||||
* Dup the options passed to map.resources so that multiple resources get the same options. [Rick Olson]
|
||||
|
||||
* Fixed the new_#{resource}_url route and added named route tests for Simply Restful. [Rick Olson]
|
||||
|
||||
* Added map.resources from the Simply Restful plugin [DHH]. Examples (the API has changed to use plurals!):
|
||||
@@ -318,14 +379,10 @@
|
||||
|
||||
* Provide support for decimal columns to form helpers. Closes #5672. [dave@pragprog.com]
|
||||
|
||||
* Update documentation for erb trim syntax. #5651 [matt@mattmargolis.net]
|
||||
|
||||
* Pass :id => nil or :class => nil to error_messages_for to supress that html attribute. #3586 [olivier_ansaldi@yahoo.com, sebastien@goetzilla.info]
|
||||
|
||||
* Reset @html_document between requests so assert_tag works. #4810 [jarkko@jlaine.net, easleydp@gmail.com]
|
||||
|
||||
* Update render :partial documentation. #5646 [matt@mattmargolis.net]
|
||||
|
||||
* Integration tests behave well with render_component. #4632 [edward.frederick@revolution.com, dev.rubyonrails@maxdunn.com]
|
||||
|
||||
* Added exception handling of missing layouts #5373 [chris@ozmm.org]
|
||||
@@ -360,8 +417,6 @@
|
||||
|
||||
* Make sure :id and friends are unescaped properly. #5275 [me@julik.nl]
|
||||
|
||||
* Fix documentation for with_routing to reflect new reality. #5281 [rramdas@gmail.com]
|
||||
|
||||
* Rewind readable CGI params so others may reread them (such as CGI::Session when passing the session id in a multipart form). #210 [mklame@atxeu.com, matthew@walker.wattle.id.au]
|
||||
|
||||
* Added Mime::TEXT (text/plain) and Mime::ICS (text/calendar) as new default types [DHH]
|
||||
@@ -425,8 +480,6 @@
|
||||
|
||||
* Fix NoMethodError when parsing params like &&. [Adam Greenfield]
|
||||
|
||||
* Fix flip flopped logic in docs for url_for's :only_path option. Closes #4998. [esad@esse.at]
|
||||
|
||||
* form.text_area handles the :size option just like the original text_area (:size => '60x10' becomes cols="60" rows="10"). [Jeremy Kemper]
|
||||
|
||||
* Excise ingrown code from FormOptionsHelper#options_for_select. #5008 [anonymous]
|
||||
@@ -435,43 +488,17 @@
|
||||
|
||||
map.connect '*path', :controller => 'files', :action => 'show'
|
||||
|
||||
* 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.]
|
||||
|
||||
* Use #flush between switching from #write to #syswrite. Closes #4907. [Blair Zajac <blair@orcaware.com>]
|
||||
|
||||
* Documentation fix: integration test scripts don't require integration_test. Closes #4914. [Frederick Ros <sl33p3r@free.fr>]
|
||||
|
||||
* ActionController::Base Summary documentation rewrite. Closes #4900. [kevin.clark@gmail.com]
|
||||
|
||||
* Fix text_helper.rb documentation rendering. Closes #4725. [Frederick Ros]
|
||||
|
||||
* Fixes bad rendering of JavaScriptMacrosHelper rdoc (closes #4910) [Frederick Ros]
|
||||
|
||||
* Allow error_messages_for to report errors for multiple objects, as well as support for customizing the name of the object in the error summary header. Closes #4186. [andrew@redlinesoftware.com, Marcel Molina Jr.]
|
||||
|
||||
error_messages_for :account, :user, :subscription, :object_name => :account
|
||||
|
||||
* Enhance documentation for setting headers in integration tests. Skip auto HTTP prepending when its already there. Closes #4079. [Rick Olson]
|
||||
|
||||
* Documentation for AbstractRequest. Closes #4895. [kevin.clark@gmail.com]
|
||||
|
||||
* Refactor various InstanceTag instance method to class methods. Closes #4800. [skaes@web.de]
|
||||
|
||||
* Remove all remaining references to @params in the documentation. [Marcel Molina Jr.]
|
||||
|
||||
* Add documentation for redirect_to :back's RedirectBackError exception. [Marcel Molina Jr.]
|
||||
|
||||
* Update layout and content_for documentation to use yield rather than magic @content_for instance variables. [Marcel Molina Jr.]
|
||||
|
||||
* Fix assert_redirected_to tests according to real-world usage. Also, don't fail if you add an extra :controller option: [Rick]
|
||||
|
||||
redirect_to :action => 'new'
|
||||
assert_redirected_to :controller => 'monkeys', :action => 'new'
|
||||
|
||||
* Cache CgiRequest#request_parameters so that multiple calls don't re-parse multipart data. [Rick]
|
||||
|
||||
* Diff compared routing options. Allow #assert_recognizes to take a second arg as a hash to specify optional request method [Rick]
|
||||
|
||||
assert_recognizes({:controller => 'users', :action => 'index'}, 'users')
|
||||
@@ -483,8 +510,6 @@
|
||||
|
||||
* Change link_to_function and button_to_function to (optionally) take an update_page block instead of a JavaScript string. Closes #4804. [zraii@comcast.net, Sam Stephenson]
|
||||
|
||||
* Fixed that remote_form_for can leave out the object parameter and default to the instance variable of the object_name, just like form_for [DHH]
|
||||
|
||||
* Modify routing so that you can say :require => { :method => :post } for a route, and the route will never be selected unless the request method is POST. Only works for route recognition, not for route generation. [Jamis Buck]
|
||||
|
||||
* Added :add_headers option to verify which merges a hash of name/value pairs into the response's headers hash if the prerequisites cannot be satisfied. [Sam Stephenson]
|
||||
@@ -492,7 +517,43 @@
|
||||
:render => { :status => 405, :text => "Must be post" },
|
||||
:add_headers => { "Allow" => "POST" }
|
||||
|
||||
* Added ActionController.filter_parameter_logging that makes it easy to remove passwords, credit card numbers, and other sensitive information from being logged when a request is handled #1897 [jeremye@bsa.ca.gov]
|
||||
|
||||
*1.12.5* (August 10th, 2006)
|
||||
|
||||
* Updated security fix
|
||||
|
||||
|
||||
*1.12.4* (August 8th, 2006)
|
||||
|
||||
* Cache CgiRequest#request_parameters so that multiple calls don't re-parse multipart data. [Rick]
|
||||
|
||||
* Fixed that remote_form_for can leave out the object parameter and default to the instance variable of the object_name, just like form_for [DHH]
|
||||
|
||||
* Added ActionController.filter_parameter_logging that makes it easy to remove passwords, credit card numbers, and other sensitive information from being logged when a request is handled. #1897 [jeremye@bsa.ca.gov]
|
||||
|
||||
* Fixed that real files and symlinks should be treated the same when compiling templates. #5438 [zachary@panandscan.com]
|
||||
|
||||
* Add :status option to send_data and send_file. Defaults to '200 OK'. #5243 [Manfred Stienstra <m.stienstra@fngtps.com>]
|
||||
|
||||
* Update documentation for erb trim syntax. #5651 [matt@mattmargolis.net]
|
||||
|
||||
* Short documentation to mention use of Mime::Type.register. #5710 [choonkeat@gmail.com]
|
||||
|
||||
|
||||
*1.12.3* (June 28th, 2006)
|
||||
|
||||
* Fix broken traverse_to_controller. We now:
|
||||
Look for a _controller.rb file under RAILS_ROOT to load.
|
||||
If we find it, we require_dependency it and return the controller it defined. (If none was defined we stop looking.)
|
||||
If we don't find it, we look for a .rb file under RAILS_ROOT to load. If we find it, and it loads a constant we keep looking.
|
||||
Otherwise we check to see if a directory of the same name exists, and if it does we create a module for it.
|
||||
|
||||
|
||||
*1.12.2* (June 27th, 2006)
|
||||
|
||||
* Refinement to avoid exceptions in traverse_to_controller.
|
||||
|
||||
* (Hackish) Fix loading of arbitrary files in Ruby's load path by traverse_to_controller. [Nicholas Seckar]
|
||||
|
||||
|
||||
*1.12.1* (April 6th, 2006)
|
||||
@@ -2727,9 +2788,9 @@ Default YAML web services were retired, ActionController::Base.param_parsers car
|
||||
|
||||
* Added pluralize method to the TextHelper that makes it easy to get strings like "1 message", "3 messages"
|
||||
|
||||
* Added proper escaping for the rescues [Andreas Schwartz]
|
||||
* Added proper escaping for the rescues [Andreas Schwarz]
|
||||
|
||||
* Added proper escaping for the option and collection tags [Andreas Schwartz]
|
||||
* Added proper escaping for the option and collection tags [Andreas Schwarz]
|
||||
|
||||
* Fixed NaN errors on benchmarking [Jim Weirich]
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ spec = Gem::Specification.new do |s|
|
||||
s.has_rdoc = true
|
||||
s.requirements << 'none'
|
||||
|
||||
s.add_dependency('activesupport', '= 1.3.1' + PKG_BUILD)
|
||||
s.add_dependency('activesupport', '= 1.4.0' + PKG_BUILD)
|
||||
|
||||
s.require_path = 'lib'
|
||||
s.autorequire = 'action_controller'
|
||||
|
||||
@@ -2,7 +2,7 @@ require 'rexml/document'
|
||||
|
||||
module ActionController #:nodoc:
|
||||
module Assertions #:nodoc:
|
||||
module DeprecatedAssertions
|
||||
module DeprecatedAssertions #:nodoc:
|
||||
def assert_success(message=nil) #:nodoc:
|
||||
assert_response(:success, message)
|
||||
end
|
||||
|
||||
@@ -5,27 +5,31 @@ module ActionController
|
||||
module Assertions
|
||||
module ResponseAssertions
|
||||
# Asserts that the response is one of the following types:
|
||||
#
|
||||
#
|
||||
# * <tt>:success</tt>: Status code was 200
|
||||
# * <tt>:redirect</tt>: Status code was in the 300-399 range
|
||||
# * <tt>:missing</tt>: Status code was 404
|
||||
# * <tt>:error</tt>: Status code was in the 500-599 range
|
||||
#
|
||||
# You can also pass an explicit status code number as the type, like assert_response(501)
|
||||
# You can also pass an explicit status number like assert_response(501)
|
||||
# or its symbolic equivalent assert_response(:not_implemented).
|
||||
# See ActionController::StatusCodes for a full list.
|
||||
def assert_response(type, message = nil)
|
||||
clean_backtrace do
|
||||
if [ :success, :missing, :redirect, :error ].include?(type) && @response.send("#{type}?")
|
||||
assert_block("") { true } # to count the assertion
|
||||
elsif type.is_a?(Fixnum) && @response.response_code == type
|
||||
assert_block("") { true } # to count the assertion
|
||||
elsif type.is_a?(Symbol) && @response.response_code == ActionController::StatusCodes::SYMBOL_TO_STATUS_CODE[type]
|
||||
assert_block("") { true } # to count the assertion
|
||||
else
|
||||
assert_block(build_message(message, "Expected response to be a <?>, but was <?>", type, @response.response_code)) { false }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial,
|
||||
# such that assert_redirected_to(:controller => "weblog") will also match the redirection of
|
||||
# such that assert_redirected_to(:controller => "weblog") will also match the redirection of
|
||||
# redirect_to(:controller => "weblog", :action => "show") and so on.
|
||||
def assert_redirected_to(options = {}, message=nil)
|
||||
clean_backtrace do
|
||||
@@ -66,18 +70,19 @@ module ActionController
|
||||
|
||||
if value.respond_to?(:[]) && value['controller']
|
||||
if key == :actual && value['controller'].first != '/' && !value['controller'].include?('/')
|
||||
value['controller'] = ActionController::Routing.controller_relative_to(value['controller'], @controller.class.controller_path)
|
||||
new_controller_path = ActionController::Routing.controller_relative_to(value['controller'], @controller.class.controller_path)
|
||||
value['controller'] = new_controller_path if value['controller'] != new_controller_path && ActionController::Routing.possible_controllers.include?(new_controller_path)
|
||||
end
|
||||
value['controller'] = value['controller'][1..-1] if value['controller'].first == '/' # strip leading hash
|
||||
end
|
||||
url[key] = value
|
||||
end
|
||||
|
||||
|
||||
|
||||
@response_diff = url[:expected].diff(url[:actual]) if url[:actual]
|
||||
msg = build_message(message, "response is not a redirection to all of the options supplied (redirection is <?>), difference: <?>",
|
||||
msg = build_message(message, "response is not a redirection to all of the options supplied (redirection is <?>), difference: <?>",
|
||||
url[:actual], @response_diff)
|
||||
|
||||
|
||||
assert_block(msg) do
|
||||
url[:expected].keys.all? do |k|
|
||||
if k == :controller then url[:expected][k] == ActionController::Routing.controller_relative_to(url[:actual][k], @controller.class.controller_path)
|
||||
@@ -94,7 +99,7 @@ module ActionController
|
||||
end.flatten
|
||||
|
||||
assert_equal(eurl, url, msg) if eurl && url
|
||||
assert_equal(epath, path, msg) if epath && path
|
||||
assert_equal(epath, path, msg) if epath && path
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -110,7 +115,7 @@ module ActionController
|
||||
else
|
||||
expected == rendered
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -132,4 +137,4 @@ module ActionController
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -407,10 +407,13 @@ module ActionController #:nodoc:
|
||||
|
||||
# Don't render layouts for templates with the given extensions.
|
||||
def exempt_from_layout(*extensions)
|
||||
regexps = extensions.collect do |extension|
|
||||
extension.is_a?(Regexp) ? extension : /\.#{Regexp.escape(extension.to_s)}$/
|
||||
end
|
||||
@@exempt_from_layout.merge regexps
|
||||
@@exempt_from_layout.merge extensions.collect { |extension|
|
||||
if extension.is_a?(Regexp)
|
||||
extension
|
||||
else
|
||||
/\.#{Regexp.escape(extension.to_s)}$/
|
||||
end
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -650,6 +653,20 @@ module ActionController #:nodoc:
|
||||
#
|
||||
# _Deprecation_ _notice_: This used to have the signature <tt>render_text("text", status = 200)</tt>
|
||||
#
|
||||
# === Rendering JSON
|
||||
#
|
||||
# Rendering JSON sets the content type to text/x-json and optionally wraps the JSON in a callback. It is expected
|
||||
# that the response will be eval'd for use as a data structure.
|
||||
#
|
||||
# # Renders '{name: "David"}'
|
||||
# render :json => {:name => "David"}.to_json
|
||||
#
|
||||
# Sometimes the result isn't handled directly by a script (such as when the request comes from a SCRIPT tag),
|
||||
# so the callback option is provided for these cases.
|
||||
#
|
||||
# # Renders 'show({name: "David"})'
|
||||
# render :json => {:name => "David"}.to_json, :callback => 'show'
|
||||
#
|
||||
# === Rendering an inline template
|
||||
#
|
||||
# Rendering of an inline template works as a cross between text and action rendering where the source for the template
|
||||
@@ -734,6 +751,9 @@ module ActionController #:nodoc:
|
||||
elsif xml = options[:xml]
|
||||
render_xml(xml, options[:status])
|
||||
|
||||
elsif json = options[:json]
|
||||
render_json(json, options[:callback], options[:status])
|
||||
|
||||
elsif partial = options[:partial]
|
||||
partial = default_template_name if partial == true
|
||||
if collection = options[:collection]
|
||||
@@ -763,13 +783,11 @@ module ActionController #:nodoc:
|
||||
# Renders according to the same rules as <tt>render</tt>, but returns the result in a string instead
|
||||
# of sending it as the response body to the browser.
|
||||
def render_to_string(options = nil, &block) #:doc:
|
||||
result = ActiveSupport::Deprecation.silence { render(options, &block) }
|
||||
|
||||
ActiveSupport::Deprecation.silence { render(options, &block) }
|
||||
ensure
|
||||
erase_render_results
|
||||
forget_variables_added_to_assigns
|
||||
reset_variables_added_to_assigns
|
||||
|
||||
result
|
||||
end
|
||||
|
||||
def render_action(action_name, status = nil, with_layout = true) #:nodoc:
|
||||
@@ -816,6 +834,13 @@ module ActionController #:nodoc:
|
||||
render_text(xml, status)
|
||||
end
|
||||
|
||||
def render_json(json, callback = nil, status = nil) #:nodoc:
|
||||
json = "#{callback}(#{json})" unless callback.blank?
|
||||
|
||||
response.content_type = Mime::JSON
|
||||
render_text(json, status)
|
||||
end
|
||||
|
||||
def render_nothing(status = nil) #:nodoc:
|
||||
render_text(' ', status)
|
||||
end
|
||||
@@ -893,7 +918,7 @@ module ActionController #:nodoc:
|
||||
response.redirected_to = nil
|
||||
response.redirected_to_method_params = nil
|
||||
response.headers['Status'] = DEFAULT_RENDER_STATUS_CODE
|
||||
response.headers.delete('location')
|
||||
response.headers.delete('Location')
|
||||
end
|
||||
|
||||
# Erase both render and redirect results
|
||||
@@ -1089,7 +1114,11 @@ module ActionController #:nodoc:
|
||||
|
||||
def assign_default_content_type_and_charset
|
||||
response.content_type ||= Mime::HTML
|
||||
response.charset ||= self.class.default_charset
|
||||
response.charset ||= self.class.default_charset unless sending_file?
|
||||
end
|
||||
|
||||
def sending_file?
|
||||
response.headers["Content-Transfer-Encoding"] == "binary"
|
||||
end
|
||||
|
||||
def action_methods
|
||||
@@ -1164,10 +1193,9 @@ module ActionController #:nodoc:
|
||||
end
|
||||
|
||||
def template_exempt_from_layout?(template_name = default_template_name)
|
||||
@@exempt_from_layout.any? { |ext| template_name =~ ext } or
|
||||
@template.pick_template_extension(template_name) == :rjs
|
||||
rescue
|
||||
false
|
||||
extension = @template.pick_template_extension(template_name) rescue nil
|
||||
name_with_extension = !template_name.include?('.') && extension ? "#{template_name}.#{extension}" : template_name
|
||||
extension == :rjs || @@exempt_from_layout.any? { |ext| name_with_extension =~ ext }
|
||||
end
|
||||
|
||||
def assert_existence_of_template_file(template_name)
|
||||
|
||||
@@ -135,7 +135,7 @@ module ActionController #:nodoc:
|
||||
|
||||
private
|
||||
def caching_allowed
|
||||
!request.post? && response.headers['Status'] && response.headers['Status'].to_i < 400
|
||||
request.get? && response.headers['Status'].to_i == 200
|
||||
end
|
||||
end
|
||||
|
||||
@@ -363,7 +363,12 @@ module ActionController #:nodoc:
|
||||
# Name can take one of three forms:
|
||||
# * String: This would normally take the form of a path like "pages/45/notes"
|
||||
# * Hash: Is treated as an implicit call to url_for, like { :controller => "pages", :action => "notes", :id => 45 }
|
||||
# * Regexp: Will destroy all the matched fragments, example: %r{pages/\d*/notes} Ensure you do not specify start and finish in the regex (^$) because the actual filename matched looks like ./cache/filename/path.cache
|
||||
# * Regexp: Will destroy all the matched fragments, example:
|
||||
# %r{pages/\d*/notes}
|
||||
# Ensure you do not specify start and finish in the regex (^$) because
|
||||
# the actual filename matched looks like ./cache/filename/path.cache
|
||||
# Regexp expiration is not supported on caches which can't iterate over
|
||||
# all keys, such as memcached.
|
||||
def expire_fragment(name, options = nil)
|
||||
return unless perform_caching
|
||||
|
||||
@@ -384,6 +389,7 @@ module ActionController #:nodoc:
|
||||
def expire_matched_fragments(matcher = /.*/, options = nil) #:nodoc:
|
||||
expire_fragment(matcher, options)
|
||||
end
|
||||
deprecate :expire_matched_fragments => :expire_fragment
|
||||
|
||||
|
||||
class UnthreadedMemoryStore #:nodoc:
|
||||
|
||||
@@ -27,13 +27,6 @@ class CGI #:nodoc:
|
||||
def request_parameters
|
||||
CGIMethods.parse_request_parameters(params, env_table)
|
||||
end
|
||||
|
||||
def redirect(where)
|
||||
header({
|
||||
"Status" => "302 Moved",
|
||||
"location" => "#{where}"
|
||||
})
|
||||
end
|
||||
|
||||
def session(parameters = nil)
|
||||
parameters = {} if parameters.nil?
|
||||
|
||||
@@ -23,18 +23,19 @@ class CGIMethods #:nodoc:
|
||||
def parse_request_parameters(params)
|
||||
parser = FormEncodedPairParser.new
|
||||
|
||||
finished = false
|
||||
until finished
|
||||
finished = true
|
||||
params = params.dup
|
||||
until params.empty?
|
||||
for key, value in params
|
||||
next if key.blank?
|
||||
if !key.include?('[')
|
||||
if key.blank?
|
||||
params.delete key
|
||||
elsif !key.include?('[')
|
||||
# much faster to test for the most common case first (GET)
|
||||
# and avoid the call to build_deep_hash
|
||||
parser.result[key] = get_typed_value(value[0])
|
||||
params.delete key
|
||||
elsif value.is_a?(Array)
|
||||
parser.parse(key, get_typed_value(value.shift))
|
||||
finished = false unless value.empty?
|
||||
params.delete key if value.empty?
|
||||
else
|
||||
raise TypeError, "Expected array, found #{value.inspect}"
|
||||
end
|
||||
@@ -63,48 +64,55 @@ class CGIMethods #:nodoc:
|
||||
|
||||
private
|
||||
def get_typed_value(value)
|
||||
# test most frequent case first
|
||||
if value.is_a?(String)
|
||||
value
|
||||
elsif value.respond_to?(:content_type) && ! value.content_type.blank?
|
||||
# Uploaded file
|
||||
unless value.respond_to?(:full_original_filename)
|
||||
class << value
|
||||
alias_method :full_original_filename, :original_filename
|
||||
case value
|
||||
when String
|
||||
value
|
||||
when NilClass
|
||||
''
|
||||
when Array
|
||||
value.map { |v| get_typed_value(v) }
|
||||
else
|
||||
# Uploaded file provides content type and filename.
|
||||
if value.respond_to?(:content_type) &&
|
||||
!value.content_type.blank? &&
|
||||
!value.original_filename.blank?
|
||||
unless value.respond_to?(:full_original_filename)
|
||||
class << value
|
||||
alias_method :full_original_filename, :original_filename
|
||||
|
||||
# Take the basename of the upload's original filename.
|
||||
# This handles the full Windows paths given by Internet Explorer
|
||||
# (and perhaps other broken user agents) without affecting
|
||||
# those which give the lone filename.
|
||||
# The Windows regexp is adapted from Perl's File::Basename.
|
||||
def original_filename
|
||||
if md = /^(?:.*[:\\\/])?(.*)/m.match(full_original_filename)
|
||||
md.captures.first
|
||||
else
|
||||
File.basename full_original_filename
|
||||
# Take the basename of the upload's original filename.
|
||||
# This handles the full Windows paths given by Internet Explorer
|
||||
# (and perhaps other broken user agents) without affecting
|
||||
# those which give the lone filename.
|
||||
# The Windows regexp is adapted from Perl's File::Basename.
|
||||
def original_filename
|
||||
if md = /^(?:.*[:\\\/])?(.*)/m.match(full_original_filename)
|
||||
md.captures.first
|
||||
else
|
||||
File.basename full_original_filename
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Return the same value after overriding original_filename.
|
||||
value
|
||||
|
||||
# Multipart values may have content type, but no filename.
|
||||
elsif value.respond_to?(:read)
|
||||
result = value.read
|
||||
value.rewind
|
||||
result
|
||||
|
||||
# Unknown value, neither string nor multipart.
|
||||
else
|
||||
raise "Unknown form value: #{value.inspect}"
|
||||
end
|
||||
end
|
||||
|
||||
# Return the same value after overriding original_filename.
|
||||
value
|
||||
|
||||
elsif value.respond_to?(:read)
|
||||
# Value as part of a multipart request
|
||||
result = value.read
|
||||
value.rewind
|
||||
result
|
||||
elsif value.class == Array
|
||||
value.collect { |v| get_typed_value(v) }
|
||||
else
|
||||
# other value (neither string nor a multipart request)
|
||||
value.to_s
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
class FormEncodedPairParser < StringScanner
|
||||
class FormEncodedPairParser < StringScanner #:nodoc:
|
||||
attr_reader :top, :parent, :result
|
||||
|
||||
def initialize(pairs = [])
|
||||
|
||||
@@ -8,13 +8,13 @@ module ActionController #:nodoc:
|
||||
# sessions (large performance increase if sessions are not needed). The <tt>session_options</tt> are the same as for CGI::Session:
|
||||
#
|
||||
# * <tt>:database_manager</tt> - standard options are CGI::Session::FileStore, CGI::Session::MemoryStore, and CGI::Session::PStore
|
||||
# (default). Additionally, there is CGI::Session::DRbStore and CGI::Session::ActiveRecordStore. Read more about these in
|
||||
# (default). Additionally, there is CGI::Session::DRbStore and CGI::Session::ActiveRecordStore. Read more about these in
|
||||
# lib/action_controller/session.
|
||||
# * <tt>:session_key</tt> - the parameter name used for the session id. Defaults to '_session_id'.
|
||||
# * <tt>:session_id</tt> - the session id to use. If not provided, then it is retrieved from the +session_key+ parameter
|
||||
# of the request, or automatically generated for a new session.
|
||||
# * <tt>:new_session</tt> - if true, force creation of a new session. If not set, a new session is only created if none currently
|
||||
# exists. If false, a new session is never created, and if none currently exists and the +session_id+ option is not set,
|
||||
# exists. If false, a new session is never created, and if none currently exists and the +session_id+ option is not set,
|
||||
# an ArgumentError is raised.
|
||||
# * <tt>:session_expires</tt> - the time the current session expires, as a +Time+ object. If not set, the session will continue
|
||||
# indefinitely.
|
||||
@@ -22,10 +22,10 @@ module ActionController #:nodoc:
|
||||
# server.
|
||||
# * <tt>:session_secure</tt> - if +true+, this session will only work over HTTPS.
|
||||
# * <tt>:session_path</tt> - the path for which this session applies. Defaults to the directory of the CGI script.
|
||||
def self.process_cgi(cgi = CGI.new, session_options = {})
|
||||
def self.process_cgi(cgi = CGI.new, session_options = {})
|
||||
new.process_cgi(cgi, session_options)
|
||||
end
|
||||
|
||||
|
||||
def process_cgi(cgi, session_options = {}) #:nodoc:
|
||||
process(CgiRequest.new(cgi, session_options), CgiResponse.new(cgi)).out
|
||||
end
|
||||
@@ -51,7 +51,7 @@ module ActionController #:nodoc:
|
||||
if (qs = @cgi.query_string) && !qs.empty?
|
||||
qs
|
||||
elsif uri = @env['REQUEST_URI']
|
||||
parts = uri.split('?')
|
||||
parts = uri.split('?')
|
||||
parts.shift
|
||||
parts.join('?')
|
||||
else
|
||||
@@ -60,7 +60,8 @@ module ActionController #:nodoc:
|
||||
end
|
||||
|
||||
def query_parameters
|
||||
(qs = self.query_string).empty? ? {} : CGIMethods.parse_query_parameters(qs)
|
||||
@query_parameters ||=
|
||||
(qs = self.query_string).empty? ? {} : CGIMethods.parse_query_parameters(qs)
|
||||
end
|
||||
|
||||
def request_parameters
|
||||
@@ -71,7 +72,7 @@ module ActionController #:nodoc:
|
||||
CGIMethods.parse_request_parameters(@cgi.params)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
def cookies
|
||||
@cgi.cookies.freeze
|
||||
end
|
||||
@@ -106,10 +107,21 @@ module ActionController #:nodoc:
|
||||
@session = Hash.new
|
||||
else
|
||||
stale_session_check! do
|
||||
if session_options_with_string_keys['new_session'] == true
|
||||
@session = new_session
|
||||
else
|
||||
@session = CGI::Session.new(@cgi, session_options_with_string_keys)
|
||||
case value = session_options_with_string_keys['new_session']
|
||||
when true
|
||||
@session = new_session
|
||||
when false
|
||||
begin
|
||||
@session = CGI::Session.new(@cgi, session_options_with_string_keys)
|
||||
# CGI::Session raises ArgumentError if 'new_session' == false
|
||||
# and no session cookie or query param is present.
|
||||
rescue ArgumentError
|
||||
@session = Hash.new
|
||||
end
|
||||
when nil
|
||||
@session = CGI::Session.new(@cgi, session_options_with_string_keys)
|
||||
else
|
||||
raise ArgumentError, "Invalid new_session option: #{value}"
|
||||
end
|
||||
@session['__valid_session']
|
||||
end
|
||||
@@ -159,7 +171,7 @@ end_msg
|
||||
end
|
||||
|
||||
def session_options_with_string_keys
|
||||
@session_options_with_string_keys ||= DEFAULT_SESSION_OPTIONS.merge(@session_options).inject({}) { |options, (k,v)| options[k.to_s] = v; options }
|
||||
@session_options_with_string_keys ||= DEFAULT_SESSION_OPTIONS.merge(@session_options).stringify_keys
|
||||
end
|
||||
end
|
||||
|
||||
@@ -170,7 +182,9 @@ end_msg
|
||||
end
|
||||
|
||||
def out(output = $stdout)
|
||||
convert_content_type!(@headers)
|
||||
convert_content_type!
|
||||
set_content_length!
|
||||
|
||||
output.binmode if output.respond_to?(:binmode)
|
||||
output.sync = false if output.respond_to?(:sync=)
|
||||
|
||||
@@ -195,16 +209,22 @@ end_msg
|
||||
end
|
||||
|
||||
private
|
||||
def convert_content_type!(headers)
|
||||
if header = headers.delete("Content-Type")
|
||||
headers["type"] = header
|
||||
def convert_content_type!
|
||||
if content_type = @headers.delete("Content-Type")
|
||||
@headers["type"] = content_type
|
||||
end
|
||||
if header = headers.delete("Content-type")
|
||||
headers["type"] = header
|
||||
if content_type = @headers.delete("Content-type")
|
||||
@headers["type"] = content_type
|
||||
end
|
||||
if header = headers.delete("content-type")
|
||||
headers["type"] = header
|
||||
if content_type = @headers.delete("content-type")
|
||||
@headers["type"] = content_type
|
||||
end
|
||||
end
|
||||
|
||||
# Don't set the Content-Length for block-based bodies as that would mean reading it all into memory. Not nice
|
||||
# for, say, a 2GB streaming file.
|
||||
def set_content_length!
|
||||
@headers["Content-Length"] = @body.size unless @body.respond_to?(:call)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -75,11 +75,13 @@ module ActionController #:nodoc:
|
||||
# will also use /code/weblog/components as template root
|
||||
# and find templates in /code/weblog/components/admin/parties/users/
|
||||
def uses_component_template_root
|
||||
path_of_calling_controller = File.dirname(caller[0].split(/:\d+:/, 2).first)
|
||||
path_of_calling_controller = File.dirname(caller[1].split(/:\d+:/, 2).first)
|
||||
path_of_controller_root = path_of_calling_controller.sub(/#{Regexp.escape(File.dirname(controller_path))}$/, "")
|
||||
|
||||
self.template_root = path_of_controller_root
|
||||
end
|
||||
|
||||
deprecate :uses_component_template_root => 'Components are deprecated and will be removed in Rails 2.0.'
|
||||
end
|
||||
|
||||
module InstanceMethods
|
||||
|
||||
@@ -81,10 +81,10 @@ module ActionController #:nodoc:
|
||||
# can use <tt>prepend_before_filter</tt> and <tt>prepend_after_filter</tt>. Filters added by these methods will be put at the
|
||||
# beginning of their respective chain and executed before the rest. For example:
|
||||
#
|
||||
# class ShoppingController
|
||||
# class ShoppingController < ActionController::Base
|
||||
# before_filter :verify_open_shop
|
||||
#
|
||||
# class CheckoutController
|
||||
# class CheckoutController < ShoppingController
|
||||
# prepend_before_filter :ensure_items_in_cart, :ensure_items_in_stock
|
||||
#
|
||||
# The filter chain for the CheckoutController is now <tt>:ensure_items_in_cart, :ensure_items_in_stock,</tt>
|
||||
@@ -616,10 +616,7 @@ module ActionController #:nodoc:
|
||||
end
|
||||
|
||||
def perform_action_with_filters
|
||||
#result = perform_filters do
|
||||
# perform_action_without_filters unless performed?
|
||||
#end
|
||||
@before_filter_chain_aborted = (call_filter(self.class.filter_chain, 0) == false)
|
||||
call_filter(self.class.filter_chain, 0)
|
||||
end
|
||||
|
||||
def process_with_filters(request, response, method = :perform_action, *arguments) #:nodoc:
|
||||
@@ -640,7 +637,7 @@ module ActionController #:nodoc:
|
||||
filter.call(self) do
|
||||
halted = call_filter(chain, index.next)
|
||||
end
|
||||
halt_filter_chain(filter.filter, :no_yield) if halted == false
|
||||
halt_filter_chain(filter.filter, :no_yield) if halted == false unless @before_filter_chain_aborted
|
||||
halted
|
||||
end
|
||||
|
||||
@@ -653,6 +650,7 @@ module ActionController #:nodoc:
|
||||
logger.info "Filter chain halted as [#{filter.inspect}] returned false."
|
||||
end
|
||||
end
|
||||
@before_filter_chain_aborted = true
|
||||
return false
|
||||
end
|
||||
|
||||
|
||||
@@ -113,7 +113,7 @@ module ActionController
|
||||
# performed on the location header.
|
||||
def follow_redirect!
|
||||
raise "not a redirect! #{@status} #{@status_message}" unless redirect?
|
||||
get(interpret_uri(headers["location"].first))
|
||||
get(interpret_uri(headers['location'].first))
|
||||
status
|
||||
end
|
||||
|
||||
@@ -493,6 +493,8 @@ module ActionController
|
||||
%w(get post cookies assigns xml_http_request).each do |method|
|
||||
define_method(method) do |*args|
|
||||
reset! unless @integration_session
|
||||
# reset the html_document variable, but only for new get/post calls
|
||||
@html_document = nil unless %w(cookies assigns).include?(method)
|
||||
returning @integration_session.send(method, *args) do
|
||||
copy_session_variables!
|
||||
end
|
||||
|
||||
@@ -27,9 +27,9 @@ module ActionController #:nodoc:
|
||||
# With layouts, you can flip it around and have the common structure know where to insert changing content. This means
|
||||
# that the header and footer are only mentioned in one place, like this:
|
||||
#
|
||||
# <!-- The header part of this layout -->
|
||||
# // The header part of this layout
|
||||
# <%= yield %>
|
||||
# <!-- The footer part of this layout -->
|
||||
# // The footer part of this layout -->
|
||||
#
|
||||
# And then you have content pages that look like this:
|
||||
#
|
||||
@@ -38,9 +38,9 @@ module ActionController #:nodoc:
|
||||
# Not a word about common structures. At rendering time, the content page is computed and then inserted in the layout,
|
||||
# like this:
|
||||
#
|
||||
# <!-- The header part of this layout -->
|
||||
# // The header part of this layout
|
||||
# hello world
|
||||
# <!-- The footer part of this layout -->
|
||||
# // The footer part of this layout -->
|
||||
#
|
||||
# == Accessing shared variables
|
||||
#
|
||||
@@ -266,7 +266,7 @@ module ActionController #:nodoc:
|
||||
|
||||
def candidate_for_layout?(options)
|
||||
(options.has_key?(:layout) && options[:layout] != false) ||
|
||||
options.values_at(:text, :xml, :file, :inline, :partial, :nothing).compact.empty? &&
|
||||
options.values_at(:text, :xml, :json, :file, :inline, :partial, :nothing).compact.empty? &&
|
||||
!template_exempt_from_layout?(default_template_name(options[:action] || options[:template]))
|
||||
end
|
||||
|
||||
|
||||
@@ -135,12 +135,14 @@ module Mime
|
||||
HTML = Type.new "text/html", :html, %w( application/xhtml+xml )
|
||||
JS = Type.new "text/javascript", :js, %w( application/javascript application/x-javascript )
|
||||
ICS = Type.new "text/calendar", :ics
|
||||
CSV = Type.new "text/csv", :csv
|
||||
XML = Type.new "application/xml", :xml, %w( text/xml application/x-xml )
|
||||
RSS = Type.new "application/rss+xml", :rss
|
||||
ATOM = Type.new "application/atom+xml", :atom
|
||||
YAML = Type.new "application/x-yaml", :yaml, %w( text/yaml )
|
||||
JSON = Type.new "application/json", :json, %w( text/x-json )
|
||||
|
||||
SET = [ ALL, TEXT, HTML, JS, ICS, XML, RSS, ATOM, YAML ]
|
||||
SET = [ ALL, TEXT, HTML, JS, ICS, XML, RSS, ATOM, YAML, JSON ]
|
||||
|
||||
LOOKUP = Hash.new { |h, k| h[k] = Type.new(k) unless k == "" }
|
||||
|
||||
@@ -157,6 +159,8 @@ module Mime
|
||||
|
||||
LOOKUP["text/calendar"] = ICS
|
||||
|
||||
LOOKUP["text/csv"] = CSV
|
||||
|
||||
LOOKUP["application/xml"] = XML
|
||||
LOOKUP["text/xml"] = XML
|
||||
LOOKUP["application/x-xml"] = XML
|
||||
@@ -167,7 +171,10 @@ module Mime
|
||||
LOOKUP["application/rss+xml"] = RSS
|
||||
LOOKUP["application/atom+xml"] = ATOM
|
||||
|
||||
|
||||
LOOKUP["application/json"] = JSON
|
||||
LOOKUP["text/x-json"] = JSON
|
||||
|
||||
|
||||
EXTENSION_LOOKUP = Hash.new { |h, k| h[k] = Type.new(k) unless k == "" }
|
||||
|
||||
EXTENSION_LOOKUP["html"] = HTML
|
||||
@@ -181,9 +188,13 @@ module Mime
|
||||
|
||||
EXTENSION_LOOKUP["ics"] = ICS
|
||||
|
||||
EXTENSION_LOOKUP["csv"] = CSV
|
||||
|
||||
EXTENSION_LOOKUP["yml"] = YAML
|
||||
EXTENSION_LOOKUP["yaml"] = YAML
|
||||
|
||||
EXTENSION_LOOKUP["rss"] = RSS
|
||||
EXTENSION_LOOKUP["atom"] = ATOM
|
||||
end
|
||||
|
||||
EXTENSION_LOOKUP["json"] = JSON
|
||||
end
|
||||
|
||||
@@ -13,14 +13,18 @@ module ActionController
|
||||
@parameters ||= request_parameters.update(query_parameters).update(path_parameters).with_indifferent_access
|
||||
end
|
||||
|
||||
# Returns the HTTP request method as a lowercase symbol (:get, for example)
|
||||
# Returns the HTTP request method as a lowercase symbol (:get, for example). Note, HEAD is returned as :get
|
||||
# since the two are supposedly to be functionaly equivilent for all purposes except that HEAD won't return a response
|
||||
# body (which Rails also takes care of elsewhere).
|
||||
def method
|
||||
@request_method ||= (!parameters[:_method].blank? && @env['REQUEST_METHOD'] == 'POST') ?
|
||||
parameters[:_method].to_s.downcase.to_sym :
|
||||
@env['REQUEST_METHOD'].downcase.to_sym
|
||||
|
||||
@request_method == :head ? :get : @request_method
|
||||
end
|
||||
|
||||
# Is this a GET request? Equivalent to request.method == :get
|
||||
# Is this a GET (or HEAD) request? Equivalent to request.method == :get
|
||||
def get?
|
||||
method == :get
|
||||
end
|
||||
@@ -40,9 +44,10 @@ module ActionController
|
||||
method == :delete
|
||||
end
|
||||
|
||||
# Is this a HEAD request? Equivalent to request.method == :head
|
||||
# Is this a HEAD request? HEAD is mapped as :get for request.method, so here we ask the
|
||||
# REQUEST_METHOD header directly. Thus, for head, both get? and head? will return true.
|
||||
def head?
|
||||
method == :head
|
||||
@env['REQUEST_METHOD'].downcase.to_sym == :head
|
||||
end
|
||||
|
||||
# Determine whether the body of a HTTP call is URL-encoded (default)
|
||||
@@ -130,19 +135,21 @@ module ActionController
|
||||
@env['RAW_POST_DATA']
|
||||
end
|
||||
|
||||
# Returns the request URI correctly, taking into account the idiosyncracies
|
||||
# of the various servers.
|
||||
# Return the request URI, accounting for server idiosyncracies.
|
||||
# WEBrick includes the full URL. IIS leaves REQUEST_URI blank.
|
||||
def request_uri
|
||||
if uri = @env['REQUEST_URI']
|
||||
(%r{^\w+\://[^/]+(/.*|$)$} =~ uri) ? $1 : uri # Remove domain, which webrick puts into the request_uri.
|
||||
else # REQUEST_URI is blank under IIS - get this from PATH_INFO and SCRIPT_NAME
|
||||
# Remove domain, which webrick puts into the request_uri.
|
||||
(%r{^\w+\://[^/]+(/.*|$)$} =~ uri) ? $1 : uri
|
||||
else
|
||||
# Construct IIS missing REQUEST_URI from SCRIPT_NAME and PATH_INFO.
|
||||
script_filename = @env['SCRIPT_NAME'].to_s.match(%r{[^/]+$})
|
||||
uri = @env['PATH_INFO']
|
||||
uri = uri.sub(/#{script_filename}\//, '') unless script_filename.nil?
|
||||
unless (env_qs = @env['QUERY_STRING']).nil? || env_qs.empty?
|
||||
uri << '?' << env_qs
|
||||
end
|
||||
uri
|
||||
@env['REQUEST_URI'] = uri
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -34,14 +34,16 @@ module ActionController #:nodoc:
|
||||
|
||||
# Overwrite to implement custom logging of errors. By default logs as fatal.
|
||||
def log_error(exception) #:doc:
|
||||
if ActionView::TemplateError === exception
|
||||
logger.fatal(exception.to_s)
|
||||
else
|
||||
logger.fatal(
|
||||
"\n\n#{exception.class} (#{exception.message}):\n " +
|
||||
clean_backtrace(exception).join("\n ") +
|
||||
"\n\n"
|
||||
)
|
||||
ActiveSupport::Deprecation.silence do
|
||||
if ActionView::TemplateError === exception
|
||||
logger.fatal(exception.to_s)
|
||||
else
|
||||
logger.fatal(
|
||||
"\n\n#{exception.class} (#{exception.message}):\n " +
|
||||
clean_backtrace(exception).join("\n ") +
|
||||
"\n\n"
|
||||
)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -162,7 +162,15 @@ module ActionController
|
||||
# map.resources :articles do |article|
|
||||
# article.resources :comments
|
||||
# end
|
||||
#
|
||||
#
|
||||
# The comment resources work the same, but must now include a value for :article_id.
|
||||
#
|
||||
# comments_url(@article)
|
||||
# comment_url(@article, @comment)
|
||||
#
|
||||
# comments_url(:article_id => @article)
|
||||
# comment_url(:article_id => @article, :id => @comment)
|
||||
#
|
||||
# * <tt>:name_prefix</tt> -- define a prefix for all generated routes, usually ending in an underscore.
|
||||
# Use this if you have named routes that may clash.
|
||||
#
|
||||
|
||||
@@ -27,7 +27,7 @@ module ActionController
|
||||
|
||||
def redirect(to_url, permanently = false)
|
||||
@headers["Status"] = "302 Found" unless @headers["Status"] == "301 Moved Permanently"
|
||||
@headers["location"] = to_url
|
||||
@headers["Location"] = to_url
|
||||
|
||||
@body = "<html><body>You are being <a href=\"#{to_url}\">redirected</a>.</body></html>"
|
||||
end
|
||||
|
||||
@@ -24,7 +24,7 @@ class NilClass
|
||||
end
|
||||
end
|
||||
|
||||
class Regexp
|
||||
class Regexp #:nodoc:
|
||||
def number_of_captures
|
||||
Regexp.new("|#{source}").match('').captures.length
|
||||
end
|
||||
@@ -305,7 +305,7 @@ module ActionController
|
||||
end
|
||||
end
|
||||
|
||||
class Route
|
||||
class Route #:nodoc:
|
||||
attr_accessor :segments, :requirements, :conditions
|
||||
|
||||
def initialize
|
||||
@@ -536,7 +536,7 @@ module ActionController
|
||||
|
||||
end
|
||||
|
||||
class Segment
|
||||
class Segment #:nodoc:
|
||||
attr_accessor :is_optional
|
||||
alias_method :optional?, :is_optional
|
||||
|
||||
@@ -591,7 +591,7 @@ module ActionController
|
||||
end
|
||||
end
|
||||
|
||||
class StaticSegment < Segment
|
||||
class StaticSegment < Segment #:nodoc:
|
||||
attr_accessor :value, :raw
|
||||
alias_method :raw?, :raw
|
||||
|
||||
@@ -625,7 +625,7 @@ module ActionController
|
||||
end
|
||||
end
|
||||
|
||||
class DividerSegment < StaticSegment
|
||||
class DividerSegment < StaticSegment #:nodoc:
|
||||
def initialize(value = nil)
|
||||
super(value)
|
||||
self.raw = true
|
||||
@@ -637,7 +637,7 @@ module ActionController
|
||||
end
|
||||
end
|
||||
|
||||
class DynamicSegment < Segment
|
||||
class DynamicSegment < Segment #:nodoc:
|
||||
attr_accessor :key, :default, :regexp
|
||||
|
||||
def initialize(key = nil, options = {})
|
||||
@@ -725,7 +725,7 @@ module ActionController
|
||||
|
||||
end
|
||||
|
||||
class ControllerSegment < DynamicSegment
|
||||
class ControllerSegment < DynamicSegment #:nodoc:
|
||||
def regexp_chunk
|
||||
possible_names = Routing.possible_controllers.collect { |name| Regexp.escape name }
|
||||
"(?i-:(#{(regexp || Regexp.union(*possible_names)).source}))"
|
||||
@@ -752,7 +752,7 @@ module ActionController
|
||||
end
|
||||
end
|
||||
|
||||
class PathSegment < DynamicSegment
|
||||
class PathSegment < DynamicSegment #:nodoc:
|
||||
EscapedSlash = CGI.escape("/")
|
||||
def interpolation_chunk
|
||||
"\#{CGI.escape(#{local_name}.to_s).gsub(#{EscapedSlash.inspect}, '/')}"
|
||||
@@ -782,7 +782,7 @@ module ActionController
|
||||
end
|
||||
end
|
||||
|
||||
class RouteBuilder
|
||||
class RouteBuilder #:nodoc:
|
||||
attr_accessor :separators, :optional_separators
|
||||
|
||||
def initialize
|
||||
@@ -950,17 +950,21 @@ module ActionController
|
||||
route.significant_keys << :action
|
||||
end
|
||||
|
||||
if !route.significant_keys.include?(:controller)
|
||||
raise ArgumentError, "Illegal route: the :controller must be specified!"
|
||||
end
|
||||
|
||||
route
|
||||
end
|
||||
end
|
||||
|
||||
class RouteSet
|
||||
class RouteSet #:nodoc:
|
||||
# Mapper instances are used to build routes. The object passed to the draw
|
||||
# block in config/routes.rb is a Mapper instance.
|
||||
#
|
||||
# Mapper instances have relatively few instance methods, in order to avoid
|
||||
# clashes with named routes.
|
||||
class Mapper
|
||||
class Mapper #:nodoc:
|
||||
def initialize(set)
|
||||
@set = set
|
||||
end
|
||||
@@ -975,6 +979,14 @@ module ActionController
|
||||
@set.add_named_route(name, path, options)
|
||||
end
|
||||
|
||||
# Added deprecation notice for anyone who already added a named route called "root".
|
||||
# It'll be used as a shortcut for map.connect '' in Rails 2.0.
|
||||
def root(*args, &proc)
|
||||
super unless args.length >= 1 && proc.nil?
|
||||
@set.add_named_route("root", *args)
|
||||
end
|
||||
deprecate :root => "(as the the label for a named route) will become a shortcut for map.connect '', so find another name"
|
||||
|
||||
def method_missing(route_name, *args, &proc)
|
||||
super unless args.length >= 1 && proc.nil?
|
||||
@set.add_named_route(route_name, *args)
|
||||
@@ -984,7 +996,7 @@ module ActionController
|
||||
# A NamedRouteCollection instance is a collection of named routes, and also
|
||||
# maintains an anonymous module that can be used to install helpers for the
|
||||
# named routes.
|
||||
class NamedRouteCollection
|
||||
class NamedRouteCollection #:nodoc:
|
||||
include Enumerable
|
||||
|
||||
attr_reader :routes, :helpers
|
||||
@@ -996,7 +1008,11 @@ module ActionController
|
||||
def clear!
|
||||
@routes = {}
|
||||
@helpers = []
|
||||
@module = Module.new
|
||||
|
||||
@module ||= Module.new
|
||||
@module.instance_methods.each do |selector|
|
||||
@module.send :remove_method, selector
|
||||
end
|
||||
end
|
||||
|
||||
def add(name, route)
|
||||
|
||||
@@ -5,6 +5,8 @@ require 'base64'
|
||||
|
||||
class CGI
|
||||
class Session
|
||||
attr_reader :data
|
||||
|
||||
# Return this session's underlying Session instance. Useful for the DB-backed session stores.
|
||||
def model
|
||||
@dbman.model if @dbman
|
||||
|
||||
@@ -26,6 +26,10 @@ class CGI #:nodoc:all
|
||||
def delete
|
||||
@@session_data.delete(@session_id)
|
||||
end
|
||||
|
||||
def data
|
||||
@@session_data[@session_id]
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -93,6 +93,10 @@ begin
|
||||
end
|
||||
@session_data = {}
|
||||
end
|
||||
|
||||
def data
|
||||
@session_data
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -120,16 +120,16 @@ module ActionController #:nodoc:
|
||||
end
|
||||
|
||||
def process_cleanup_with_session_management_support
|
||||
process_cleanup_without_session_management_support
|
||||
clear_persistent_model_associations
|
||||
process_cleanup_without_session_management_support
|
||||
end
|
||||
|
||||
# Clear cached associations in session data so they don't overflow
|
||||
# the database field. Only applies to ActiveRecordStore since there
|
||||
# is not a standard way to iterate over session data.
|
||||
def clear_persistent_model_associations #:doc:
|
||||
if defined?(@_session) && @_session.instance_variables.include?('@data')
|
||||
session_data = @_session.instance_variable_get('@data')
|
||||
if defined?(@_session) && @_session.respond_to?(:data)
|
||||
session_data = @_session.data
|
||||
|
||||
if session_data && session_data.respond_to?(:each_value)
|
||||
session_data.each_value do |obj|
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
module ActionController
|
||||
module StatusCodes
|
||||
|
||||
module StatusCodes #:nodoc:
|
||||
# Defines the standard HTTP status codes, by integer, with their
|
||||
# corresponding default message texts.
|
||||
# Source: http://www.iana.org/assignments/http-status-codes
|
||||
STATUS_CODES = {
|
||||
100 => "Continue",
|
||||
101 => "Switching Protocols",
|
||||
102 => "Processing",
|
||||
|
||||
200 => "OK",
|
||||
201 => "Created",
|
||||
@@ -14,6 +15,8 @@ module ActionController
|
||||
204 => "No Content",
|
||||
205 => "Reset Content",
|
||||
206 => "Partial Content",
|
||||
207 => "Multi-Status",
|
||||
226 => "IM Used",
|
||||
|
||||
300 => "Multiple Choices",
|
||||
301 => "Moved Permanently",
|
||||
@@ -41,13 +44,19 @@ module ActionController
|
||||
415 => "Unsupported Media Type",
|
||||
416 => "Requested Range Not Satisfiable",
|
||||
417 => "Expectation Failed",
|
||||
422 => "Unprocessable Entity",
|
||||
423 => "Locked",
|
||||
424 => "Failed Dependency",
|
||||
426 => "Upgrade Required",
|
||||
|
||||
500 => "Internal Server Error",
|
||||
501 => "Not Implemented",
|
||||
502 => "Bad Gateway",
|
||||
503 => "Service Unavailable",
|
||||
504 => "Gateway Timeout",
|
||||
505 => "HTTP Version Not Supported"
|
||||
505 => "HTTP Version Not Supported",
|
||||
507 => "Insufficient Storage",
|
||||
510 => "Not Extended"
|
||||
}
|
||||
|
||||
# Provides a symbol-to-fixnum lookup for converting a symbol (like
|
||||
|
||||
@@ -38,7 +38,7 @@ module ActionController #:nodoc:
|
||||
|
||||
def reset_session
|
||||
@session = TestSession.new
|
||||
end
|
||||
end
|
||||
|
||||
def raw_post
|
||||
if raw_post = env['RAW_POST_DATA']
|
||||
@@ -179,7 +179,7 @@ module ActionController #:nodoc:
|
||||
|
||||
# returns the redirection location or nil
|
||||
def redirect_url
|
||||
redirect? ? headers['location'] : nil
|
||||
headers['Location']
|
||||
end
|
||||
|
||||
# does the redirect location match this regexp pattern?
|
||||
@@ -275,27 +275,40 @@ module ActionController #:nodoc:
|
||||
end
|
||||
|
||||
class TestSession #:nodoc:
|
||||
def initialize(attributes = {})
|
||||
attr_accessor :session_id
|
||||
|
||||
def initialize(attributes = nil)
|
||||
@session_id = ''
|
||||
@attributes = attributes
|
||||
@saved_attributes = nil
|
||||
end
|
||||
|
||||
def data
|
||||
@attributes ||= @saved_attributes || {}
|
||||
end
|
||||
|
||||
def [](key)
|
||||
@attributes[key]
|
||||
data[key]
|
||||
end
|
||||
|
||||
def []=(key, value)
|
||||
@attributes[key] = value
|
||||
data[key] = value
|
||||
end
|
||||
|
||||
def session_id
|
||||
""
|
||||
def update
|
||||
@saved_attributes = @attributes
|
||||
end
|
||||
|
||||
def update() end
|
||||
def close() end
|
||||
def delete() @attributes = {} end
|
||||
def delete
|
||||
@attributes = nil
|
||||
end
|
||||
|
||||
def close
|
||||
update
|
||||
delete
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
# Essentially generates a modified Tempfile object similar to the object
|
||||
# you'd get from the standard library CGI module in a multipart
|
||||
# request. This means you can use an ActionController::TestUploadedFile
|
||||
|
||||
@@ -316,7 +316,7 @@ module HTML #:nodoc:
|
||||
s = "<#{@name}"
|
||||
@attributes.each do |k,v|
|
||||
s << " #{k}"
|
||||
s << "='#{v.gsub(/'/,"\\\\'")}'" if String === v
|
||||
s << "=\"#{v}\"" if String === v
|
||||
end
|
||||
s << " /" if @closing == :self
|
||||
s << ">"
|
||||
|
||||
@@ -201,7 +201,8 @@ module HTML
|
||||
|
||||
|
||||
# An invalid selector.
|
||||
class InvalidSelectorError < StandardError ; end
|
||||
class InvalidSelectorError < StandardError #:nodoc:
|
||||
end
|
||||
|
||||
|
||||
class << self
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
module ActionPack #:nodoc:
|
||||
module VERSION #:nodoc:
|
||||
MAJOR = 1
|
||||
MINOR = 12
|
||||
TINY = 5
|
||||
MINOR = 13
|
||||
TINY = 0
|
||||
|
||||
STRING = [MAJOR, MINOR, TINY].join('.')
|
||||
end
|
||||
|
||||
@@ -85,8 +85,10 @@ module ActionView
|
||||
# <%= error_message_on "post", "title", "Title simply ", " (or it won't work)", "inputError" %> =>
|
||||
# <div class="inputError">Title simply can't be empty (or it won't work)</div>
|
||||
def error_message_on(object, method, prepend_text = "", append_text = "", css_class = "formError")
|
||||
if errors = instance_variable_get("@#{object}").errors.on(method)
|
||||
if (obj = instance_variable_get("@#{object}")) && (errors = obj.errors.on(method))
|
||||
content_tag("div", "#{prepend_text}#{errors.is_a?(Array) ? errors.first : errors}#{append_text}", :class => css_class)
|
||||
else
|
||||
''
|
||||
end
|
||||
end
|
||||
|
||||
@@ -167,6 +169,8 @@ module ActionView
|
||||
to_date_select_tag(options)
|
||||
when :datetime, :timestamp
|
||||
to_datetime_select_tag(options)
|
||||
when :time
|
||||
to_time_select_tag(options)
|
||||
when :boolean
|
||||
to_boolean_select_tag(options)
|
||||
end
|
||||
@@ -208,6 +212,15 @@ module ActionView
|
||||
end
|
||||
end
|
||||
|
||||
alias_method :to_time_select_tag_without_error_wrapping, :to_time_select_tag
|
||||
def to_time_select_tag(options = {})
|
||||
if object.respond_to?("errors") && object.errors.respond_to?("on")
|
||||
error_wrapping(to_time_select_tag_without_error_wrapping(options), object.errors.on(@method_name))
|
||||
else
|
||||
to_time_select_tag_without_error_wrapping(options)
|
||||
end
|
||||
end
|
||||
|
||||
def error_wrapping(html_tag, has_error)
|
||||
has_error ? Base.field_error_proc.call(html_tag, self) : html_tag
|
||||
end
|
||||
|
||||
@@ -3,20 +3,36 @@ require File.dirname(__FILE__) + '/url_helper'
|
||||
require File.dirname(__FILE__) + '/tag_helper'
|
||||
|
||||
module ActionView
|
||||
module Helpers
|
||||
# Provides methods for linking a HTML page together with other assets, such as javascripts, stylesheets, and feeds.
|
||||
module Helpers #:nodoc:
|
||||
# Provides methods for linking an HTML page together with other assets such
|
||||
# as images, javascripts, stylesheets, and feeds. You can direct Rails to
|
||||
# link to assets from a dedicated assets server by setting ActionController::Base.asset_host
|
||||
# in your environment.rb. These methods do not verify the assets exist before
|
||||
# linking to them.
|
||||
#
|
||||
# ActionController::Base.asset_host = "http://assets.example.com"
|
||||
# image_tag("rails.png")
|
||||
# => <img src="http://assets.example.com/images/rails.png" alt="Rails" />
|
||||
# stylesheet_include_tag("application")
|
||||
# => <link href="http://assets.example.com/stylesheets/application.css" media="screen" rel="Stylesheet" type="text/css" />
|
||||
module AssetTagHelper
|
||||
# Returns a link tag that browsers and news readers can use to auto-detect a RSS or ATOM feed for this page. The +type+ can
|
||||
# either be <tt>:rss</tt> (default) or <tt>:atom</tt> and the +options+ follow the url_for style of declaring a link target.
|
||||
# Returns a link tag that browsers and news readers can use to auto-detect
|
||||
# an RSS or ATOM feed. The +type+ can either be <tt>:rss</tt> (default) or
|
||||
# <tt>:atom</tt>. Control the link options in url_for format using the
|
||||
# +url_options+. You can modify the LINK tag itself in +tag_options+.
|
||||
#
|
||||
# Examples:
|
||||
# auto_discovery_link_tag # =>
|
||||
# Tag Options:
|
||||
# * <tt>:rel</tt> - Specify the relation of this link, defaults to "alternate"
|
||||
# * <tt>:type</tt> - Override the auto-generated mime type
|
||||
# * <tt>:title</tt> - Specify the title of the link, defaults to the +type+
|
||||
#
|
||||
# auto_discovery_link_tag # =>
|
||||
# <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.curenthost.com/controller/action" />
|
||||
# auto_discovery_link_tag(:atom) # =>
|
||||
# auto_discovery_link_tag(:atom) # =>
|
||||
# <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.curenthost.com/controller/action" />
|
||||
# auto_discovery_link_tag(:rss, {:action => "feed"}) # =>
|
||||
# auto_discovery_link_tag(:rss, {:action => "feed"}) # =>
|
||||
# <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.curenthost.com/controller/feed" />
|
||||
# auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "My RSS"}) # =>
|
||||
# auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "My RSS"}) # =>
|
||||
# <link rel="alternate" type="application/rss+xml" title="My RSS" href="http://www.curenthost.com/controller/feed" />
|
||||
def auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {})
|
||||
tag(
|
||||
@@ -28,9 +44,14 @@ module ActionView
|
||||
)
|
||||
end
|
||||
|
||||
# Returns path to a javascript asset. Example:
|
||||
# Computes the path to a javascript asset in the public javascripts directory.
|
||||
# If the +source+ filename has no extension, .js will be appended.
|
||||
# Full paths from the document root will be passed through.
|
||||
# Used internally by javascript_include_tag to build the script path.
|
||||
#
|
||||
# javascript_path "xmlhr" # => /javascripts/xmlhr.js
|
||||
# javascript_path "dir/xmlhr.js" # => /javascripts/dir/xmlhr.js
|
||||
# javascript_path "/dir/xmlhr" # => /dir/xmlhr.js
|
||||
def javascript_path(source)
|
||||
compute_public_path(source, 'javascripts', 'js')
|
||||
end
|
||||
@@ -38,7 +59,15 @@ module ActionView
|
||||
JAVASCRIPT_DEFAULT_SOURCES = ['prototype', 'effects', 'dragdrop', 'controls'] unless const_defined?(:JAVASCRIPT_DEFAULT_SOURCES)
|
||||
@@javascript_default_sources = JAVASCRIPT_DEFAULT_SOURCES.dup
|
||||
|
||||
# Returns a script include tag per source given as argument. Examples:
|
||||
# Returns an html script tag for each of the +sources+ provided. You
|
||||
# can pass in the filename (.js extension is optional) of javascript files
|
||||
# that exist in your public/javascripts directory for inclusion into the
|
||||
# current page or you can pass the full path relative to your document
|
||||
# root. To include the Prototype and Scriptaculous javascript libraries in
|
||||
# your application, pass <tt>:defaults</tt> as the source. When using
|
||||
# :defaults, if an <tt>application.js</tt> file exists in your public
|
||||
# javascripts directory, it will be included as well. You can modify the
|
||||
# html attributes of the script tag by passing a hash as the last argument.
|
||||
#
|
||||
# javascript_include_tag "xmlhr" # =>
|
||||
# <script type="text/javascript" src="/javascripts/xmlhr.js"></script>
|
||||
@@ -52,11 +81,6 @@ module ActionView
|
||||
# <script type="text/javascript" src="/javascripts/effects.js"></script>
|
||||
# ...
|
||||
# <script type="text/javascript" src="/javascripts/application.js"></script> *see below
|
||||
#
|
||||
# If there's an <tt>application.js</tt> file in your <tt>public/javascripts</tt> directory,
|
||||
# <tt>javascript_include_tag :defaults</tt> will automatically include it. This file
|
||||
# facilitates the inclusion of small snippets of JavaScript code, along the lines of
|
||||
# <tt>controllers/application.rb</tt> and <tt>helpers/application_helper.rb</tt>.
|
||||
def javascript_include_tag(*sources)
|
||||
options = sources.last.is_a?(Hash) ? sources.pop.stringify_keys : { }
|
||||
|
||||
@@ -69,18 +93,16 @@ module ActionView
|
||||
sources << "application" if defined?(RAILS_ROOT) && File.exists?("#{RAILS_ROOT}/public/javascripts/application.js")
|
||||
end
|
||||
|
||||
sources.collect { |source|
|
||||
sources.collect do |source|
|
||||
source = javascript_path(source)
|
||||
content_tag("script", "", { "type" => "text/javascript", "src" => source }.merge(options))
|
||||
}.join("\n")
|
||||
end.join("\n")
|
||||
end
|
||||
|
||||
# Register one or more additional JavaScript files to be included when
|
||||
#
|
||||
# javascript_include_tag :defaults
|
||||
#
|
||||
# is called. This method is intended to be called only from plugin initialization
|
||||
# to register extra .js files the plugin installed in <tt>public/javascripts</tt>.
|
||||
# <tt>javascript_include_tag :defaults</tt> is called. This method is
|
||||
# only intended to be called from plugin initialization to register additional
|
||||
# .js files that the plugin installed in <tt>public/javascripts</tt>.
|
||||
def self.register_javascript_include_default(*sources)
|
||||
@@javascript_default_sources.concat(sources)
|
||||
end
|
||||
@@ -89,14 +111,21 @@ module ActionView
|
||||
@@javascript_default_sources = JAVASCRIPT_DEFAULT_SOURCES.dup
|
||||
end
|
||||
|
||||
# Returns path to a stylesheet asset. Example:
|
||||
# Computes the path to a stylesheet asset in the public stylesheets directory.
|
||||
# If the +source+ filename has no extension, .css will be appended.
|
||||
# Full paths from the document root will be passed through.
|
||||
# Used internally by stylesheet_link_tag to build the stylesheet path.
|
||||
#
|
||||
# stylesheet_path "style" # => /stylesheets/style.css
|
||||
# stylesheet_path "dir/style.css" # => /stylesheets/dir/style.css
|
||||
# stylesheet_path "/dir/style.css" # => /dir/style.css
|
||||
def stylesheet_path(source)
|
||||
compute_public_path(source, 'stylesheets', 'css')
|
||||
end
|
||||
|
||||
# Returns a css link tag per source given as argument. Examples:
|
||||
# Returns a stylesheet link tag for the sources specified as arguments. If
|
||||
# you don't specify an extension, .css will be appended automatically.
|
||||
# You can modify the link attributes by passing a hash as the last argument.
|
||||
#
|
||||
# stylesheet_link_tag "style" # =>
|
||||
# <link href="/stylesheets/style.css" media="screen" rel="Stylesheet" type="text/css" />
|
||||
@@ -109,18 +138,20 @@ module ActionView
|
||||
# <link href="/css/stylish.css" media="screen" rel="Stylesheet" type="text/css" />
|
||||
def stylesheet_link_tag(*sources)
|
||||
options = sources.last.is_a?(Hash) ? sources.pop.stringify_keys : { }
|
||||
sources.collect { |source|
|
||||
sources.collect do |source|
|
||||
source = stylesheet_path(source)
|
||||
tag("link", { "rel" => "Stylesheet", "type" => "text/css", "media" => "screen", "href" => source }.merge(options))
|
||||
}.join("\n")
|
||||
end.join("\n")
|
||||
end
|
||||
|
||||
# Returns path to an image asset. Example:
|
||||
# Computes the path to an image asset in the public images directory.
|
||||
# Full paths from the document root will be passed through.
|
||||
# Used internally by image_tag to build the image path. Passing
|
||||
# a filename without an extension is deprecated.
|
||||
#
|
||||
# The +src+ can be supplied as a...
|
||||
# * full path, like "/my_images/image.gif"
|
||||
# * file name, like "rss.gif", that gets expanded to "/images/rss.gif"
|
||||
# * file name without extension, like "logo", that gets expanded to "/images/logo.png"
|
||||
# image_path("edit.png") # => /images/edit.png
|
||||
# image_path("icons/edit.png") # => /images/icons/edit.png
|
||||
# image_path("/icons/edit.png") # => /icons/edit.png
|
||||
def image_path(source)
|
||||
unless (source.split("/").last || source).include?(".") || source.blank?
|
||||
ActiveSupport::Deprecation.warn(
|
||||
@@ -133,15 +164,24 @@ module ActionView
|
||||
compute_public_path(source, 'images', 'png')
|
||||
end
|
||||
|
||||
# Returns an image tag converting the +options+ into html options on the tag, but with these special cases:
|
||||
# Returns an html image tag for the +source+. The +source+ can be a full
|
||||
# path or a file that exists in your public images directory. Note that
|
||||
# specifying a filename without the extension is now deprecated in Rails.
|
||||
# You can add html attributes using the +options+. The +options+ supports
|
||||
# two additional keys for convienence and conformance:
|
||||
#
|
||||
# * <tt>:alt</tt> - If no alt text is given, the file name part of the +src+ is used (capitalized and without the extension)
|
||||
# * <tt>:size</tt> - Supplied as "XxY", so "30x45" becomes width="30" and height="45"
|
||||
# * <tt>:alt</tt> - If no alt text is given, the file name part of the
|
||||
# +source+ is used (capitalized and without the extension)
|
||||
# * <tt>:size</tt> - Supplied as "{Width}x{Height}", so "30x45" becomes
|
||||
# width="30" and height="45". <tt>:size</tt> will be ignored if the
|
||||
# value is not in the correct format.
|
||||
#
|
||||
# The +src+ can be supplied as a...
|
||||
# * full path, like "/my_images/image.gif"
|
||||
# * file name, like "rss.gif", that gets expanded to "/images/rss.gif"
|
||||
# * file name without extension, like "logo", that gets expanded to "/images/logo.png"
|
||||
# image_tag("icon.png") # =>
|
||||
# <img src="/images/icon.png" alt="Icon" />
|
||||
# image_tag("icon.png", :size => "16x10", :alt => "Edit Entry") # =>
|
||||
# <img src="/images/icon.png" width="16" height="10" alt="Edit Entry" />
|
||||
# image_tag("/icons/icon.gif", :size => "16x16") # =>
|
||||
# <img src="/icons/icon.gif" width="16" height="16" alt="Icon" />
|
||||
def image_tag(source, options = {})
|
||||
options.symbolize_keys!
|
||||
|
||||
@@ -149,8 +189,8 @@ module ActionView
|
||||
options[:alt] ||= File.basename(options[:src], '.*').split('.').first.capitalize
|
||||
|
||||
if options[:size]
|
||||
options[:width], options[:height] = options[:size].split("x")
|
||||
options.delete :size
|
||||
options[:width], options[:height] = options[:size].split("x") if options[:size] =~ %r{^\d+x\d+$}
|
||||
options.delete(:size)
|
||||
end
|
||||
|
||||
tag("img", options)
|
||||
@@ -163,7 +203,7 @@ module ActionView
|
||||
unless source =~ %r{^[-a-z]+://}
|
||||
source = "/#{dir}/#{source}" unless source[0] == ?/
|
||||
asset_id = rails_asset_id(source)
|
||||
source << '?' + asset_id if defined?(RAILS_ROOT) and not asset_id.blank?
|
||||
source << '?' + asset_id if defined?(RAILS_ROOT) && !asset_id.blank?
|
||||
source = "#{ActionController::Base.asset_host}#{@controller.request.relative_url_root}#{source}"
|
||||
end
|
||||
source
|
||||
|
||||
@@ -62,7 +62,7 @@ module ActionView
|
||||
when 40..59 then 'less than a minute'
|
||||
else '1 minute'
|
||||
end
|
||||
|
||||
|
||||
when 2..44 then "#{distance_in_minutes} minutes"
|
||||
when 45..89 then 'about 1 hour'
|
||||
when 90..1439 then "about #{(distance_in_minutes.to_f / 60.0).round} hours"
|
||||
@@ -74,12 +74,12 @@ module ActionView
|
||||
else "over #{(distance_in_minutes / 525960).round} years"
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
# Like distance_of_time_in_words, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.
|
||||
def time_ago_in_words(from_time, include_seconds = false)
|
||||
distance_of_time_in_words(from_time, Time.now, include_seconds)
|
||||
end
|
||||
|
||||
|
||||
alias_method :distance_of_time_in_words_to_now, :time_ago_in_words
|
||||
|
||||
# Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute (identified by
|
||||
@@ -108,6 +108,19 @@ module ActionView
|
||||
InstanceTag.new(object_name, method, self, nil, options.delete(:object)).to_date_select_tag(options)
|
||||
end
|
||||
|
||||
# Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a specified
|
||||
# time-based attribute (identified by +method+) on an object assigned to the template (identified by +object+).
|
||||
# You can include the seconds with <tt>:include_seconds</tt>.
|
||||
# Examples:
|
||||
#
|
||||
# time_select("post", "sunrise")
|
||||
# time_select("post", "start_time", :include_seconds => true)
|
||||
#
|
||||
# The selects are prepared for multi-parameter assignment to an Active Record object.
|
||||
def time_select(object_name, method, options = {})
|
||||
InstanceTag.new(object_name, method, self, nil, options.delete(:object)).to_time_select_tag(options)
|
||||
end
|
||||
|
||||
# Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a specified datetime-based
|
||||
# attribute (identified by +method+) on an object assigned to the template (identified by +object+). Examples:
|
||||
#
|
||||
@@ -119,36 +132,55 @@ module ActionView
|
||||
InstanceTag.new(object_name, method, self, nil, options.delete(:object)).to_datetime_select_tag(options)
|
||||
end
|
||||
|
||||
# Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+.
|
||||
def select_date(date = Date.today, options = {})
|
||||
select_year(date, options) + select_month(date, options) + select_day(date, options)
|
||||
end
|
||||
|
||||
# Returns a set of html select-tags (one for year, month, day, hour, and minute) pre-selected with the +datetime+.
|
||||
def select_datetime(datetime = Time.now, options = {})
|
||||
select_year(datetime, options) + select_month(datetime, options) + select_day(datetime, options) +
|
||||
select_hour(datetime, options) + select_minute(datetime, options)
|
||||
# It's also possible to explicitly set the order of the tags using the <tt>:order</tt> option with an array of
|
||||
# symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not supply a Symbol, it
|
||||
# will be appened onto the <tt>:order</tt> passed in. You can also add <tt>:date_separator</tt> and <tt>:time_separator</tt>
|
||||
# keys to the +options+ to control visual display of the elements.
|
||||
def select_datetime(datetime = Time.now, options = {})
|
||||
separator = options[:datetime_separator] || ''
|
||||
select_date(datetime, options) + separator + select_time(datetime, options)
|
||||
end
|
||||
|
||||
# Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+.
|
||||
# It's possible to explicitly set the order of the tags using the <tt>:order</tt> option with an array of
|
||||
# symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not supply a Symbol, it
|
||||
# will be appened onto the <tt>:order</tt> passed in.
|
||||
def select_date(date = Date.today, options = {})
|
||||
options[:order] ||= []
|
||||
[:year, :month, :day].each { |o| options[:order].push(o) unless options[:order].include?(o) }
|
||||
|
||||
select_date = ''
|
||||
options[:order].each do |o|
|
||||
select_date << self.send("select_#{o}", date, options)
|
||||
end
|
||||
select_date
|
||||
end
|
||||
|
||||
# Returns a set of html select-tags (one for hour and minute)
|
||||
# You can set <tt>:add_separator</tt> key to format the output.
|
||||
def select_time(datetime = Time.now, options = {})
|
||||
h = select_hour(datetime, options) + select_minute(datetime, options) + (options[:include_seconds] ? select_second(datetime, options) : '')
|
||||
separator = options[:time_separator] || ''
|
||||
select_hour(datetime, options) + separator + select_minute(datetime, options) + (options[:include_seconds] ? separator + select_second(datetime, options) : '')
|
||||
end
|
||||
|
||||
# Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.
|
||||
# The <tt>second</tt> can also be substituted for a second number.
|
||||
# Override the field name using the <tt>:field_name</tt> option, 'second' by default.
|
||||
def select_second(datetime, options = {})
|
||||
second_options = []
|
||||
|
||||
0.upto(59) do |second|
|
||||
second_options << ((datetime && (datetime.kind_of?(Fixnum) ? datetime : datetime.sec) == second) ?
|
||||
%(<option value="#{leading_zero_on_single_digits(second)}" selected="selected">#{leading_zero_on_single_digits(second)}</option>\n) :
|
||||
%(<option value="#{leading_zero_on_single_digits(second)}">#{leading_zero_on_single_digits(second)}</option>\n)
|
||||
)
|
||||
val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.sec) : ''
|
||||
if options[:use_hidden]
|
||||
options[:include_seconds] ? hidden_html(options[:field_name] || 'second', val, options) : ''
|
||||
else
|
||||
second_options = []
|
||||
0.upto(59) do |second|
|
||||
second_options << ((val == second) ?
|
||||
%(<option value="#{leading_zero_on_single_digits(second)}" selected="selected">#{leading_zero_on_single_digits(second)}</option>\n) :
|
||||
%(<option value="#{leading_zero_on_single_digits(second)}">#{leading_zero_on_single_digits(second)}</option>\n)
|
||||
)
|
||||
end
|
||||
select_html(options[:field_name] || 'second', second_options, options)
|
||||
end
|
||||
|
||||
select_html(options[:field_name] || 'second', second_options, options[:prefix], options[:include_blank], options[:discard_type], options[:disabled])
|
||||
end
|
||||
|
||||
# Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
|
||||
@@ -156,84 +188,100 @@ module ActionView
|
||||
# The <tt>minute</tt> can also be substituted for a minute number.
|
||||
# Override the field name using the <tt>:field_name</tt> option, 'minute' by default.
|
||||
def select_minute(datetime, options = {})
|
||||
minute_options = []
|
||||
|
||||
0.step(59, options[:minute_step] || 1) do |minute|
|
||||
minute_options << ((datetime && (datetime.kind_of?(Fixnum) ? datetime : datetime.min) == minute) ?
|
||||
%(<option value="#{leading_zero_on_single_digits(minute)}" selected="selected">#{leading_zero_on_single_digits(minute)}</option>\n) :
|
||||
%(<option value="#{leading_zero_on_single_digits(minute)}">#{leading_zero_on_single_digits(minute)}</option>\n)
|
||||
)
|
||||
end
|
||||
|
||||
select_html(options[:field_name] || 'minute', minute_options, options[:prefix], options[:include_blank], options[:discard_type], options[:disabled])
|
||||
val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.min) : ''
|
||||
if options[:use_hidden]
|
||||
hidden_html(options[:field_name] || 'minute', val, options)
|
||||
else
|
||||
minute_options = []
|
||||
0.step(59, options[:minute_step] || 1) do |minute|
|
||||
minute_options << ((val == minute) ?
|
||||
%(<option value="#{leading_zero_on_single_digits(minute)}" selected="selected">#{leading_zero_on_single_digits(minute)}</option>\n) :
|
||||
%(<option value="#{leading_zero_on_single_digits(minute)}">#{leading_zero_on_single_digits(minute)}</option>\n)
|
||||
)
|
||||
end
|
||||
select_html(options[:field_name] || 'minute', minute_options, options)
|
||||
end
|
||||
end
|
||||
|
||||
# Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
|
||||
# The <tt>hour</tt> can also be substituted for a hour number.
|
||||
# Override the field name using the <tt>:field_name</tt> option, 'hour' by default.
|
||||
def select_hour(datetime, options = {})
|
||||
hour_options = []
|
||||
|
||||
0.upto(23) do |hour|
|
||||
hour_options << ((datetime && (datetime.kind_of?(Fixnum) ? datetime : datetime.hour) == hour) ?
|
||||
%(<option value="#{leading_zero_on_single_digits(hour)}" selected="selected">#{leading_zero_on_single_digits(hour)}</option>\n) :
|
||||
%(<option value="#{leading_zero_on_single_digits(hour)}">#{leading_zero_on_single_digits(hour)}</option>\n)
|
||||
)
|
||||
val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.hour) : ''
|
||||
if options[:use_hidden]
|
||||
hidden_html(options[:field_name] || 'hour', val, options)
|
||||
else
|
||||
hour_options = []
|
||||
0.upto(23) do |hour|
|
||||
hour_options << ((val == hour) ?
|
||||
%(<option value="#{leading_zero_on_single_digits(hour)}" selected="selected">#{leading_zero_on_single_digits(hour)}</option>\n) :
|
||||
%(<option value="#{leading_zero_on_single_digits(hour)}">#{leading_zero_on_single_digits(hour)}</option>\n)
|
||||
)
|
||||
end
|
||||
select_html(options[:field_name] || 'hour', hour_options, options)
|
||||
end
|
||||
|
||||
select_html(options[:field_name] || 'hour', hour_options, options[:prefix], options[:include_blank], options[:discard_type], options[:disabled])
|
||||
end
|
||||
|
||||
# Returns a select tag with options for each of the days 1 through 31 with the current day selected.
|
||||
# The <tt>date</tt> can also be substituted for a hour number.
|
||||
# Override the field name using the <tt>:field_name</tt> option, 'day' by default.
|
||||
def select_day(date, options = {})
|
||||
day_options = []
|
||||
|
||||
1.upto(31) do |day|
|
||||
day_options << ((date && (date.kind_of?(Fixnum) ? date : date.day) == day) ?
|
||||
%(<option value="#{day}" selected="selected">#{day}</option>\n) :
|
||||
%(<option value="#{day}">#{day}</option>\n)
|
||||
)
|
||||
val = date ? (date.kind_of?(Fixnum) ? date : date.day) : ''
|
||||
if options[:use_hidden]
|
||||
hidden_html(options[:field_name] || 'day', val, options)
|
||||
else
|
||||
day_options = []
|
||||
1.upto(31) do |day|
|
||||
day_options << ((val == day) ?
|
||||
%(<option value="#{day}" selected="selected">#{day}</option>\n) :
|
||||
%(<option value="#{day}">#{day}</option>\n)
|
||||
)
|
||||
end
|
||||
select_html(options[:field_name] || 'day', day_options, options)
|
||||
end
|
||||
|
||||
select_html(options[:field_name] || 'day', day_options, options[:prefix], options[:include_blank], options[:discard_type], options[:disabled])
|
||||
end
|
||||
|
||||
# Returns a select tag with options for each of the months January through December with the current month selected.
|
||||
# The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are used as values
|
||||
# (what's submitted to the server). It's also possible to use month numbers for the presentation instead of names --
|
||||
# set the <tt>:use_month_numbers</tt> key in +options+ to true for this to happen. If you want both numbers and names,
|
||||
# set the <tt>:add_month_numbers</tt> key in +options+ to true. Examples:
|
||||
# set the <tt>:add_month_numbers</tt> key in +options+ to true. If you would prefer to show month names as abbreviations,
|
||||
# set the <tt>:use_short_month</tt> key in +options+ to true. If you want to use your own month names, set the
|
||||
# <tt>:use_month_names</tt> key in +options+ to an array of 12 month names.
|
||||
#
|
||||
# Examples:
|
||||
#
|
||||
# select_month(Date.today) # Will use keys like "January", "March"
|
||||
# select_month(Date.today, :use_month_numbers => true) # Will use keys like "1", "3"
|
||||
# select_month(Date.today, :add_month_numbers => true) # Will use keys like "1 - January", "3 - March"
|
||||
# select_month(Date.today, :use_short_month => true) # Will use keys like "Jan", "Mar"
|
||||
# select_month(Date.today, :use_month_names => %w(Januar Februar Marts ...)) # Will use keys like "Januar", "Marts"
|
||||
#
|
||||
# Override the field name using the <tt>:field_name</tt> option, 'month' by default.
|
||||
#
|
||||
# If you would prefer to show month names as abbreviations, set the
|
||||
# <tt>:use_short_month</tt> key in +options+ to true.
|
||||
def select_month(date, options = {})
|
||||
month_options = []
|
||||
month_names = options[:use_short_month] ? Date::ABBR_MONTHNAMES : Date::MONTHNAMES
|
||||
val = date ? (date.kind_of?(Fixnum) ? date : date.month) : ''
|
||||
if options[:use_hidden]
|
||||
hidden_html(options[:field_name] || 'month', val, options)
|
||||
else
|
||||
month_options = []
|
||||
month_names = options[:use_month_names] || (options[:use_short_month] ? Date::ABBR_MONTHNAMES : Date::MONTHNAMES)
|
||||
month_names.unshift(nil) if month_names.size < 13
|
||||
1.upto(12) do |month_number|
|
||||
month_name = if options[:use_month_numbers]
|
||||
month_number
|
||||
elsif options[:add_month_numbers]
|
||||
month_number.to_s + ' - ' + month_names[month_number]
|
||||
else
|
||||
month_names[month_number]
|
||||
end
|
||||
|
||||
1.upto(12) do |month_number|
|
||||
month_name = if options[:use_month_numbers]
|
||||
month_number
|
||||
elsif options[:add_month_numbers]
|
||||
month_number.to_s + ' - ' + month_names[month_number]
|
||||
else
|
||||
month_names[month_number]
|
||||
month_options << ((val == month_number) ?
|
||||
%(<option value="#{month_number}" selected="selected">#{month_name}</option>\n) :
|
||||
%(<option value="#{month_number}">#{month_name}</option>\n)
|
||||
)
|
||||
end
|
||||
|
||||
month_options << ((date && (date.kind_of?(Fixnum) ? date : date.month) == month_number) ?
|
||||
%(<option value="#{month_number}" selected="selected">#{month_name}</option>\n) :
|
||||
%(<option value="#{month_number}">#{month_name}</option>\n)
|
||||
)
|
||||
select_html(options[:field_name] || 'month', month_options, options)
|
||||
end
|
||||
|
||||
select_html(options[:field_name] || 'month', month_options, options[:prefix], options[:include_blank], options[:discard_type], options[:disabled])
|
||||
end
|
||||
|
||||
# Returns a select tag with options for each of the five years on each side of the current, which is selected. The five year radius
|
||||
@@ -243,37 +291,51 @@ module ActionView
|
||||
#
|
||||
# select_year(Date.today, :start_year => 1992, :end_year => 2007) # ascending year values
|
||||
# select_year(Date.today, :start_year => 2005, :end_year => 1900) # descending year values
|
||||
# select_year(2006, :start_year => 2000, :end_year => 2010)
|
||||
#
|
||||
# Override the field name using the <tt>:field_name</tt> option, 'year' by default.
|
||||
def select_year(date, options = {})
|
||||
year_options = []
|
||||
y = date ? (date.kind_of?(Fixnum) ? (y = (date == 0) ? Date.today.year : date) : date.year) : Date.today.year
|
||||
val = date ? (date.kind_of?(Fixnum) ? date : date.year) : ''
|
||||
if options[:use_hidden]
|
||||
hidden_html(options[:field_name] || 'year', val, options)
|
||||
else
|
||||
year_options = []
|
||||
y = date ? (date.kind_of?(Fixnum) ? (y = (date == 0) ? Date.today.year : date) : date.year) : Date.today.year
|
||||
|
||||
start_year, end_year = (options[:start_year] || y-5), (options[:end_year] || y+5)
|
||||
step_val = start_year < end_year ? 1 : -1
|
||||
|
||||
start_year.step(end_year, step_val) do |year|
|
||||
year_options << ((date && (date.kind_of?(Fixnum) ? date : date.year) == year) ?
|
||||
%(<option value="#{year}" selected="selected">#{year}</option>\n) :
|
||||
%(<option value="#{year}">#{year}</option>\n)
|
||||
)
|
||||
start_year, end_year = (options[:start_year] || y-5), (options[:end_year] || y+5)
|
||||
step_val = start_year < end_year ? 1 : -1
|
||||
start_year.step(end_year, step_val) do |year|
|
||||
year_options << ((val == year) ?
|
||||
%(<option value="#{year}" selected="selected">#{year}</option>\n) :
|
||||
%(<option value="#{year}">#{year}</option>\n)
|
||||
)
|
||||
end
|
||||
select_html(options[:field_name] || 'year', year_options, options)
|
||||
end
|
||||
|
||||
select_html(options[:field_name] || 'year', year_options, options[:prefix], options[:include_blank], options[:discard_type], options[:disabled])
|
||||
end
|
||||
|
||||
private
|
||||
def select_html(type, options, prefix = nil, include_blank = false, discard_type = false, disabled = false)
|
||||
select_html = %(<select name="#{prefix || DEFAULT_PREFIX})
|
||||
select_html << "[#{type}]" unless discard_type
|
||||
select_html << %(")
|
||||
select_html << %( disabled="disabled") if disabled
|
||||
|
||||
def select_html(type, html_options, options)
|
||||
name_and_id_from_options(options, type)
|
||||
select_html = %(<select id="#{options[:id]}" name="#{options[:name]}")
|
||||
select_html << %( disabled="disabled") if options[:disabled]
|
||||
select_html << %(>\n)
|
||||
select_html << %(<option value=""></option>\n) if include_blank
|
||||
select_html << options.to_s
|
||||
select_html << %(<option value=""></option>\n) if options[:include_blank]
|
||||
select_html << html_options.to_s
|
||||
select_html << "</select>\n"
|
||||
end
|
||||
|
||||
def hidden_html(type, value, options)
|
||||
name_and_id_from_options(options, type)
|
||||
hidden_html = %(<input type="hidden" id="#{options[:id]}" name="#{options[:name]}" value="#{value}" />\n)
|
||||
end
|
||||
|
||||
def name_and_id_from_options(options, type)
|
||||
options[:name] = (options[:prefix] || DEFAULT_PREFIX) + (options[:discard_type] ? '' : "[#{type}]")
|
||||
options[:id] = options[:name].gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '')
|
||||
end
|
||||
|
||||
def leading_zero_on_single_digits(number)
|
||||
number > 9 ? number : "0#{number}"
|
||||
end
|
||||
@@ -283,45 +345,71 @@ module ActionView
|
||||
include DateHelper
|
||||
|
||||
def to_date_select_tag(options = {})
|
||||
defaults = { :discard_type => true }
|
||||
options = defaults.merge(options)
|
||||
options_with_prefix = Proc.new { |position| options.merge(:prefix => "#{@object_name}[#{@method_name}(#{position}i)]") }
|
||||
value = value(object)
|
||||
date = options[:include_blank] ? (value || 0) : (value || Date.today)
|
||||
date_or_time_select options.merge(:discard_hour => true)
|
||||
end
|
||||
|
||||
date_select = ''
|
||||
options[:order] = [:month, :year, :day] if options[:month_before_year] # For backwards compatibility
|
||||
options[:order] ||= [:year, :month, :day]
|
||||
|
||||
position = {:year => 1, :month => 2, :day => 3}
|
||||
|
||||
discard = {}
|
||||
discard[:year] = true if options[:discard_year]
|
||||
discard[:month] = true if options[:discard_month]
|
||||
discard[:day] = true if options[:discard_day] or options[:discard_month]
|
||||
|
||||
options[:order].each do |param|
|
||||
date_select << self.send("select_#{param}", date, options_with_prefix.call(position[param])) unless discard[param]
|
||||
end
|
||||
|
||||
date_select
|
||||
def to_time_select_tag(options = {})
|
||||
date_or_time_select options.merge(:discard_year => true, :discard_month => true)
|
||||
end
|
||||
|
||||
def to_datetime_select_tag(options = {})
|
||||
defaults = { :discard_type => true }
|
||||
options = defaults.merge(options)
|
||||
options_with_prefix = Proc.new { |position| options.merge(:prefix => "#{@object_name}[#{@method_name}(#{position}i)]") }
|
||||
value = value(object)
|
||||
datetime = options[:include_blank] ? (value || nil) : (value || Time.now)
|
||||
|
||||
datetime_select = select_year(datetime, options_with_prefix.call(1))
|
||||
datetime_select << select_month(datetime, options_with_prefix.call(2)) unless options[:discard_month]
|
||||
datetime_select << select_day(datetime, options_with_prefix.call(3)) unless options[:discard_day] || options[:discard_month]
|
||||
datetime_select << ' — ' + select_hour(datetime, options_with_prefix.call(4)) unless options[:discard_hour]
|
||||
datetime_select << ' : ' + select_minute(datetime, options_with_prefix.call(5)) unless options[:discard_minute] || options[:discard_hour]
|
||||
|
||||
datetime_select
|
||||
date_or_time_select options
|
||||
end
|
||||
|
||||
private
|
||||
def date_or_time_select(options)
|
||||
defaults = { :discard_type => true }
|
||||
options = defaults.merge(options)
|
||||
datetime = value(object)
|
||||
datetime ||= Time.now unless options[:include_blank]
|
||||
|
||||
position = { :year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6 }
|
||||
|
||||
order = (options[:order] ||= [:year, :month, :day])
|
||||
|
||||
# Discard explicit and implicit by not being included in the :order
|
||||
discard = {}
|
||||
discard[:year] = true if options[:discard_year] or !order.include?(:year)
|
||||
discard[:month] = true if options[:discard_month] or !order.include?(:month)
|
||||
discard[:day] = true if options[:discard_day] or discard[:month] or !order.include?(:day)
|
||||
discard[:hour] = true if options[:discard_hour]
|
||||
discard[:minute] = true if options[:discard_minute] or discard[:hour]
|
||||
discard[:second] = true unless options[:include_seconds] && !discard[:minute]
|
||||
|
||||
# Maintain valid dates by including hidden fields for discarded elements
|
||||
[:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
|
||||
# Ensure proper ordering of :hour, :minute and :second
|
||||
[:hour, :minute, :second].each { |o| order.delete(o); order.push(o) }
|
||||
|
||||
date_or_time_select = ''
|
||||
order.reverse.each do |param|
|
||||
# Send hidden fields for discarded elements once output has started
|
||||
# This ensures AR can reconstruct valid dates using ParseDate
|
||||
next if discard[param] && date_or_time_select.empty?
|
||||
|
||||
date_or_time_select.insert(0, self.send("select_#{param}", datetime, options_with_prefix(position[param], options.merge(:use_hidden => discard[param]))))
|
||||
date_or_time_select.insert(0,
|
||||
case param
|
||||
when :hour then (discard[:year] && discard[:day] ? "" : " — ")
|
||||
when :minute then " : "
|
||||
when :second then options[:include_seconds] ? " : " : ""
|
||||
else ""
|
||||
end)
|
||||
|
||||
end
|
||||
|
||||
date_or_time_select
|
||||
end
|
||||
|
||||
def options_with_prefix(position, options)
|
||||
prefix = "#{@object_name}"
|
||||
if options[:index]
|
||||
prefix << "[#{options[:index]}]"
|
||||
elsif @auto_index
|
||||
prefix << "[#{@auto_index}]"
|
||||
end
|
||||
options.merge(:prefix => "#{prefix}[#{@method_name}(#{position}i)]")
|
||||
end
|
||||
end
|
||||
|
||||
class FormBuilder
|
||||
@@ -329,6 +417,10 @@ module ActionView
|
||||
@template.date_select(@object_name, method, options.merge(:object => @object))
|
||||
end
|
||||
|
||||
def time_select(method, options = {})
|
||||
@template.time_select(@object_name, method, options.merge(:object => @object))
|
||||
end
|
||||
|
||||
def datetime_select(method, options = {})
|
||||
@template.datetime_select(@object_name, method, options.merge(:object => @object))
|
||||
end
|
||||
|
||||
34
actionpack/lib/action_view/helpers/deprecated_helper.rb
Normal file
34
actionpack/lib/action_view/helpers/deprecated_helper.rb
Normal file
@@ -0,0 +1,34 @@
|
||||
module ActionView
|
||||
module Helpers
|
||||
module PrototypeHelper
|
||||
|
||||
def update_element_function(element_id, options = {}, &block)
|
||||
content = escape_javascript(options[:content] || '')
|
||||
content = escape_javascript(capture(&block)) if block
|
||||
|
||||
javascript_function = case (options[:action] || :update)
|
||||
when :update
|
||||
if options[:position]
|
||||
"new Insertion.#{options[:position].to_s.camelize}('#{element_id}','#{content}')"
|
||||
else
|
||||
"$('#{element_id}').innerHTML = '#{content}'"
|
||||
end
|
||||
|
||||
when :empty
|
||||
"$('#{element_id}').innerHTML = ''"
|
||||
|
||||
when :remove
|
||||
"Element.remove('#{element_id}')"
|
||||
|
||||
else
|
||||
raise ArgumentError, "Invalid action, choose one of :update, :remove, :empty"
|
||||
end
|
||||
|
||||
javascript_function << ";\n"
|
||||
options[:binding] ? concat(javascript_function, options[:binding]) : javascript_function
|
||||
end
|
||||
deprecate :update_element_function => "use RJS instead"
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -142,11 +142,13 @@ module ActionView
|
||||
#
|
||||
# Note: This also works for the methods in FormOptionHelper and DateHelper that are designed to work with an object as base.
|
||||
# Like collection_select and datetime_select.
|
||||
def fields_for(object_name, *args, &proc)
|
||||
def fields_for(object_name, *args, &block)
|
||||
raise ArgumentError, "Missing block" unless block_given?
|
||||
options = args.last.is_a?(Hash) ? args.pop : {}
|
||||
object = args.first
|
||||
yield((options[:builder] || FormBuilder).new(object_name, object, self, options, proc))
|
||||
|
||||
builder = options[:builder] || ActionView::Base.default_form_builder
|
||||
yield builder.new(object_name, object, self, options, block)
|
||||
end
|
||||
|
||||
# Returns an input tag of the "text" type tailored for accessing a specified attribute (identified by +method+) on an object
|
||||
@@ -436,4 +438,9 @@ module ActionView
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
class Base
|
||||
cattr_accessor :default_form_builder
|
||||
self.default_form_builder = ::ActionView::Helpers::FormBuilder
|
||||
end
|
||||
end
|
||||
|
||||
@@ -189,9 +189,9 @@ module ActionView
|
||||
# Wrapper for text_field with added AJAX autocompletion functionality.
|
||||
#
|
||||
# In your controller, you'll need to define an action called
|
||||
# auto_complete_for_object_method to respond the AJAX calls,
|
||||
# auto_complete_for to respond the AJAX calls,
|
||||
#
|
||||
# See the RDoc on ActionController::AutoComplete to learn more about this.
|
||||
# See the RDoc on ActionController::Macros::AutoComplete to learn more about this.
|
||||
def text_field_with_auto_complete(object, method, tag_options = {}, completion_options = {})
|
||||
(completion_options[:skip_style] ? "" : auto_complete_stylesheet) +
|
||||
text_field(object, method, tag_options) +
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
|
||||
// (c) 2005 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
|
||||
// (c) 2005 Jon Tirsen (http://www.tirsen.com)
|
||||
// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
|
||||
// (c) 2005, 2006 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
|
||||
// (c) 2005, 2006 Jon Tirsen (http://www.tirsen.com)
|
||||
// Contributors:
|
||||
// Richard Livsey
|
||||
// Rahul Bhargava
|
||||
@@ -473,6 +473,7 @@ Ajax.InPlaceEditor.prototype = {
|
||||
this.element = $(element);
|
||||
|
||||
this.options = Object.extend({
|
||||
paramName: "value",
|
||||
okButton: true,
|
||||
okText: "ok",
|
||||
cancelLink: true,
|
||||
@@ -604,7 +605,7 @@ Ajax.InPlaceEditor.prototype = {
|
||||
var textField = document.createElement("input");
|
||||
textField.obj = this;
|
||||
textField.type = "text";
|
||||
textField.name = "value";
|
||||
textField.name = this.options.paramName;
|
||||
textField.value = text;
|
||||
textField.style.backgroundColor = this.options.highlightcolor;
|
||||
textField.className = 'editor_field';
|
||||
@@ -617,7 +618,7 @@ Ajax.InPlaceEditor.prototype = {
|
||||
this.options.textarea = true;
|
||||
var textArea = document.createElement("textarea");
|
||||
textArea.obj = this;
|
||||
textArea.name = "value";
|
||||
textArea.name = this.options.paramName;
|
||||
textArea.value = this.convertHTMLLineBreaks(text);
|
||||
textArea.rows = this.options.rows;
|
||||
textArea.cols = this.options.cols || 40;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
|
||||
// (c) 2005 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
|
||||
// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
|
||||
// (c) 2005, 2006 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
|
||||
//
|
||||
// script.aculo.us is freely distributable under the terms of an MIT-style license.
|
||||
// For details, see the script.aculo.us web site: http://script.aculo.us/
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
|
||||
// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
|
||||
// Contributors:
|
||||
// Justin Palmer (http://encytemedia.com/)
|
||||
// Mark Pilgrim (http://diveintomark.org/)
|
||||
@@ -10,7 +10,7 @@
|
||||
// converts rgb() and #xxx to #xxxxxx format,
|
||||
// returns self (or first argument) if not convertable
|
||||
String.prototype.parseColor = function() {
|
||||
var color = '#';
|
||||
var color = '#';
|
||||
if(this.slice(0,4) == 'rgb(') {
|
||||
var cols = this.slice(4,this.length-1).split(',');
|
||||
var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
|
||||
@@ -939,8 +939,142 @@ Effect.Fold = function(element) {
|
||||
}}, arguments[1] || {}));
|
||||
};
|
||||
|
||||
Effect.Morph = Class.create();
|
||||
Object.extend(Object.extend(Effect.Morph.prototype, Effect.Base.prototype), {
|
||||
initialize: function(element) {
|
||||
this.element = $(element);
|
||||
if(!this.element) throw(Effect._elementDoesNotExistError);
|
||||
var options = Object.extend({
|
||||
style: ''
|
||||
}, arguments[1] || {});
|
||||
this.start(options);
|
||||
},
|
||||
setup: function(){
|
||||
function parseColor(color){
|
||||
if(!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
|
||||
color = color.parseColor();
|
||||
return $R(0,2).map(function(i){
|
||||
return parseInt( color.slice(i*2+1,i*2+3), 16 )
|
||||
});
|
||||
}
|
||||
this.transforms = this.options.style.parseStyle().map(function(property){
|
||||
var originalValue = this.element.getStyle(property[0]);
|
||||
return $H({
|
||||
style: property[0],
|
||||
originalValue: property[1].unit=='color' ?
|
||||
parseColor(originalValue) : parseFloat(originalValue || 0),
|
||||
targetValue: property[1].unit=='color' ?
|
||||
parseColor(property[1].value) : property[1].value,
|
||||
unit: property[1].unit
|
||||
});
|
||||
}.bind(this)).reject(function(transform){
|
||||
return (
|
||||
(transform.originalValue == transform.targetValue) ||
|
||||
(
|
||||
transform.unit != 'color' &&
|
||||
(isNaN(transform.originalValue) || isNaN(transform.targetValue))
|
||||
)
|
||||
)
|
||||
});
|
||||
},
|
||||
update: function(position) {
|
||||
var style = $H(), value = null;
|
||||
this.transforms.each(function(transform){
|
||||
value = transform.unit=='color' ?
|
||||
$R(0,2).inject('#',function(m,v,i){
|
||||
return m+(Math.round(transform.originalValue[i]+
|
||||
(transform.targetValue[i] - transform.originalValue[i])*position)).toColorPart() }) :
|
||||
transform.originalValue + Math.round(
|
||||
((transform.targetValue - transform.originalValue) * position) * 1000)/1000 + transform.unit;
|
||||
style[transform.style] = value;
|
||||
});
|
||||
this.element.setStyle(style);
|
||||
}
|
||||
});
|
||||
|
||||
Effect.Transform = Class.create();
|
||||
Object.extend(Effect.Transform.prototype, {
|
||||
initialize: function(tracks){
|
||||
this.tracks = [];
|
||||
this.options = arguments[1] || {};
|
||||
this.addTracks(tracks);
|
||||
},
|
||||
addTracks: function(tracks){
|
||||
tracks.each(function(track){
|
||||
var data = $H(track).values().first();
|
||||
this.tracks.push($H({
|
||||
ids: $H(track).keys().first(),
|
||||
effect: Effect.Morph,
|
||||
options: { style: data }
|
||||
}));
|
||||
}.bind(this));
|
||||
return this;
|
||||
},
|
||||
play: function(){
|
||||
return new Effect.Parallel(
|
||||
this.tracks.map(function(track){
|
||||
var elements = [$(track.ids) || $$(track.ids)].flatten();
|
||||
return elements.map(function(e){ return new track.effect(e, Object.extend({ sync:true }, track.options)) });
|
||||
}).flatten(),
|
||||
this.options
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
Element.CSS_PROPERTIES = ['azimuth', 'backgroundAttachment', 'backgroundColor', 'backgroundImage',
|
||||
'backgroundPosition', 'backgroundRepeat', 'borderBottomColor', 'borderBottomStyle',
|
||||
'borderBottomWidth', 'borderCollapse', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth',
|
||||
'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderSpacing', 'borderTopColor',
|
||||
'borderTopStyle', 'borderTopWidth', 'bottom', 'captionSide', 'clear', 'clip', 'color', 'content',
|
||||
'counterIncrement', 'counterReset', 'cssFloat', 'cueAfter', 'cueBefore', 'cursor', 'direction',
|
||||
'display', 'elevation', 'emptyCells', 'fontFamily', 'fontSize', 'fontSizeAdjust', 'fontStretch',
|
||||
'fontStyle', 'fontVariant', 'fontWeight', 'height', 'left', 'letterSpacing', 'lineHeight',
|
||||
'listStyleImage', 'listStylePosition', 'listStyleType', 'marginBottom', 'marginLeft', 'marginRight',
|
||||
'marginTop', 'markerOffset', 'marks', 'maxHeight', 'maxWidth', 'minHeight', 'minWidth', 'opacity',
|
||||
'orphans', 'outlineColor', 'outlineOffset', 'outlineStyle', 'outlineWidth', 'overflowX', 'overflowY',
|
||||
'paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop', 'page', 'pageBreakAfter', 'pageBreakBefore',
|
||||
'pageBreakInside', 'pauseAfter', 'pauseBefore', 'pitch', 'pitchRange', 'position', 'quotes',
|
||||
'richness', 'right', 'size', 'speakHeader', 'speakNumeral', 'speakPunctuation', 'speechRate', 'stress',
|
||||
'tableLayout', 'textAlign', 'textDecoration', 'textIndent', 'textShadow', 'textTransform', 'top',
|
||||
'unicodeBidi', 'verticalAlign', 'visibility', 'voiceFamily', 'volume', 'whiteSpace', 'widows',
|
||||
'width', 'wordSpacing', 'zIndex'];
|
||||
|
||||
Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
|
||||
|
||||
String.prototype.parseStyle = function(){
|
||||
var element = Element.extend(document.createElement('div'));
|
||||
element.innerHTML = '<div style="' + this + '"></div>';
|
||||
var style = element.down().style, styleRules = $H();
|
||||
|
||||
Element.CSS_PROPERTIES.each(function(property){
|
||||
if(style[property]) styleRules[property] = style[property];
|
||||
});
|
||||
|
||||
var result = $H();
|
||||
|
||||
styleRules.each(function(pair){
|
||||
var property = pair[0], value = pair[1], unit = null;
|
||||
|
||||
if(value.parseColor('#zzzzzz') != '#zzzzzz') {
|
||||
value = value.parseColor();
|
||||
unit = 'color';
|
||||
} else if(Element.CSS_LENGTH.test(value))
|
||||
var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/),
|
||||
value = parseFloat(components[1]), unit = (components.length == 3) ? components[2] : null;
|
||||
|
||||
result[property.underscore().dasherize()] = $H({ value:value, unit:unit });
|
||||
}.bind(this));
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
Element.morph = function(element, style) {
|
||||
new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || {}));
|
||||
return element;
|
||||
};
|
||||
|
||||
['setOpacity','getOpacity','getInlineOpacity','forceRerendering','setContentZoom',
|
||||
'collectTextNodes','collectTextNodesIgnoreClass'].each(
|
||||
'collectTextNodes','collectTextNodesIgnoreClass','morph'].each(
|
||||
function(f) { Element.Methods[f] = Element[f]; }
|
||||
);
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -63,7 +63,7 @@ module ActionView
|
||||
# can simulate PUT or DELETE over POST. All specified with <tt>options[:method]</tt>
|
||||
#
|
||||
# Example:
|
||||
# link_to_remote "Destroy", person_url(:id => person), :method => :delete
|
||||
# link_to_remote "Destroy", :url => person_url(:id => person), :method => :delete
|
||||
#
|
||||
# By default, these remote requests are processed asynchronous during
|
||||
# which various JavaScript callbacks can be triggered (for progress
|
||||
@@ -204,81 +204,6 @@ module ActionView
|
||||
tag("input", options[:html], false)
|
||||
end
|
||||
|
||||
# Returns a JavaScript function (or expression) that'll update a DOM
|
||||
# element according to the options passed.
|
||||
#
|
||||
# * <tt>:content</tt>: The content to use for updating. Can be left out
|
||||
# if using block, see example.
|
||||
# * <tt>:action</tt>: Valid options are :update (assumed by default),
|
||||
# :empty, :remove
|
||||
# * <tt>:position</tt> If the :action is :update, you can optionally
|
||||
# specify one of the following positions: :before, :top, :bottom,
|
||||
# :after.
|
||||
#
|
||||
# Examples:
|
||||
# <%= javascript_tag(update_element_function("products",
|
||||
# :position => :bottom, :content => "<p>New product!</p>")) %>
|
||||
#
|
||||
# <% replacement_function = update_element_function("products") do %>
|
||||
# <p>Product 1</p>
|
||||
# <p>Product 2</p>
|
||||
# <% end %>
|
||||
# <%= javascript_tag(replacement_function) %>
|
||||
#
|
||||
# This method can also be used in combination with remote method call
|
||||
# where the result is evaluated afterwards to cause multiple updates on
|
||||
# a page. Example:
|
||||
#
|
||||
# # Calling view
|
||||
# <%= form_remote_tag :url => { :action => "buy" },
|
||||
# :complete => evaluate_remote_response %>
|
||||
# all the inputs here...
|
||||
#
|
||||
# # Controller action
|
||||
# def buy
|
||||
# @product = Product.find(1)
|
||||
# end
|
||||
#
|
||||
# # Returning view
|
||||
# <%= update_element_function(
|
||||
# "cart", :action => :update, :position => :bottom,
|
||||
# :content => "<p>New Product: #{@product.name}</p>")) %>
|
||||
# <% update_element_function("status", :binding => binding) do %>
|
||||
# You've bought a new product!
|
||||
# <% end %>
|
||||
#
|
||||
# Notice how the second call doesn't need to be in an ERb output block
|
||||
# since it uses a block and passes in the binding to render directly.
|
||||
# This trick will however only work in ERb (not Builder or other
|
||||
# template forms).
|
||||
#
|
||||
# See also JavaScriptGenerator and update_page.
|
||||
def update_element_function(element_id, options = {}, &block)
|
||||
content = escape_javascript(options[:content] || '')
|
||||
content = escape_javascript(capture(&block)) if block
|
||||
|
||||
javascript_function = case (options[:action] || :update)
|
||||
when :update
|
||||
if options[:position]
|
||||
"new Insertion.#{options[:position].to_s.camelize}('#{element_id}','#{content}')"
|
||||
else
|
||||
"$('#{element_id}').innerHTML = '#{content}'"
|
||||
end
|
||||
|
||||
when :empty
|
||||
"$('#{element_id}').innerHTML = ''"
|
||||
|
||||
when :remove
|
||||
"Element.remove('#{element_id}')"
|
||||
|
||||
else
|
||||
raise ArgumentError, "Invalid action, choose one of :update, :remove, :empty"
|
||||
end
|
||||
|
||||
javascript_function << ";\n"
|
||||
options[:binding] ? concat(javascript_function, options[:binding]) : javascript_function
|
||||
end
|
||||
|
||||
# Returns 'eval(request.responseText)' which is the JavaScript function
|
||||
# that form_remote_tag can call in :complete to evaluate a multiple
|
||||
# update return document using update_element_function calls.
|
||||
@@ -466,7 +391,7 @@ module ActionView
|
||||
# Returns an object whose <tt>#to_json</tt> evaluates to +code+. Use this to pass a literal JavaScript
|
||||
# expression as an argument to another JavaScriptGenerator method.
|
||||
def literal(code)
|
||||
JavaScriptLiteral.new(code)
|
||||
ActiveSupport::JSON::Variable.new(code.to_s)
|
||||
end
|
||||
|
||||
# Returns a collection reference by finding it through a CSS +pattern+ in the DOM. This collection can then be
|
||||
@@ -542,7 +467,7 @@ module ActionView
|
||||
#
|
||||
# # Replace the DOM element having ID 'person-45' with the
|
||||
# # 'person' partial for the appropriate object.
|
||||
# replace_html 'person-45', :partial => 'person', :object => @person
|
||||
# replace 'person-45', :partial => 'person', :object => @person
|
||||
#
|
||||
# This allows the same partial that is used for the +insert_html+ to
|
||||
# be also used for the input to +replace+ without resorting to
|
||||
@@ -763,13 +688,6 @@ module ActionView
|
||||
end
|
||||
end
|
||||
|
||||
# Bypasses string escaping so you can pass around raw JavaScript
|
||||
class JavaScriptLiteral < String #:nodoc:
|
||||
def to_json
|
||||
to_s
|
||||
end
|
||||
end
|
||||
|
||||
# Converts chained method calls on DOM proxy elements into JavaScript chains
|
||||
class JavaScriptProxy < Builder::BlankSlate #:nodoc:
|
||||
def initialize(generator, root = nil)
|
||||
|
||||
@@ -2,30 +2,48 @@ require 'cgi'
|
||||
require 'erb'
|
||||
|
||||
module ActionView
|
||||
module Helpers
|
||||
# This is poor man's Builder for the rare cases where you need to programmatically make tags but can't use Builder.
|
||||
module Helpers #:nodoc:
|
||||
# Use these methods to generate HTML tags programmatically when you can't use
|
||||
# a Builder. By default, they output XHTML compliant tags.
|
||||
module TagHelper
|
||||
include ERB::Util
|
||||
|
||||
# Examples:
|
||||
# * <tt>tag("br") => <br /></tt>
|
||||
# * <tt>tag("input", { "type" => "text"}) => <input type="text" /></tt>
|
||||
# Returns an empty HTML tag of type +name+ which by default is XHTML
|
||||
# compliant. Setting +open+ to true will create an open tag compatible
|
||||
# with HTML 4.0 and below. Add HTML attributes by passing an attributes
|
||||
# hash to +options+. For attributes with no value like (disabled and
|
||||
# readonly), give it a value of true in the +options+ hash. You can use
|
||||
# symbols or strings for the attribute names.
|
||||
#
|
||||
# tag("br")
|
||||
# # => <br />
|
||||
# tag("br", nil, true)
|
||||
# # => <br>
|
||||
# tag("input", { :type => 'text', :disabled => true })
|
||||
# # => <input type="text" disabled="disabled" />
|
||||
def tag(name, options = nil, open = false)
|
||||
"<#{name}#{tag_options(options.stringify_keys) if options}" + (open ? ">" : " />")
|
||||
"<#{name}#{tag_options(options) if options}" + (open ? ">" : " />")
|
||||
end
|
||||
|
||||
# Examples:
|
||||
# * <tt>content_tag(:p, "Hello world!") => <p>Hello world!</p></tt>
|
||||
# * <tt>content_tag(:div, content_tag(:p, "Hello world!"), :class => "strong") => </tt>
|
||||
# <tt><div class="strong"><p>Hello world!</p></div></tt>
|
||||
# Returns an HTML block tag of type +name+ surrounding the +content+. Add
|
||||
# HTML attributes by passing an attributes hash to +options+. For attributes
|
||||
# with no value like (disabled and readonly), give it a value of true in
|
||||
# the +options+ hash. You can use symbols or strings for the attribute names.
|
||||
#
|
||||
# ERb example:
|
||||
# <% content_tag :div, :class => "strong" do -%>
|
||||
# Hello world!
|
||||
# <% end -%>
|
||||
# content_tag(:p, "Hello world!")
|
||||
# # => <p>Hello world!</p>
|
||||
# content_tag(:div, content_tag(:p, "Hello world!"), :class => "strong")
|
||||
# # => <div class="strong"><p>Hello world!</p></div>
|
||||
# content_tag("select", options, :multiple => true)
|
||||
# # => <select multiple="multiple">...options...</select>
|
||||
#
|
||||
# Will output:
|
||||
# <div class="strong"><p>Hello world!</p></div>
|
||||
# Instead of passing the content as an argument, you can also use a block
|
||||
# in which case, you pass your +options+ as the second parameter.
|
||||
#
|
||||
# <% content_tag :div, :class => "strong" do -%>
|
||||
# Hello world!
|
||||
# <% end -%>
|
||||
# # => <div class="strong"><p>Hello world!</p></div>
|
||||
def content_tag(name, content_or_options_with_block = nil, options = nil, &block)
|
||||
if block_given?
|
||||
options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
|
||||
@@ -37,27 +55,28 @@ module ActionView
|
||||
end
|
||||
end
|
||||
|
||||
# Returns a CDATA section for the given +content+. CDATA sections
|
||||
# Returns a CDATA section with the given +content+. CDATA sections
|
||||
# are used to escape blocks of text containing characters which would
|
||||
# otherwise be recognized as markup. CDATA sections begin with the string
|
||||
# <tt><![CDATA[</tt> and end with (and may not contain) the string
|
||||
# <tt>]]></tt>.
|
||||
# <tt><![CDATA[</tt> and end with (and may not contain) the string <tt>]]></tt>.
|
||||
#
|
||||
# cdata_section("<hello world>")
|
||||
# # => <![CDATA[<hello world>]]>
|
||||
def cdata_section(content)
|
||||
"<![CDATA[#{content}]]>"
|
||||
end
|
||||
|
||||
# Escapes a given string, while leaving any currently escaped entities alone.
|
||||
# Returns the escaped +html+ without affecting existing escaped entities.
|
||||
#
|
||||
# escape_once("1 > 2 & 3")
|
||||
# # => "1 < 2 & 3"
|
||||
#
|
||||
# # => "1 < 2 & 3"
|
||||
def escape_once(html)
|
||||
fix_double_escape(html_escape(html.to_s))
|
||||
end
|
||||
|
||||
private
|
||||
def content_tag_string(name, content, options)
|
||||
tag_options = options ? tag_options(options.stringify_keys) : ""
|
||||
tag_options = options ? tag_options(options) : ""
|
||||
"<#{name}#{tag_options}>#{content}</#{name}>"
|
||||
end
|
||||
|
||||
|
||||
@@ -154,12 +154,10 @@ module ActionView
|
||||
# considered as a linebreak and a <tt><br /></tt> tag is appended. This
|
||||
# method does not remove the newlines from the +text+.
|
||||
def simple_format(text)
|
||||
text = text.gsub(/(\r\n|\n|\r)/, "\n") # lets make them newlines crossplatform
|
||||
text.gsub!(/\n\n+/, "\n\n") # zap dupes
|
||||
text.gsub!(/\n\n/, '</p>\0<p>') # turn two newlines into paragraph
|
||||
text.gsub!(/([^\n])(\n)(?=[^\n])/, '\1\2<br />') # turn single newline into <br />
|
||||
|
||||
content_tag("p", text)
|
||||
content_tag 'p', text.to_s.
|
||||
gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
|
||||
gsub(/\n\n+/, "</p>\n\n<p>"). # 2+ newline -> paragraph
|
||||
gsub(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br
|
||||
end
|
||||
|
||||
# Turns all urls and email addresses into clickable links. The +link+ parameter
|
||||
@@ -256,7 +254,7 @@ module ActionView
|
||||
# html-scanner tokenizer and so its HTML parsing ability is limited by
|
||||
# that of html-scanner.
|
||||
def strip_tags(html)
|
||||
return nil if html.blank?
|
||||
return html if html.blank?
|
||||
if html.index("<")
|
||||
text = ""
|
||||
tokenizer = HTML::Tokenizer.new(html)
|
||||
|
||||
@@ -310,9 +310,15 @@ module ActionView
|
||||
end
|
||||
end
|
||||
|
||||
# Returns true if the current page uri is generated by the +options+ passed.
|
||||
# True if the current request uri was generated by the given +options+.
|
||||
def current_page?(options)
|
||||
CGI.escapeHTML(self.url_for(options)) == @controller.request.request_uri
|
||||
url_string = CGI.escapeHTML(url_for(options))
|
||||
request = @controller.request
|
||||
if url_string =~ /^\w+:\/\//
|
||||
url_string == "#{request.protocol}#{request.host_with_port}#{request.request_uri}"
|
||||
else
|
||||
url_string == request.request_uri
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
@@ -6,16 +6,22 @@ module ActionView
|
||||
|
||||
attr_reader :original_exception
|
||||
|
||||
def initialize(base_path, file_name, assigns, source, original_exception)
|
||||
@base_path, @assigns, @source, @original_exception =
|
||||
base_path, assigns, source, original_exception
|
||||
@file_name = file_name
|
||||
def initialize(base_path, file_path, assigns, source, original_exception)
|
||||
@base_path, @assigns, @source, @original_exception =
|
||||
base_path, assigns.dup, source, original_exception
|
||||
@file_path = file_path
|
||||
|
||||
remove_deprecated_assigns!
|
||||
end
|
||||
|
||||
|
||||
def message
|
||||
original_exception.message
|
||||
ActiveSupport::Deprecation.silence { original_exception.message }
|
||||
end
|
||||
|
||||
|
||||
def clean_backtrace
|
||||
original_exception.clean_backtrace
|
||||
end
|
||||
|
||||
def sub_template_message
|
||||
if @sub_templates
|
||||
"Trace of template inclusion: " +
|
||||
@@ -24,63 +30,81 @@ module ActionView
|
||||
""
|
||||
end
|
||||
end
|
||||
|
||||
def source_extract(indention = 0)
|
||||
source_code = IO.readlines(@file_name)
|
||||
|
||||
start_on_line = [ line_number - SOURCE_CODE_RADIUS - 1, 0 ].max
|
||||
end_on_line = [ line_number + SOURCE_CODE_RADIUS - 1, source_code.length].min
|
||||
|
||||
def source_extract(indentation = 0)
|
||||
return unless num = line_number
|
||||
num = num.to_i
|
||||
|
||||
source_code = IO.readlines(@file_path)
|
||||
|
||||
start_on_line = [ num - SOURCE_CODE_RADIUS - 1, 0 ].max
|
||||
end_on_line = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min
|
||||
|
||||
indent = ' ' * indentation
|
||||
line_counter = start_on_line
|
||||
extract = source_code[start_on_line..end_on_line].collect do |line|
|
||||
|
||||
source_code[start_on_line..end_on_line].sum do |line|
|
||||
line_counter += 1
|
||||
"#{' ' * indention}#{line_counter}: " + line
|
||||
"#{indent}#{line_counter}: #{line}"
|
||||
end
|
||||
|
||||
extract.join
|
||||
end
|
||||
|
||||
def sub_template_of(file_name)
|
||||
def sub_template_of(template_path)
|
||||
@sub_templates ||= []
|
||||
@sub_templates << file_name
|
||||
@sub_templates << template_path
|
||||
end
|
||||
|
||||
|
||||
def line_number
|
||||
if file_name
|
||||
regexp = /#{Regexp.escape File.basename(file_name)}:(\d+)/
|
||||
[@original_exception.message, @original_exception.clean_backtrace].flatten.each do |line|
|
||||
return $1.to_i if regexp =~ line
|
||||
@line_number ||=
|
||||
if file_name
|
||||
regexp = /#{Regexp.escape File.basename(file_name)}:(\d+)/
|
||||
|
||||
$1 if message =~ regexp or clean_backtrace.find { |line| line =~ regexp }
|
||||
end
|
||||
end
|
||||
0
|
||||
end
|
||||
|
||||
|
||||
def file_name
|
||||
stripped = strip_base_path(@file_name)
|
||||
stripped[0] == ?/ ? stripped[1..-1] : stripped
|
||||
stripped = strip_base_path(@file_path)
|
||||
stripped.slice!(0,1) if stripped[0] == ?/
|
||||
stripped
|
||||
end
|
||||
|
||||
|
||||
def to_s
|
||||
"\n\n#{self.class} (#{message}) on line ##{line_number} of #{file_name}:\n" +
|
||||
source_extract + "\n " +
|
||||
original_exception.clean_backtrace.join("\n ") +
|
||||
"\n\n"
|
||||
"\n\n#{self.class} (#{message}) #{source_location}:\n" +
|
||||
"#{source_extract}\n #{clean_backtrace.join("\n ")}\n\n"
|
||||
end
|
||||
|
||||
def backtrace
|
||||
[
|
||||
"On line ##{line_number} of #{file_name}\n\n#{source_extract(4)}\n " +
|
||||
original_exception.clean_backtrace.join("\n ")
|
||||
[
|
||||
"#{source_location.capitalize}\n\n#{source_extract(4)}\n " +
|
||||
clean_backtrace.join("\n ")
|
||||
]
|
||||
end
|
||||
|
||||
private
|
||||
def strip_base_path(file_name)
|
||||
file_name = File.expand_path(file_name).gsub(/^#{Regexp.escape File.expand_path(RAILS_ROOT)}/, '')
|
||||
file_name.gsub(@base_path, "")
|
||||
def remove_deprecated_assigns!
|
||||
ActionController::Base::DEPRECATED_INSTANCE_VARIABLES.each do |ivar|
|
||||
@assigns.delete(ivar)
|
||||
end
|
||||
end
|
||||
|
||||
def strip_base_path(path)
|
||||
File.expand_path(path).
|
||||
gsub(/^#{Regexp.escape File.expand_path(RAILS_ROOT)}/, '').
|
||||
gsub(@base_path, "")
|
||||
end
|
||||
|
||||
def source_location
|
||||
if line_number
|
||||
"on line ##{line_number} of "
|
||||
else
|
||||
'in '
|
||||
end + file_name
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Exception::TraceSubstitutions << [/:in\s+`_run_(html|xml).*'\s*$/, ''] if defined?(Exception::TraceSubstitutions)
|
||||
Exception::TraceSubstitutions << [%r{^\s*#{Regexp.escape RAILS_ROOT}}, '#{RAILS_ROOT}'] if defined?(RAILS_ROOT)
|
||||
if defined?(Exception::TraceSubstitutions)
|
||||
Exception::TraceSubstitutions << [/:in\s+`_run_(html|xml).*'\s*$/, '']
|
||||
Exception::TraceSubstitutions << [%r{^\s*#{Regexp.escape RAILS_ROOT}}, '#{RAILS_ROOT}'] if defined?(RAILS_ROOT)
|
||||
end
|
||||
|
||||
@@ -4,7 +4,7 @@ require File.dirname(__FILE__) + '/../abstract_unit'
|
||||
class ActionPackAssertionsController < ActionController::Base
|
||||
|
||||
# this does absolutely nothing
|
||||
def nothing() render_text ""; end
|
||||
def nothing() head :ok end
|
||||
|
||||
# a standard template
|
||||
def hello_world() render "test/hello_world"; end
|
||||
@@ -27,13 +27,13 @@ class ActionPackAssertionsController < ActionController::Base
|
||||
def redirect_external() redirect_to_url "http://www.rubyonrails.org"; end
|
||||
|
||||
# a 404
|
||||
def response404() render_text "", "404 AWOL"; end
|
||||
def response404() head '404 AWOL' end
|
||||
|
||||
# a 500
|
||||
def response500() render_text "", "500 Sorry"; end
|
||||
def response500() head '500 Sorry' end
|
||||
|
||||
# a fictional 599
|
||||
def response599() render_text "", "599 Whoah!"; end
|
||||
def response599() head '599 Whoah!' end
|
||||
|
||||
# putting stuff in the flash
|
||||
def flash_me
|
||||
@@ -139,6 +139,10 @@ module Admin
|
||||
def redirect_to_fellow_controller
|
||||
redirect_to :controller => 'user'
|
||||
end
|
||||
|
||||
def redirect_to_top_level_named_route
|
||||
redirect_to top_level_url(:id => "foo")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -155,10 +159,16 @@ ActionPackAssertionsController.template_root = File.dirname(__FILE__) + "/../fix
|
||||
class ActionPackAssertionsControllerTest < Test::Unit::TestCase
|
||||
# let's get this party started
|
||||
def setup
|
||||
ActionController::Routing::Routes.reload
|
||||
ActionController::Routing.use_controllers!(%w(action_pack_assertions admin/inner_module content admin/user))
|
||||
@controller = ActionPackAssertionsController.new
|
||||
@request, @response = ActionController::TestRequest.new, ActionController::TestResponse.new
|
||||
end
|
||||
|
||||
def teardown
|
||||
ActionController::Routing::Routes.reload
|
||||
end
|
||||
|
||||
# -- assertion-based testing ------------------------------------------------
|
||||
|
||||
def test_assert_tag_and_url_for
|
||||
@@ -295,6 +305,19 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
|
||||
end
|
||||
end
|
||||
|
||||
def test_assert_redirected_to_top_level_named_route_from_nested_controller
|
||||
with_routing do |set|
|
||||
set.draw do |map|
|
||||
map.top_level '/action_pack_assertions/:id', :controller => 'action_pack_assertions', :action => 'index'
|
||||
map.connect ':controller/:action/:id'
|
||||
end
|
||||
@controller = Admin::InnerModuleController.new
|
||||
process :redirect_to_top_level_named_route
|
||||
# passes -> assert_redirected_to "http://test.host/action_pack_assertions/foo"
|
||||
assert_redirected_to "/action_pack_assertions/foo"
|
||||
end
|
||||
end
|
||||
|
||||
# test the flash-based assertions with something is in the flash
|
||||
def test_flash_assertions_full
|
||||
process :flash_me
|
||||
@@ -402,7 +425,9 @@ class ActionPackAssertionsControllerTest < Test::Unit::TestCase
|
||||
|
||||
process :redirect_external
|
||||
assert_equal 'http://www.rubyonrails.org', @response.redirect_url
|
||||
end
|
||||
|
||||
def test_no_redirect_url
|
||||
process :nothing
|
||||
assert_nil @response.redirect_url
|
||||
end
|
||||
|
||||
@@ -5,8 +5,29 @@ CACHE_DIR = 'test_cache'
|
||||
# Don't change '/../temp/' cavalierly or you might hoze something you don't want hozed
|
||||
FILE_STORE_PATH = File.join(File.dirname(__FILE__), '/../temp/', CACHE_DIR)
|
||||
ActionController::Base.perform_caching = true
|
||||
ActionController::Base.page_cache_directory = FILE_STORE_PATH
|
||||
ActionController::Base.fragment_cache_store = :file_store, FILE_STORE_PATH
|
||||
|
||||
class PageCachingTestController < ActionController::Base
|
||||
caches_page :ok, :no_content, :found, :not_found
|
||||
|
||||
def ok
|
||||
head :ok
|
||||
end
|
||||
|
||||
def no_content
|
||||
head :no_content
|
||||
end
|
||||
|
||||
def found
|
||||
redirect_to :action => 'ok'
|
||||
end
|
||||
|
||||
def not_found
|
||||
head :not_found
|
||||
end
|
||||
end
|
||||
|
||||
class PageCachingTest < Test::Unit::TestCase
|
||||
def setup
|
||||
ActionController::Routing::Routes.draw do |map|
|
||||
@@ -14,11 +35,23 @@ class PageCachingTest < Test::Unit::TestCase
|
||||
map.resources :posts
|
||||
map.connect ':controller/:action/:id'
|
||||
end
|
||||
|
||||
|
||||
@request = ActionController::TestRequest.new
|
||||
@request.host = 'hostname.com'
|
||||
|
||||
@response = ActionController::TestResponse.new
|
||||
@controller = PageCachingTestController.new
|
||||
|
||||
@params = {:controller => 'posts', :action => 'index', :only_path => true, :skip_relative_url_root => true}
|
||||
@rewriter = ActionController::UrlRewriter.new(@request, @params)
|
||||
end
|
||||
|
||||
FileUtils.rm_rf(File.dirname(FILE_STORE_PATH))
|
||||
FileUtils.mkdir_p(FILE_STORE_PATH)
|
||||
end
|
||||
|
||||
def teardown
|
||||
FileUtils.rm_rf(File.dirname(FILE_STORE_PATH))
|
||||
end
|
||||
|
||||
def test_page_caching_resources_saves_to_correct_path_with_extension_even_if_default_route
|
||||
@params[:format] = 'rss'
|
||||
@@ -26,35 +59,67 @@ class PageCachingTest < Test::Unit::TestCase
|
||||
@params[:format] = nil
|
||||
assert_equal '/', @rewriter.rewrite(@params)
|
||||
end
|
||||
|
||||
def test_should_cache_get_with_ok_status
|
||||
get :ok
|
||||
assert_response :ok
|
||||
assert_page_cached :ok, "get with ok status should have been cached"
|
||||
end
|
||||
|
||||
[:ok, :no_content, :found, :not_found].each do |status|
|
||||
[:get, :post, :put, :delete].each do |method|
|
||||
unless method == :get and status == :ok
|
||||
define_method "test_shouldnt_cache_#{method}_with_#{status}_status" do
|
||||
@request.env['REQUEST_METHOD'] = method.to_s.upcase
|
||||
process status
|
||||
assert_response status
|
||||
assert_page_not_cached status, "#{method} with #{status} status shouldn't have been cached"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
def assert_page_cached(action, message = "#{action} should have been cached")
|
||||
assert page_cached?(action), message
|
||||
end
|
||||
|
||||
def assert_page_not_cached(action, message = "#{action} shouldn't have been cached")
|
||||
assert !page_cached?(action), message
|
||||
end
|
||||
|
||||
def page_cached?(action)
|
||||
File.exist? "#{FILE_STORE_PATH}/page_caching_test/#{action}.html"
|
||||
end
|
||||
end
|
||||
|
||||
class ActionCachingTestController < ActionController::Base
|
||||
caches_action :index
|
||||
|
||||
|
||||
def index
|
||||
@cache_this = Time.now.to_f.to_s
|
||||
render :text => @cache_this
|
||||
end
|
||||
|
||||
|
||||
def expire
|
||||
expire_action :controller => 'action_caching_test', :action => 'index'
|
||||
render :nothing => true
|
||||
end
|
||||
|
||||
|
||||
end
|
||||
|
||||
class ActionCachingMockController
|
||||
attr_accessor :mock_url_for
|
||||
attr_accessor :mock_path
|
||||
|
||||
|
||||
def initialize
|
||||
yield self if block_given?
|
||||
end
|
||||
|
||||
|
||||
def url_for(*args)
|
||||
@mock_url_for
|
||||
end
|
||||
|
||||
|
||||
def request
|
||||
mocked_path = @mock_path
|
||||
Object.new.instance_eval(<<-EVAL)
|
||||
@@ -71,62 +136,62 @@ class ActionCacheTest < Test::Unit::TestCase
|
||||
@path_class = ActionController::Caching::Actions::ActionCachePath
|
||||
@mock_controller = ActionCachingMockController.new
|
||||
end
|
||||
|
||||
|
||||
def teardown
|
||||
FileUtils.rm_rf(File.dirname(FILE_STORE_PATH))
|
||||
end
|
||||
|
||||
|
||||
def test_simple_action_cache
|
||||
get :index
|
||||
cached_time = content_to_cache
|
||||
assert_equal cached_time, @response.body
|
||||
reset!
|
||||
|
||||
|
||||
get :index
|
||||
assert_equal cached_time, @response.body
|
||||
end
|
||||
|
||||
|
||||
def test_cache_expiration
|
||||
get :index
|
||||
cached_time = content_to_cache
|
||||
reset!
|
||||
|
||||
|
||||
get :index
|
||||
assert_equal cached_time, @response.body
|
||||
reset!
|
||||
|
||||
get :expire
|
||||
reset!
|
||||
|
||||
|
||||
get :index
|
||||
new_cached_time = content_to_cache
|
||||
assert_not_equal cached_time, @response.body
|
||||
reset!
|
||||
|
||||
|
||||
get :index
|
||||
assert_response :success
|
||||
assert_equal new_cached_time, @response.body
|
||||
end
|
||||
|
||||
|
||||
def test_cache_is_scoped_by_subdomain
|
||||
@request.host = 'jamis.hostname.com'
|
||||
get :index
|
||||
jamis_cache = content_to_cache
|
||||
|
||||
|
||||
@request.host = 'david.hostname.com'
|
||||
get :index
|
||||
david_cache = content_to_cache
|
||||
assert_not_equal jamis_cache, @response.body
|
||||
|
||||
|
||||
@request.host = 'jamis.hostname.com'
|
||||
get :index
|
||||
assert_equal jamis_cache, @response.body
|
||||
|
||||
|
||||
@request.host = 'david.hostname.com'
|
||||
get :index
|
||||
assert_equal david_cache, @response.body
|
||||
end
|
||||
|
||||
|
||||
def test_xml_version_of_resource_is_treated_as_different_cache
|
||||
@mock_controller.mock_url_for = 'http://example.org/posts/'
|
||||
@mock_controller.mock_path = '/posts/index.xml'
|
||||
@@ -134,32 +199,30 @@ class ActionCacheTest < Test::Unit::TestCase
|
||||
assert_equal 'xml', path_object.extension
|
||||
assert_equal 'example.org/posts/index.xml', path_object.path
|
||||
end
|
||||
|
||||
|
||||
def test_empty_path_is_normalized
|
||||
@mock_controller.mock_url_for = 'http://example.org/'
|
||||
@mock_controller.mock_path = '/'
|
||||
|
||||
assert_equal 'example.org/index', @path_class.path_for(@mock_controller)
|
||||
end
|
||||
|
||||
|
||||
def test_file_extensions
|
||||
get :index, :id => 'kitten.jpg'
|
||||
get :index, :id => 'kitten.jpg'
|
||||
get :index, :id => 'kitten.jpg'
|
||||
|
||||
assert_response :success
|
||||
end
|
||||
|
||||
|
||||
private
|
||||
|
||||
def content_to_cache
|
||||
assigns(:cache_this)
|
||||
end
|
||||
|
||||
|
||||
def reset!
|
||||
@request = ActionController::TestRequest.new
|
||||
@response = ActionController::TestResponse.new
|
||||
@controller = ActionCachingTestController.new
|
||||
@request.host = 'hostname.com'
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
|
||||
@@ -7,15 +7,15 @@ class CaptureController < ActionController::Base
|
||||
def content_for
|
||||
render :layout => "talk_from_action"
|
||||
end
|
||||
|
||||
|
||||
def erb_content_for
|
||||
render :layout => "talk_from_action"
|
||||
end
|
||||
|
||||
|
||||
def block_content_for
|
||||
render :layout => "talk_from_action"
|
||||
end
|
||||
|
||||
|
||||
def non_erb_block_content_for
|
||||
render :layout => "talk_from_action"
|
||||
end
|
||||
@@ -43,36 +43,38 @@ class CaptureTest < Test::Unit::TestCase
|
||||
get :capturing
|
||||
assert_equal "Dreamy days", @response.body.strip
|
||||
end
|
||||
|
||||
|
||||
def test_content_for
|
||||
get :content_for
|
||||
assert_equal expected_content_for_output, @response.body
|
||||
end
|
||||
|
||||
|
||||
def test_erb_content_for
|
||||
get :content_for
|
||||
assert_equal expected_content_for_output, @response.body
|
||||
end
|
||||
|
||||
|
||||
def test_block_content_for
|
||||
get :block_content_for
|
||||
assert_equal expected_content_for_output, @response.body
|
||||
end
|
||||
|
||||
|
||||
def test_non_erb_block_content_for
|
||||
get :non_erb_block_content_for
|
||||
assert_equal expected_content_for_output, @response.body
|
||||
end
|
||||
|
||||
def test_update_element_with_capture
|
||||
get :update_element_with_capture
|
||||
assert_deprecated 'update_element_function' do
|
||||
get :update_element_with_capture
|
||||
end
|
||||
assert_equal(
|
||||
"<script type=\"text/javascript\">\n//<![CDATA[\n$('products').innerHTML = '\\n <p>Product 1</p>\\n <p>Product 2</p>\\n';\n\n//]]>\n</script>" +
|
||||
"\n\n$('status').innerHTML = '\\n <b>You bought something!</b>\\n';",
|
||||
"\n\n$('status').innerHTML = '\\n <b>You bought something!</b>\\n';",
|
||||
@response.body.strip
|
||||
)
|
||||
end
|
||||
|
||||
|
||||
private
|
||||
def expected_content_for_output
|
||||
"<title>Putting stuff in the title!</title>\n\nGreat stuff!"
|
||||
|
||||
@@ -155,9 +155,10 @@ class CGITest < Test::Unit::TestCase
|
||||
end
|
||||
|
||||
def test_parse_params_from_multipart_upload
|
||||
mockup = Struct.new(:content_type, :original_filename)
|
||||
mockup = Struct.new(:content_type, :original_filename, :read, :rewind)
|
||||
file = mockup.new('img/jpeg', 'foo.jpg')
|
||||
ie_file = mockup.new('img/jpeg', 'c:\\Documents and Settings\\foo\\Desktop\\bar.jpg')
|
||||
non_file_text_part = mockup.new('text/plain', '', 'abc')
|
||||
|
||||
input = {
|
||||
"something" => [ StringIO.new("") ],
|
||||
@@ -168,9 +169,10 @@ class CGITest < Test::Unit::TestCase
|
||||
"products[string]" => [ StringIO.new("Apple Computer") ],
|
||||
"products[file]" => [ file ],
|
||||
"ie_products[string]" => [ StringIO.new("Microsoft") ],
|
||||
"ie_products[file]" => [ ie_file ]
|
||||
"ie_products[file]" => [ ie_file ],
|
||||
"text_part" => [non_file_text_part]
|
||||
}
|
||||
|
||||
|
||||
expected_output = {
|
||||
"something" => "",
|
||||
"array_of_stringios" => ["One", "Two"],
|
||||
@@ -192,7 +194,8 @@ class CGITest < Test::Unit::TestCase
|
||||
"ie_products" => {
|
||||
"string" => "Microsoft",
|
||||
"file" => ie_file
|
||||
}
|
||||
},
|
||||
"text_part" => "abc"
|
||||
}
|
||||
|
||||
params = CGIMethods.parse_request_parameters(input)
|
||||
@@ -338,7 +341,7 @@ class MultipartCGITest < Test::Unit::TestCase
|
||||
assert_equal 'bar', params['foo']
|
||||
|
||||
# Ruby CGI doesn't handle multipart/mixed for us.
|
||||
assert_kind_of StringIO, params['files']
|
||||
assert_kind_of String, params['files']
|
||||
assert_equal 19756, params['files'].size
|
||||
end
|
||||
|
||||
@@ -422,4 +425,16 @@ class CGIRequestTest < Test::Unit::TestCase
|
||||
assert_equal ["c84ace84796670c052c6ceb2451fb0f2"], alt_cookies["_session_id"]
|
||||
assert_equal ["yes"], alt_cookies["is_admin"]
|
||||
end
|
||||
|
||||
def test_unbalanced_query_string_with_array
|
||||
assert_equal(
|
||||
{'location' => ["1", "2"], 'age_group' => ["2"]},
|
||||
CGIMethods.parse_query_parameters("location[]=1&location[]=2&age_group[]=2")
|
||||
)
|
||||
assert_equal(
|
||||
{'location' => ["1", "2"], 'age_group' => ["2"]},
|
||||
CGIMethods.parse_request_parameters({'location[]' => ["1", "2"],
|
||||
'age_group[]' => ["2"]})
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -134,7 +134,8 @@ module A
|
||||
class NestedController < ActionController::Base
|
||||
# Stub for uses_component_template_root
|
||||
def self.caller
|
||||
['./test/fixtures/a/b/c/nested_controller.rb']
|
||||
[ '/path/to/active_support/deprecation.rb:93:in `uses_component_template_root',
|
||||
'./test/fixtures/a/b/c/nested_controller.rb' ]
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -143,6 +144,8 @@ end
|
||||
|
||||
class UsesComponentTemplateRootTest < Test::Unit::TestCase
|
||||
def test_uses_component_template_root
|
||||
assert_equal './test/fixtures/', A::B::C::NestedController.uses_component_template_root
|
||||
assert_deprecated 'uses_component_template_root' do
|
||||
assert_equal './test/fixtures/', A::B::C::NestedController.uses_component_template_root
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -4,77 +4,85 @@ class CookieTest < Test::Unit::TestCase
|
||||
class TestController < ActionController::Base
|
||||
def authenticate_with_deprecated_writer
|
||||
cookie "name" => "user_name", "value" => "david"
|
||||
render_text "hello world"
|
||||
end
|
||||
|
||||
def authenticate
|
||||
cookies["user_name"] = "david"
|
||||
render_text "hello world"
|
||||
end
|
||||
|
||||
def authenticate_for_fourten_days
|
||||
cookies["user_name"] = { "value" => "david", "expires" => Time.local(2005, 10, 10) }
|
||||
render_text "hello world"
|
||||
end
|
||||
|
||||
def authenticate_for_fourten_days_with_symbols
|
||||
cookies[:user_name] = { :value => "david", :expires => Time.local(2005, 10, 10) }
|
||||
render_text "hello world"
|
||||
end
|
||||
|
||||
def set_multiple_cookies
|
||||
cookies["user_name"] = { "value" => "david", "expires" => Time.local(2005, 10, 10) }
|
||||
cookies["login"] = "XJ-122"
|
||||
render_text "hello world"
|
||||
end
|
||||
|
||||
def access_frozen_cookies
|
||||
cookies["will"] = "work"
|
||||
render_text "hello world"
|
||||
end
|
||||
|
||||
def rescue_action(e) raise end
|
||||
def logout
|
||||
cookies.delete("user_name")
|
||||
end
|
||||
|
||||
def rescue_action(e)
|
||||
raise unless ActionController::MissingTemplate # No templates here, and we don't care about the output
|
||||
end
|
||||
end
|
||||
|
||||
def setup
|
||||
@request = ActionController::TestRequest.new
|
||||
@response = ActionController::TestResponse.new
|
||||
|
||||
@controller = TestController.new
|
||||
@request.host = "www.nextangle.com"
|
||||
end
|
||||
|
||||
def test_setting_cookie_with_deprecated_writer
|
||||
@request.action = "authenticate_with_deprecated_writer"
|
||||
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david") ], process_request.headers["cookie"]
|
||||
get :authenticate_with_deprecated_writer
|
||||
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david") ], @response.headers["cookie"]
|
||||
end
|
||||
|
||||
def test_setting_cookie
|
||||
@request.action = "authenticate"
|
||||
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david") ], process_request.headers["cookie"]
|
||||
get :authenticate
|
||||
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david") ], @response.headers["cookie"]
|
||||
end
|
||||
|
||||
def test_setting_cookie_for_fourteen_days
|
||||
@request.action = "authenticate_for_fourten_days"
|
||||
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david", "expires" => Time.local(2005, 10, 10)) ], process_request.headers["cookie"]
|
||||
get :authenticate_for_fourten_days
|
||||
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david", "expires" => Time.local(2005, 10, 10)) ], @response.headers["cookie"]
|
||||
end
|
||||
|
||||
def test_setting_cookie_for_fourteen_days_with_symbols
|
||||
@request.action = "authenticate_for_fourten_days"
|
||||
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david", "expires" => Time.local(2005, 10, 10)) ], process_request.headers["cookie"]
|
||||
get :authenticate_for_fourten_days
|
||||
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "david", "expires" => Time.local(2005, 10, 10)) ], @response.headers["cookie"]
|
||||
end
|
||||
|
||||
def test_multiple_cookies
|
||||
@request.action = "set_multiple_cookies"
|
||||
assert_equal 2, process_request.headers["cookie"].size
|
||||
get :set_multiple_cookies
|
||||
assert_equal 2, @response.cookies.size
|
||||
end
|
||||
|
||||
def test_setting_test_cookie
|
||||
@request.action = "access_frozen_cookies"
|
||||
assert_nothing_raised { process_request }
|
||||
assert_nothing_raised { get :access_frozen_cookies }
|
||||
end
|
||||
|
||||
def test_expiring_cookie
|
||||
get :logout
|
||||
assert_equal [ CGI::Cookie::new("name" => "user_name", "value" => "", "expires" => Time.at(0)) ], @response.headers["cookie"]
|
||||
end
|
||||
|
||||
def test_cookiejar_accessor
|
||||
@request.cookies["user_name"] = CGI::Cookie.new("name" => "user_name", "value" => "david", "expires" => Time.local(2025, 10, 10))
|
||||
@controller.request = @request
|
||||
jar = ActionController::CookieJar.new(@controller)
|
||||
assert_equal "david", jar["user_name"]
|
||||
assert_equal nil, jar["something_else"]
|
||||
end
|
||||
|
||||
private
|
||||
def process_request
|
||||
TestController.process(@request, @response)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -14,6 +14,10 @@ class DeprecatedBaseMethodsTest < Test::Unit::TestCase
|
||||
"http://example.com/#{greeting}"
|
||||
end
|
||||
|
||||
def raises_name_error
|
||||
this_method_doesnt_exist
|
||||
end
|
||||
|
||||
def rescue_action(e) raise e end
|
||||
end
|
||||
|
||||
@@ -40,4 +44,17 @@ class DeprecatedBaseMethodsTest < Test::Unit::TestCase
|
||||
|
||||
assert_equal "Living in a nested world", @response.body
|
||||
end
|
||||
|
||||
def test_log_error_silences_deprecation_warnings
|
||||
get :raises_name_error
|
||||
rescue => e
|
||||
assert_not_deprecated { @controller.send :log_error, e }
|
||||
end
|
||||
|
||||
def test_assertion_failed_error_silences_deprecation_warnings
|
||||
get :raises_name_error
|
||||
rescue => e
|
||||
error = Test::Unit::Error.new('testing ur doodz', e)
|
||||
assert_not_deprecated { error.message }
|
||||
end
|
||||
end
|
||||
|
||||
@@ -75,6 +75,8 @@ end
|
||||
class ExemptFromLayoutTest < Test::Unit::TestCase
|
||||
def setup
|
||||
@controller = LayoutTest.new
|
||||
@request = ActionController::TestRequest.new
|
||||
@response = ActionController::TestResponse.new
|
||||
end
|
||||
|
||||
def test_rjs_exempt_from_layout
|
||||
@@ -103,6 +105,15 @@ class ExemptFromLayoutTest < Test::Unit::TestCase
|
||||
ActionController::Base.exempt_from_layout /\.rdoc/
|
||||
assert @controller.send(:template_exempt_from_layout?, 'test.rdoc')
|
||||
end
|
||||
|
||||
def test_rhtml_exempt_from_layout_status_should_prevent_layout_render
|
||||
ActionController::Base.exempt_from_layout :rhtml
|
||||
assert @controller.send(:template_exempt_from_layout?, 'test.rhtml')
|
||||
|
||||
get :hello
|
||||
assert_equal 'hello.rhtml', @response.body
|
||||
ActionController::Base.exempt_from_layout.delete(/\.rhtml$/)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
|
||||
@@ -20,6 +20,13 @@ class RespondToController < ActionController::Base
|
||||
end
|
||||
end
|
||||
|
||||
def json_or_yaml
|
||||
respond_to do |type|
|
||||
type.json { render :text => "JSON" }
|
||||
type.yaml { render :text => "YAML" }
|
||||
end
|
||||
end
|
||||
|
||||
def html_or_xml
|
||||
respond_to do |type|
|
||||
type.html { render :text => "HTML" }
|
||||
@@ -164,6 +171,27 @@ class MimeControllerTest < Test::Unit::TestCase
|
||||
assert_response 406
|
||||
end
|
||||
|
||||
def test_json_or_yaml
|
||||
get :json_or_yaml
|
||||
assert_equal 'JSON', @response.body
|
||||
|
||||
get :json_or_yaml, :format => 'json'
|
||||
assert_equal 'JSON', @response.body
|
||||
|
||||
get :json_or_yaml, :format => 'yaml'
|
||||
assert_equal 'YAML', @response.body
|
||||
|
||||
{ 'YAML' => %w(text/yaml),
|
||||
'JSON' => %w(application/json text/x-json)
|
||||
}.each do |body, content_types|
|
||||
content_types.each do |content_type|
|
||||
@request.env['HTTP_ACCEPT'] = content_type
|
||||
get :json_or_yaml
|
||||
assert_equal body, @response.body
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def test_js_or_anything
|
||||
@request.env["HTTP_ACCEPT"] = "text/javascript, */*"
|
||||
get :js_or_html
|
||||
|
||||
@@ -160,6 +160,33 @@ class NewRenderTestController < ActionController::Base
|
||||
@customers = [ Customer.new("david"), Customer.new("mary") ]
|
||||
render :text => "How's there? #{render_to_string("test/list")}"
|
||||
end
|
||||
|
||||
def render_to_string_with_assigns
|
||||
@before = "i'm before the render"
|
||||
render_to_string :text => "foo"
|
||||
@after = "i'm after the render"
|
||||
render :action => "test/hello_world"
|
||||
end
|
||||
|
||||
def render_to_string_with_partial
|
||||
@partial_only = render_to_string :partial => "partial_only"
|
||||
@partial_with_locals = render_to_string :partial => "customer", :locals => { :customer => Customer.new("david") }
|
||||
render :action => "test/hello_world"
|
||||
end
|
||||
|
||||
def render_to_string_with_exception
|
||||
render_to_string :file => "exception that will not be caught - this will certainly not work", :use_full_path => true
|
||||
end
|
||||
|
||||
def render_to_string_with_caught_exception
|
||||
@before = "i'm before the render"
|
||||
begin
|
||||
render_to_string :file => "exception that will be caught- hope my future instance vars still work!", :use_full_path => true
|
||||
rescue
|
||||
end
|
||||
@after = "i'm after the render"
|
||||
render :action => "test/hello_world"
|
||||
end
|
||||
|
||||
def accessing_params_in_template
|
||||
render :inline => "Hello: <%= params[:name] %>"
|
||||
@@ -187,6 +214,11 @@ class NewRenderTestController < ActionController::Base
|
||||
render :text => "hello"
|
||||
redirect_to :action => "double_render"
|
||||
end
|
||||
|
||||
def render_to_string_and_render
|
||||
@stuff = render_to_string :text => "here is some cached stuff"
|
||||
render :text => "Hi web users! #{@stuff}"
|
||||
end
|
||||
|
||||
def rendering_with_conflicting_local_vars
|
||||
@name = "David"
|
||||
@@ -523,6 +555,28 @@ EOS
|
||||
assert_not_deprecated { get :hello_in_a_string }
|
||||
assert_equal "How's there? goodbyeHello: davidHello: marygoodbye\n", @response.body
|
||||
end
|
||||
|
||||
def test_render_to_string_doesnt_break_assigns
|
||||
get :render_to_string_with_assigns
|
||||
assert_equal "i'm before the render", assigns(:before)
|
||||
assert_equal "i'm after the render", assigns(:after)
|
||||
end
|
||||
|
||||
def test_render_to_string_partial
|
||||
get :render_to_string_with_partial
|
||||
assert_equal "only partial", assigns(:partial_only)
|
||||
assert_equal "Hello: david", assigns(:partial_with_locals)
|
||||
end
|
||||
|
||||
def test_bad_render_to_string_still_throws_exception
|
||||
assert_raises(ActionController::MissingTemplate) { get :render_to_string_with_exception }
|
||||
end
|
||||
|
||||
def test_render_to_string_that_throws_caught_exception_doesnt_break_assigns
|
||||
assert_nothing_raised { get :render_to_string_with_caught_exception }
|
||||
assert_equal "i'm before the render", assigns(:before)
|
||||
assert_equal "i'm after the render", assigns(:after)
|
||||
end
|
||||
|
||||
def test_nested_rendering
|
||||
get :hello_world
|
||||
@@ -555,6 +609,12 @@ EOS
|
||||
def test_render_and_redirect
|
||||
assert_raises(ActionController::DoubleRenderError) { get :render_and_redirect }
|
||||
end
|
||||
|
||||
# specify the one exception to double render rule - render_to_string followed by render
|
||||
def test_render_to_string_and_render
|
||||
get :render_to_string_and_render
|
||||
assert_equal("Hi web users! here is some cached stuff", @response.body)
|
||||
end
|
||||
|
||||
def test_rendering_with_conflicting_local_vars
|
||||
get :rendering_with_conflicting_local_vars
|
||||
@@ -640,24 +700,29 @@ EOS
|
||||
get :head_with_location_header
|
||||
assert @response.body.blank?
|
||||
assert_equal "/foo", @response.headers["Location"]
|
||||
assert_response :ok
|
||||
end
|
||||
|
||||
def test_head_with_custom_header
|
||||
get :head_with_custom_header
|
||||
assert @response.body.blank?
|
||||
assert_equal "something", @response.headers["X-Custom-Header"]
|
||||
assert_response :ok
|
||||
end
|
||||
|
||||
def test_head_with_symbolic_status
|
||||
get :head_with_symbolic_status, :status => "ok"
|
||||
assert_equal "200 OK", @response.headers["Status"]
|
||||
assert_response :ok
|
||||
|
||||
get :head_with_symbolic_status, :status => "not_found"
|
||||
assert_equal "404 Not Found", @response.headers["Status"]
|
||||
assert_response :not_found
|
||||
|
||||
ActionController::StatusCodes::SYMBOL_TO_STATUS_CODE.each do |status, code|
|
||||
get :head_with_symbolic_status, :status => status.to_s
|
||||
assert_equal code, @response.response_code
|
||||
assert_response status
|
||||
end
|
||||
end
|
||||
|
||||
@@ -672,6 +737,7 @@ EOS
|
||||
get :head_with_string_status, :status => "404 Eat Dirt"
|
||||
assert_equal 404, @response.response_code
|
||||
assert_equal "Eat Dirt", @response.message
|
||||
assert_response :not_found
|
||||
end
|
||||
|
||||
def test_head_with_status_code_first
|
||||
@@ -679,5 +745,6 @@ EOS
|
||||
assert_equal 403, @response.response_code
|
||||
assert_equal "Forbidden", @response.message
|
||||
assert_equal "something", @response.headers["X-Custom-Header"]
|
||||
assert_response :forbidden
|
||||
end
|
||||
end
|
||||
|
||||
@@ -39,6 +39,18 @@ class TestController < ActionController::Base
|
||||
render_text "hello world"
|
||||
end
|
||||
|
||||
def render_json_hello_world
|
||||
render_json({:hello => 'world'}.to_json)
|
||||
end
|
||||
|
||||
def render_json_hello_world_with_callback
|
||||
render_json({:hello => 'world'}.to_json, 'alert')
|
||||
end
|
||||
|
||||
def render_symbol_json
|
||||
render :json => {:hello => 'world'}.to_json
|
||||
end
|
||||
|
||||
def render_custom_code
|
||||
render_text "hello world", "404 Moved"
|
||||
end
|
||||
@@ -117,6 +129,7 @@ class TestController < ActionController::Base
|
||||
case action_name
|
||||
when "layout_test": "layouts/standard"
|
||||
when "builder_layout_test": "layouts/builder"
|
||||
when "render_symbol_json": "layouts/standard" # to make sure layouts don't interfere
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -164,6 +177,24 @@ class RenderTest < Test::Unit::TestCase
|
||||
assert_equal "hello world", @response.body
|
||||
end
|
||||
|
||||
def test_do_with_render_json
|
||||
get :render_json_hello_world
|
||||
assert_equal '{hello: "world"}', @response.body
|
||||
assert_equal 'application/json', @response.content_type
|
||||
end
|
||||
|
||||
def test_do_with_render_json_with_callback
|
||||
get :render_json_hello_world_with_callback
|
||||
assert_equal 'alert({hello: "world"})', @response.body
|
||||
assert_equal 'application/json', @response.content_type
|
||||
end
|
||||
|
||||
def test_do_with_render_symbol_json
|
||||
get :render_symbol_json
|
||||
assert_equal '{hello: "world"}', @response.body
|
||||
assert_equal 'application/json', @response.content_type
|
||||
end
|
||||
|
||||
def test_do_with_render_custom_code
|
||||
get :render_custom_code
|
||||
assert_response 404
|
||||
|
||||
@@ -174,48 +174,54 @@ class RequestTest < Test::Unit::TestCase
|
||||
assert_equal "/path/of/some/uri?mapped=1", @request.request_uri
|
||||
assert_equal "/path/of/some/uri", @request.path
|
||||
|
||||
@request.set_REQUEST_URI nil
|
||||
@request.relative_url_root = nil
|
||||
@request.env['PATH_INFO'] = "/path/of/some/uri?mapped=1"
|
||||
@request.env['SCRIPT_NAME'] = "/path/dispatch.rb"
|
||||
assert_equal "/path/of/some/uri?mapped=1", @request.request_uri
|
||||
assert_equal "/of/some/uri", @request.path
|
||||
|
||||
@request.set_REQUEST_URI nil
|
||||
@request.relative_url_root = nil
|
||||
@request.env['PATH_INFO'] = "/path/of/some/uri"
|
||||
@request.env['SCRIPT_NAME'] = nil
|
||||
assert_equal "/path/of/some/uri", @request.request_uri
|
||||
assert_equal "/path/of/some/uri", @request.path
|
||||
|
||||
@request.set_REQUEST_URI nil
|
||||
@request.relative_url_root = nil
|
||||
@request.env['PATH_INFO'] = "/"
|
||||
assert_equal "/", @request.request_uri
|
||||
assert_equal "/", @request.path
|
||||
|
||||
@request.set_REQUEST_URI nil
|
||||
@request.relative_url_root = nil
|
||||
@request.env['PATH_INFO'] = "/?m=b"
|
||||
assert_equal "/?m=b", @request.request_uri
|
||||
assert_equal "/", @request.path
|
||||
|
||||
|
||||
@request.set_REQUEST_URI nil
|
||||
@request.relative_url_root = nil
|
||||
@request.env['PATH_INFO'] = "/"
|
||||
@request.env['SCRIPT_NAME'] = "/dispatch.cgi"
|
||||
assert_equal "/", @request.request_uri
|
||||
assert_equal "/", @request.path
|
||||
assert_equal "/", @request.path
|
||||
|
||||
@request.set_REQUEST_URI nil
|
||||
@request.relative_url_root = nil
|
||||
@request.env['PATH_INFO'] = "/hieraki/"
|
||||
@request.env['SCRIPT_NAME'] = "/hieraki/dispatch.cgi"
|
||||
assert_equal "/hieraki/", @request.request_uri
|
||||
assert_equal "/", @request.path
|
||||
|
||||
assert_equal "/", @request.path
|
||||
|
||||
@request.set_REQUEST_URI '/hieraki/dispatch.cgi'
|
||||
@request.relative_url_root = '/hieraki'
|
||||
assert_equal "/dispatch.cgi", @request.path
|
||||
assert_equal "/dispatch.cgi", @request.path
|
||||
@request.relative_url_root = nil
|
||||
|
||||
@request.set_REQUEST_URI '/hieraki/dispatch.cgi'
|
||||
@request.relative_url_root = '/foo'
|
||||
assert_equal "/hieraki/dispatch.cgi", @request.path
|
||||
assert_equal "/hieraki/dispatch.cgi", @request.path
|
||||
@request.relative_url_root = nil
|
||||
|
||||
# This test ensures that Rails uses REQUEST_URI over PATH_INFO
|
||||
@@ -226,7 +232,7 @@ class RequestTest < Test::Unit::TestCase
|
||||
assert_equal "/some/path", @request.request_uri
|
||||
assert_equal "/some/path", @request.path
|
||||
end
|
||||
|
||||
|
||||
|
||||
def test_host_with_port
|
||||
@request.host = "rubyonrails.org"
|
||||
@@ -274,7 +280,7 @@ class RequestTest < Test::Unit::TestCase
|
||||
end
|
||||
|
||||
def test_symbolized_request_methods
|
||||
[:head, :get, :post, :put, :delete].each do |method|
|
||||
[:get, :post, :put, :delete].each do |method|
|
||||
set_request_method_to method
|
||||
assert_equal method, @request.method
|
||||
end
|
||||
@@ -282,7 +288,7 @@ class RequestTest < Test::Unit::TestCase
|
||||
|
||||
def test_allow_method_hacking_on_post
|
||||
set_request_method_to :post
|
||||
[:head, :get, :put, :delete].each do |method|
|
||||
[:get, :put, :delete].each do |method|
|
||||
@request.instance_eval { @parameters = { :_method => method } ; @request_method = nil }
|
||||
assert_equal method, @request.method
|
||||
end
|
||||
@@ -290,11 +296,18 @@ class RequestTest < Test::Unit::TestCase
|
||||
|
||||
def test_restrict_method_hacking
|
||||
@request.instance_eval { @parameters = { :_method => 'put' } }
|
||||
[:head, :get, :put, :delete].each do |method|
|
||||
[:get, :put, :delete].each do |method|
|
||||
set_request_method_to method
|
||||
assert_equal method, @request.method
|
||||
end
|
||||
end
|
||||
|
||||
def test_head_masquarading_as_get
|
||||
set_request_method_to :head
|
||||
assert_equal :get, @request.method
|
||||
assert @request.get?
|
||||
assert @request.head?
|
||||
end
|
||||
|
||||
protected
|
||||
def set_request_method_to(method)
|
||||
|
||||
@@ -49,6 +49,12 @@ class ResourcesTest < Test::Unit::TestCase
|
||||
assert_simply_restful_for :comments, :path_prefix => 'thread/5/', :options => { :thread_id => '5' }
|
||||
end
|
||||
end
|
||||
|
||||
def test_with_name_prefix
|
||||
with_restful_routing :messages, :name_prefix => 'post_' do
|
||||
assert_simply_restful_for :messages, :name_prefix => 'post_'
|
||||
end
|
||||
end
|
||||
|
||||
def test_with_collection_action
|
||||
rss_options = {:action => 'rss'}
|
||||
@@ -232,13 +238,14 @@ class ResourcesTest < Test::Unit::TestCase
|
||||
options[:options].delete :action
|
||||
|
||||
full_prefix = "/#{options[:path_prefix]}#{controller_name}"
|
||||
name_prefix = options[:name_prefix]
|
||||
|
||||
assert_named_route "#{full_prefix}", "#{controller_name}_path", options[:options]
|
||||
assert_named_route "#{full_prefix}.xml", "formatted_#{controller_name}_path", options[:options].merge(:format => 'xml')
|
||||
assert_named_route "#{full_prefix}/new", "new_#{singular_name}_path", options[:options]
|
||||
assert_named_route "#{full_prefix}/1", "#{singular_name}_path", options[:options].merge(:id => '1')
|
||||
assert_named_route "#{full_prefix}/1;edit", "edit_#{singular_name}_path", options[:options].merge(:id => '1')
|
||||
assert_named_route "#{full_prefix}/1.xml", "formatted_#{singular_name}_path", options[:options].merge(:format => 'xml', :id => '1')
|
||||
assert_named_route "#{full_prefix}", "#{name_prefix}#{controller_name}_path", options[:options]
|
||||
assert_named_route "#{full_prefix}.xml", "formatted_#{name_prefix}#{controller_name}_path", options[:options].merge(:format => 'xml')
|
||||
assert_named_route "#{full_prefix}/new", "#{name_prefix}new_#{singular_name}_path", options[:options]
|
||||
assert_named_route "#{full_prefix}/1", "#{name_prefix}#{singular_name}_path", options[:options].merge(:id => '1')
|
||||
assert_named_route "#{full_prefix}/1;edit", "#{name_prefix}edit_#{singular_name}_path", options[:options].merge(:id => '1')
|
||||
assert_named_route "#{full_prefix}/1.xml", "formatted_#{name_prefix}#{singular_name}_path", options[:options].merge(:format => 'xml', :id => '1')
|
||||
yield options[:options] if block_given?
|
||||
end
|
||||
|
||||
|
||||
@@ -376,7 +376,7 @@ class LegacyRouteSetTests < Test::Unit::TestCase
|
||||
|
||||
def test_named_url_with_no_action_specified
|
||||
rs.draw do |map|
|
||||
map.root '', :controller => 'content'
|
||||
map.home '', :controller => 'content'
|
||||
map.connect ':controller/:action/:id'
|
||||
end
|
||||
|
||||
@@ -384,14 +384,14 @@ class LegacyRouteSetTests < Test::Unit::TestCase
|
||||
assert_equal '/', rs.generate(:controller => 'content')
|
||||
|
||||
x = setup_for_named_route.new
|
||||
assert_equal({:controller => 'content', :action => 'index', :use_route => :root, :only_path => false},
|
||||
x.send(:root_url))
|
||||
assert_equal({:controller => 'content', :action => 'index', :use_route => :home, :only_path => false},
|
||||
x.send(:home_url))
|
||||
end
|
||||
|
||||
def test_url_generated_when_forgetting_action
|
||||
[{:controller => 'content', :action => 'index'}, {:controller => 'content'}].each do |hash|
|
||||
rs.draw do |map|
|
||||
map.root '', hash
|
||||
map.home '', hash
|
||||
map.connect ':controller/:action/:id'
|
||||
end
|
||||
assert_equal '/', rs.generate({:action => nil}, {:controller => 'content', :action => 'hello'})
|
||||
@@ -853,6 +853,12 @@ class RouteTest < Test::Unit::TestCase
|
||||
{ :controller => "users", :action => "show", :format => "html" },
|
||||
route.defaults)
|
||||
end
|
||||
|
||||
def test_builder_complains_without_controller
|
||||
assert_raises(ArgumentError) do
|
||||
ROUTING::RouteBuilder.new.build '/contact', :contoller => "contact", :action => "index"
|
||||
end
|
||||
end
|
||||
|
||||
def test_significant_keys_for_default_route
|
||||
keys = default_route.significant_keys.sort_by {|k| k.to_s }
|
||||
@@ -1576,6 +1582,18 @@ class RouteSetTest < Test::Unit::TestCase
|
||||
Object.send(:remove_const, :PeopleController)
|
||||
end
|
||||
|
||||
def test_deprecation_warning_for_root_route
|
||||
Object.const_set(:PeopleController, Class.new)
|
||||
|
||||
set.draw do |map|
|
||||
assert_deprecated do
|
||||
map.root('', :controller => "people")
|
||||
end
|
||||
end
|
||||
ensure
|
||||
Object.send(:remove_const, :PeopleController)
|
||||
end
|
||||
|
||||
def test_generate_with_default_action
|
||||
set.draw do |map|
|
||||
map.connect "/people", :controller => "people"
|
||||
@@ -1673,10 +1691,13 @@ class RoutingTest < Test::Unit::TestCase
|
||||
|
||||
def test_possible_controllers
|
||||
true_controller_paths = ActionController::Routing.controller_paths
|
||||
|
||||
|
||||
ActionController::Routing.use_controllers! nil
|
||||
Object.send(:const_set, :RAILS_ROOT, File.dirname(__FILE__) + '/controller_fixtures')
|
||||
|
||||
|
||||
silence_warnings do
|
||||
Object.send(:const_set, :RAILS_ROOT, File.dirname(__FILE__) + '/controller_fixtures')
|
||||
end
|
||||
|
||||
ActionController::Routing.controller_paths = [
|
||||
RAILS_ROOT, RAILS_ROOT + '/app/controllers', RAILS_ROOT + '/vendor/plugins/bad_plugin/lib'
|
||||
]
|
||||
@@ -1734,4 +1755,4 @@ class RoutingTest < Test::Unit::TestCase
|
||||
assert_equal %w(vendor\\rails\\railties\\builtin\\rails_info vendor\\rails\\actionpack\\lib app\\controllers app\\helpers app\\models lib .), paths
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
|
||||
@@ -63,6 +63,14 @@ class SendFileTest < Test::Unit::TestCase
|
||||
assert_equal file_data, response.body
|
||||
end
|
||||
|
||||
def test_headers_after_send_shouldnt_include_charset
|
||||
response = process('data')
|
||||
assert_equal "application/octet-stream", response.headers["Content-Type"]
|
||||
|
||||
response = process('file')
|
||||
assert_equal "application/octet-stream", response.headers["Content-Type"]
|
||||
end
|
||||
|
||||
# Test that send_file_headers! is setting the correct HTTP headers.
|
||||
def test_send_file_headers!
|
||||
options = {
|
||||
|
||||
@@ -44,6 +44,49 @@ class SessionManagementTest < Test::Unit::TestCase
|
||||
end
|
||||
end
|
||||
|
||||
class AssociationCachingTestController < ActionController::Base
|
||||
class ObjectWithAssociationCache
|
||||
def initialize
|
||||
@cached_associations = false
|
||||
end
|
||||
|
||||
def fetch_associations
|
||||
@cached_associations = true
|
||||
end
|
||||
|
||||
def clear_association_cache
|
||||
@cached_associations = false
|
||||
end
|
||||
|
||||
def has_cached_associations?
|
||||
@cached_associations
|
||||
end
|
||||
end
|
||||
|
||||
def show
|
||||
session[:object] = ObjectWithAssociationCache.new
|
||||
session[:object].fetch_associations
|
||||
if session[:object].has_cached_associations?
|
||||
render :text => "has cached associations"
|
||||
else
|
||||
render :text => "does not have cached associations"
|
||||
end
|
||||
end
|
||||
|
||||
def tell
|
||||
if session[:object]
|
||||
if session[:object].has_cached_associations?
|
||||
render :text => "has cached associations"
|
||||
else
|
||||
render :text => "does not have cached associations"
|
||||
end
|
||||
else
|
||||
render :text => "there is no object"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
def setup
|
||||
@request, @response = ActionController::TestRequest.new,
|
||||
ActionController::TestResponse.new
|
||||
@@ -91,4 +134,12 @@ class SessionManagementTest < Test::Unit::TestCase
|
||||
assert_equal CGI::Session::ActiveRecordStore, ActionController::Base.session_store
|
||||
end
|
||||
end
|
||||
|
||||
def test_process_cleanup_with_session_management_support
|
||||
@controller = AssociationCachingTestController.new
|
||||
get :show
|
||||
assert_equal "has cached associations", @response.body
|
||||
get :tell
|
||||
assert_equal "does not have cached associations", @response.body
|
||||
end
|
||||
end
|
||||
|
||||
@@ -66,6 +66,11 @@ HTML
|
||||
redirect_to :controller => 'fail', :id => 5
|
||||
end
|
||||
|
||||
def create
|
||||
headers['Location'] = 'created resource'
|
||||
head :created
|
||||
end
|
||||
|
||||
private
|
||||
def rescue_action(e)
|
||||
raise e
|
||||
@@ -81,7 +86,7 @@ HTML
|
||||
@request = ActionController::TestRequest.new
|
||||
@response = ActionController::TestResponse.new
|
||||
ActionController::Routing::Routes.reload
|
||||
ActionController::Routing.use_controllers! %w(content admin/user)
|
||||
ActionController::Routing.use_controllers! %w(content admin/user test_test/test)
|
||||
end
|
||||
|
||||
def teardown
|
||||
@@ -463,6 +468,20 @@ HTML
|
||||
end
|
||||
end
|
||||
|
||||
def test_redirect_url_only_cares_about_location_header
|
||||
get :create
|
||||
assert_response :created
|
||||
|
||||
# Redirect url doesn't care that it wasn't a :redirect response.
|
||||
assert_equal 'created resource', @response.redirect_url
|
||||
assert_equal @response.redirect_url, redirect_to_url
|
||||
|
||||
# Must be a :redirect response.
|
||||
assert_raise(Test::Unit::AssertionFailedError) do
|
||||
assert_redirected_to 'created resource'
|
||||
end
|
||||
end
|
||||
|
||||
protected
|
||||
def with_foo_routing
|
||||
with_routing do |set|
|
||||
|
||||
@@ -78,7 +78,7 @@ class UrlWriterTests < Test::Unit::TestCase
|
||||
|
||||
def test_named_route
|
||||
ActionController::Routing::Routes.draw do |map|
|
||||
map.home '/home/sweet/home/:user'
|
||||
map.home '/home/sweet/home/:user', :controller => 'home', :action => 'index'
|
||||
map.connect ':controller/:action/:id'
|
||||
end
|
||||
|
||||
@@ -96,7 +96,7 @@ class UrlWriterTests < Test::Unit::TestCase
|
||||
|
||||
def test_only_path
|
||||
ActionController::Routing::Routes.draw do |map|
|
||||
map.home '/home/sweet/home/:user'
|
||||
map.home '/home/sweet/home/:user', :controller => 'home', :action => 'index'
|
||||
map.connect ':controller/:action/:id'
|
||||
end
|
||||
|
||||
|
||||
BIN
actionpack/test/fixtures/multipart/binary_file
vendored
BIN
actionpack/test/fixtures/multipart/binary_file
vendored
Binary file not shown.
1
actionpack/test/fixtures/public/javascripts/application.js
vendored
Normal file
1
actionpack/test/fixtures/public/javascripts/application.js
vendored
Normal file
@@ -0,0 +1 @@
|
||||
# Test file for javascript_include_tag
|
||||
File diff suppressed because one or more lines are too long
@@ -34,6 +34,7 @@ class AssetTagHelperTest < Test::Unit::TestCase
|
||||
|
||||
AutoDiscoveryToTag = {
|
||||
%(auto_discovery_link_tag) => %(<link href="http://www.example.com" rel="alternate" title="RSS" type="application/rss+xml" />),
|
||||
%(auto_discovery_link_tag(:rss)) => %(<link href="http://www.example.com" rel="alternate" title="RSS" type="application/rss+xml" />),
|
||||
%(auto_discovery_link_tag(:atom)) => %(<link href="http://www.example.com" rel="alternate" title="ATOM" type="application/atom+xml" />),
|
||||
%(auto_discovery_link_tag(:rss, :action => "feed")) => %(<link href="http://www.example.com" rel="alternate" title="RSS" type="application/rss+xml" />),
|
||||
%(auto_discovery_link_tag(:rss, "http://localhost/feed")) => %(<link href="http://localhost/feed" rel="alternate" title="RSS" type="application/rss+xml" />),
|
||||
@@ -47,11 +48,13 @@ class AssetTagHelperTest < Test::Unit::TestCase
|
||||
|
||||
JavascriptPathToTag = {
|
||||
%(javascript_path("xmlhr")) => %(/javascripts/xmlhr.js),
|
||||
%(javascript_path("super/xmlhr")) => %(/javascripts/super/xmlhr.js)
|
||||
%(javascript_path("super/xmlhr")) => %(/javascripts/super/xmlhr.js),
|
||||
%(javascript_path("/super/xmlhr.js")) => %(/super/xmlhr.js)
|
||||
}
|
||||
|
||||
JavascriptIncludeToTag = {
|
||||
%(javascript_include_tag("xmlhr")) => %(<script src="/javascripts/xmlhr.js" type="text/javascript"></script>),
|
||||
%(javascript_include_tag("xmlhr.js")) => %(<script src="/javascripts/xmlhr.js" type="text/javascript"></script>),
|
||||
%(javascript_include_tag("xmlhr", :lang => "vbscript")) => %(<script lang="vbscript" src="/javascripts/xmlhr.js" type="text/javascript"></script>),
|
||||
%(javascript_include_tag("common.javascript", "/elsewhere/cools")) => %(<script src="/javascripts/common.javascript" type="text/javascript"></script>\n<script src="/elsewhere/cools.js" type="text/javascript"></script>),
|
||||
%(javascript_include_tag(:defaults)) => %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>),
|
||||
@@ -61,12 +64,14 @@ class AssetTagHelperTest < Test::Unit::TestCase
|
||||
|
||||
StylePathToTag = {
|
||||
%(stylesheet_path("style")) => %(/stylesheets/style.css),
|
||||
%(stylesheet_path("style.css")) => %(/stylesheets/style.css),
|
||||
%(stylesheet_path('dir/file')) => %(/stylesheets/dir/file.css),
|
||||
%(stylesheet_path('/dir/file')) => %(/dir/file.css)
|
||||
%(stylesheet_path('/dir/file.rcss')) => %(/dir/file.rcss)
|
||||
}
|
||||
|
||||
StyleLinkToTag = {
|
||||
%(stylesheet_link_tag("style")) => %(<link href="/stylesheets/style.css" media="screen" rel="Stylesheet" type="text/css" />),
|
||||
%(stylesheet_link_tag("style.css")) => %(<link href="/stylesheets/style.css" media="screen" rel="Stylesheet" type="text/css" />),
|
||||
%(stylesheet_link_tag("/dir/file")) => %(<link href="/dir/file.css" media="screen" rel="Stylesheet" type="text/css" />),
|
||||
%(stylesheet_link_tag("dir/file")) => %(<link href="/stylesheets/dir/file.css" media="screen" rel="Stylesheet" type="text/css" />),
|
||||
%(stylesheet_link_tag("style", :media => "all")) => %(<link href="/stylesheets/style.css" media="all" rel="Stylesheet" type="text/css" />),
|
||||
@@ -75,18 +80,28 @@ class AssetTagHelperTest < Test::Unit::TestCase
|
||||
}
|
||||
|
||||
ImagePathToTag = {
|
||||
%(image_path("xml")) => %(/images/xml.png),
|
||||
%(image_path("xml.png")) => %(/images/xml.png),
|
||||
%(image_path("dir/xml.png")) => %(/images/dir/xml.png),
|
||||
%(image_path("/dir/xml.png")) => %(/dir/xml.png)
|
||||
}
|
||||
|
||||
ImageLinkToTag = {
|
||||
%(image_tag("xml")) => %(<img alt="Xml" src="/images/xml.png" />),
|
||||
%(image_tag("rss", :alt => "rss syndication")) => %(<img alt="rss syndication" src="/images/rss.png" />),
|
||||
%(image_tag("gold", :size => "45x70")) => %(<img alt="Gold" height="70" src="/images/gold.png" width="45" />),
|
||||
%(image_tag("symbolize", "size" => "45x70")) => %(<img alt="Symbolize" height="70" src="/images/symbolize.png" width="45" />),
|
||||
%(image_tag("http://www.rubyonrails.com/images/rails")) => %(<img alt="Rails" src="http://www.rubyonrails.com/images/rails.png" />)
|
||||
%(image_tag("xml.png")) => %(<img alt="Xml" src="/images/xml.png" />),
|
||||
%(image_tag("rss.gif", :alt => "rss syndication")) => %(<img alt="rss syndication" src="/images/rss.gif" />),
|
||||
%(image_tag("gold.png", :size => "45x70")) => %(<img alt="Gold" height="70" src="/images/gold.png" width="45" />),
|
||||
%(image_tag("gold.png", "size" => "45x70")) => %(<img alt="Gold" height="70" src="/images/gold.png" width="45" />),
|
||||
%(image_tag("error.png", "size" => "45")) => %(<img alt="Error" src="/images/error.png" />),
|
||||
%(image_tag("error.png", "size" => "45 x 70")) => %(<img alt="Error" src="/images/error.png" />),
|
||||
%(image_tag("error.png", "size" => "x")) => %(<img alt="Error" src="/images/error.png" />),
|
||||
%(image_tag("http://www.rubyonrails.com/images/rails.png")) => %(<img alt="Rails" src="http://www.rubyonrails.com/images/rails.png" />)
|
||||
}
|
||||
|
||||
def test_auto_discovery
|
||||
DeprecatedImagePathToTag = {
|
||||
%(image_path("xml")) => %(/images/xml.png)
|
||||
}
|
||||
|
||||
|
||||
def test_auto_discovery_link_tag
|
||||
AutoDiscoveryToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
|
||||
end
|
||||
|
||||
@@ -94,8 +109,12 @@ class AssetTagHelperTest < Test::Unit::TestCase
|
||||
JavascriptPathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
|
||||
end
|
||||
|
||||
def test_javascript_include
|
||||
def test_javascript_include_tag
|
||||
JavascriptIncludeToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
|
||||
|
||||
Object.send(:const_set, :RAILS_ROOT, File.dirname(__FILE__) + "/../fixtures/")
|
||||
ENV["RAILS_ASSET_ID"] = "1"
|
||||
assert_dom_equal(%(<script src="/javascripts/prototype.js?1" type="text/javascript"></script>\n<script src="/javascripts/effects.js?1" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js?1" type="text/javascript"></script>\n<script src="/javascripts/controls.js?1" type="text/javascript"></script>\n<script src="/javascripts/application.js?1" type="text/javascript"></script>), javascript_include_tag(:defaults))
|
||||
end
|
||||
|
||||
def test_register_javascript_include_default
|
||||
@@ -105,23 +124,25 @@ class AssetTagHelperTest < Test::Unit::TestCase
|
||||
assert_dom_equal %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/slider.js" type="text/javascript"></script>\n<script src="/javascripts/lib1.js" type="text/javascript"></script>\n<script src="/elsewhere/blub/lib2.js" type="text/javascript"></script>), javascript_include_tag(:defaults)
|
||||
end
|
||||
|
||||
def test_style_path
|
||||
def test_stylesheet_path
|
||||
StylePathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
|
||||
end
|
||||
|
||||
def test_style_link
|
||||
def test_stylesheet_link_tag
|
||||
StyleLinkToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
|
||||
end
|
||||
|
||||
def test_image_path
|
||||
ImagePathToTag.each do |method, tag|
|
||||
assert_deprecated(/image_path/) { assert_dom_equal(tag, eval(method)) }
|
||||
end
|
||||
ImagePathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
|
||||
end
|
||||
|
||||
|
||||
def test_image_tag
|
||||
ImageLinkToTag.each do |method, tag|
|
||||
assert_deprecated(/image_path/) { assert_dom_equal(tag, eval(method)) }
|
||||
ImageLinkToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
|
||||
end
|
||||
|
||||
def test_should_deprecate_image_filename_with_no_extension
|
||||
DeprecatedImagePathToTag.each do |method, tag|
|
||||
assert_deprecated("image_path") { assert_dom_equal(tag, eval(method)) }
|
||||
end
|
||||
end
|
||||
|
||||
@@ -131,12 +152,12 @@ class AssetTagHelperTest < Test::Unit::TestCase
|
||||
assert_equal %(<img alt="Rails" src="/images/rails.png?#{expected_time}" />), image_tag("rails.png")
|
||||
end
|
||||
|
||||
def test_skipping_asset_id_on_complete_url
|
||||
def test_should_skip_asset_id_on_complete_url
|
||||
Object.send(:const_set, :RAILS_ROOT, File.dirname(__FILE__) + "/../fixtures/")
|
||||
assert_equal %(<img alt="Rails" src="http://www.example.com/rails.png" />), image_tag("http://www.example.com/rails.png")
|
||||
end
|
||||
|
||||
def test_preset_asset_id
|
||||
def test_should_use_preset_asset_id
|
||||
Object.send(:const_set, :RAILS_ROOT, File.dirname(__FILE__) + "/../fixtures/")
|
||||
ENV["RAILS_ASSET_ID"] = "4500"
|
||||
assert_equal %(<img alt="Rails" src="/images/rails.png?4500" />), image_tag("rails.png")
|
||||
@@ -148,13 +169,11 @@ class AssetTagHelperTest < Test::Unit::TestCase
|
||||
assert_equal %(<img alt="Rails" src="/images/rails.png" />), image_tag("rails.png")
|
||||
end
|
||||
|
||||
def test_url_dup_image_tag
|
||||
Object.send(:const_set, :RAILS_ROOT, File.dirname(__FILE__) + "/../fixtures/")
|
||||
img_url = '/images/rails.png'
|
||||
url_copy = img_url.dup
|
||||
image_tag(img_url)
|
||||
|
||||
assert_equal url_copy, img_url
|
||||
def test_should_not_modify_source_string
|
||||
source = '/images/rails.png'
|
||||
copy = source.dup
|
||||
image_tag(source)
|
||||
assert_equal copy, source
|
||||
end
|
||||
end
|
||||
|
||||
@@ -168,13 +187,13 @@ class AssetTagHelperNonVhostTest < Test::Unit::TestCase
|
||||
attr_accessor :request
|
||||
|
||||
def url_for(options, *parameters_for_method_reference)
|
||||
"http://www.example.com/calloboration/hieraki"
|
||||
"http://www.example.com/collaboration/hieraki"
|
||||
end
|
||||
end.new
|
||||
|
||||
@request = Class.new do
|
||||
def relative_url_root
|
||||
"/calloboration/hieraki"
|
||||
"/collaboration/hieraki"
|
||||
end
|
||||
end.new
|
||||
|
||||
@@ -183,89 +202,31 @@ class AssetTagHelperNonVhostTest < Test::Unit::TestCase
|
||||
ActionView::Helpers::AssetTagHelper::reset_javascript_include_default
|
||||
end
|
||||
|
||||
AutoDiscoveryToTag = {
|
||||
%(auto_discovery_link_tag(:rss, :action => "feed")) => %(<link href="http://www.example.com/calloboration/hieraki" rel="alternate" title="RSS" type="application/rss+xml" />),
|
||||
%(auto_discovery_link_tag(:atom)) => %(<link href="http://www.example.com/calloboration/hieraki" rel="alternate" title="ATOM" type="application/atom+xml" />),
|
||||
%(auto_discovery_link_tag) => %(<link href="http://www.example.com/calloboration/hieraki" rel="alternate" title="RSS" type="application/rss+xml" />),
|
||||
}
|
||||
|
||||
JavascriptPathToTag = {
|
||||
%(javascript_path("xmlhr")) => %(/calloboration/hieraki/javascripts/xmlhr.js),
|
||||
}
|
||||
|
||||
JavascriptIncludeToTag = {
|
||||
%(javascript_include_tag("xmlhr")) => %(<script src="/calloboration/hieraki/javascripts/xmlhr.js" type="text/javascript"></script>),
|
||||
%(javascript_include_tag("common.javascript", "/elsewhere/cools")) => %(<script src="/calloboration/hieraki/javascripts/common.javascript" type="text/javascript"></script>\n<script src="/calloboration/hieraki/elsewhere/cools.js" type="text/javascript"></script>),
|
||||
%(javascript_include_tag(:defaults)) => %(<script src="/calloboration/hieraki/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/calloboration/hieraki/javascripts/effects.js" type="text/javascript"></script>\n<script src="/calloboration/hieraki/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/calloboration/hieraki/javascripts/controls.js" type="text/javascript"></script>)
|
||||
}
|
||||
|
||||
StylePathToTag = {
|
||||
%(stylesheet_path("style")) => %(/calloboration/hieraki/stylesheets/style.css),
|
||||
}
|
||||
|
||||
StyleLinkToTag = {
|
||||
%(stylesheet_link_tag("style")) => %(<link href="/calloboration/hieraki/stylesheets/style.css" media="screen" rel="Stylesheet" type="text/css" />),
|
||||
%(stylesheet_link_tag("random.styles", "/css/stylish")) => %(<link href="/calloboration/hieraki/stylesheets/random.styles" media="screen" rel="Stylesheet" type="text/css" />\n<link href="/calloboration/hieraki/css/stylish.css" media="screen" rel="Stylesheet" type="text/css" />)
|
||||
}
|
||||
|
||||
ImagePathToTag = {
|
||||
%(image_path("xml")) => %(/calloboration/hieraki/images/xml.png),
|
||||
}
|
||||
|
||||
ImageLinkToTag = {
|
||||
%(image_tag("xml")) => %(<img alt="Xml" src="/calloboration/hieraki/images/xml.png" />),
|
||||
%(image_tag("rss", :alt => "rss syndication")) => %(<img alt="rss syndication" src="/calloboration/hieraki/images/rss.png" />),
|
||||
%(image_tag("gold", :size => "45x70")) => %(<img alt="Gold" height="70" src="/calloboration/hieraki/images/gold.png" width="45" />),
|
||||
%(image_tag("symbolize", "size" => "45x70")) => %(<img alt="Symbolize" height="70" src="/calloboration/hieraki/images/symbolize.png" width="45" />)
|
||||
}
|
||||
|
||||
def test_auto_discovery
|
||||
AutoDiscoveryToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
|
||||
end
|
||||
|
||||
def test_javascript_path
|
||||
JavascriptPathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
|
||||
end
|
||||
|
||||
def test_javascript_include
|
||||
JavascriptIncludeToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
|
||||
def test_should_compute_proper_path
|
||||
assert_dom_equal(%(<link href="http://www.example.com/collaboration/hieraki" rel="alternate" title="RSS" type="application/rss+xml" />), auto_discovery_link_tag)
|
||||
assert_dom_equal(%(/collaboration/hieraki/javascripts/xmlhr.js), javascript_path("xmlhr"))
|
||||
assert_dom_equal(%(/collaboration/hieraki/stylesheets/style.css), stylesheet_path("style"))
|
||||
assert_dom_equal(%(/collaboration/hieraki/images/xml.png), image_path("xml.png"))
|
||||
end
|
||||
|
||||
def test_register_javascript_include_default
|
||||
ActionView::Helpers::AssetTagHelper::register_javascript_include_default 'slider'
|
||||
assert_dom_equal %(<script src="/calloboration/hieraki/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/calloboration/hieraki/javascripts/effects.js" type="text/javascript"></script>\n<script src="/calloboration/hieraki/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/calloboration/hieraki/javascripts/controls.js" type="text/javascript"></script>\n<script src="/calloboration/hieraki/javascripts/slider.js" type="text/javascript"></script>), javascript_include_tag(:defaults)
|
||||
ActionView::Helpers::AssetTagHelper::register_javascript_include_default 'lib1', '/elsewhere/blub/lib2'
|
||||
assert_dom_equal %(<script src="/calloboration/hieraki/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/calloboration/hieraki/javascripts/effects.js" type="text/javascript"></script>\n<script src="/calloboration/hieraki/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/calloboration/hieraki/javascripts/controls.js" type="text/javascript"></script>\n<script src="/calloboration/hieraki/javascripts/slider.js" type="text/javascript"></script>\n<script src="/calloboration/hieraki/javascripts/lib1.js" type="text/javascript"></script>\n<script src="/calloboration/hieraki/elsewhere/blub/lib2.js" type="text/javascript"></script>), javascript_include_tag(:defaults)
|
||||
def test_should_ignore_relative_root_path_on_complete_url
|
||||
assert_dom_equal(%(http://www.example.com/images/xml.png), image_path("http://www.example.com/images/xml.png"))
|
||||
end
|
||||
|
||||
def test_style_path
|
||||
StylePathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
|
||||
end
|
||||
|
||||
def test_style_link
|
||||
StyleLinkToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
|
||||
end
|
||||
|
||||
def test_image_path
|
||||
ImagePathToTag.each { |method, tag| assert_deprecated(/image_path/) { assert_dom_equal(tag, eval(method)) } }
|
||||
end
|
||||
|
||||
def test_image_tag
|
||||
ImageLinkToTag.each do |method, tag|
|
||||
assert_deprecated(/image_path/) { assert_dom_equal(tag, eval(method)) }
|
||||
end
|
||||
# Assigning a default alt tag should not cause an exception to be raised
|
||||
assert_nothing_raised { image_tag('') }
|
||||
end
|
||||
|
||||
def test_stylesheet_with_asset_host_already_encoded
|
||||
ActionController::Base.asset_host = "http://foo.example.com"
|
||||
result = stylesheet_link_tag("http://bar.example.com/stylesheets/style.css")
|
||||
assert_dom_equal(
|
||||
%(<link href="http://bar.example.com/stylesheets/style.css" media="screen" rel="Stylesheet" type="text/css" />),
|
||||
result)
|
||||
def test_should_compute_proper_path_with_asset_host
|
||||
ActionController::Base.asset_host = "http://assets.example.com"
|
||||
assert_dom_equal(%(<link href="http://www.example.com/collaboration/hieraki" rel="alternate" title="RSS" type="application/rss+xml" />), auto_discovery_link_tag)
|
||||
assert_dom_equal(%(http://assets.example.com/collaboration/hieraki/javascripts/xmlhr.js), javascript_path("xmlhr"))
|
||||
assert_dom_equal(%(http://assets.example.com/collaboration/hieraki/stylesheets/style.css), stylesheet_path("style"))
|
||||
assert_dom_equal(%(http://assets.example.com/collaboration/hieraki/images/xml.png), image_path("xml.png"))
|
||||
ensure
|
||||
ActionController::Base.asset_host = ""
|
||||
end
|
||||
|
||||
def test_should_ignore_asset_host_on_complete_url
|
||||
ActionController::Base.asset_host = "http://assets.example.com"
|
||||
assert_dom_equal(%(<link href="http://bar.example.com/stylesheets/style.css" media="screen" rel="Stylesheet" type="text/css" />), stylesheet_link_tag("http://bar.example.com/stylesheets/style.css"))
|
||||
ensure
|
||||
ActionController::Base.asset_host = ""
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
36
actionpack/test/template/deprecated_helper_test.rb
Normal file
36
actionpack/test/template/deprecated_helper_test.rb
Normal file
@@ -0,0 +1,36 @@
|
||||
require File.dirname(__FILE__) + '/../abstract_unit'
|
||||
|
||||
class DeprecatedHelperTest < Test::Unit::TestCase
|
||||
include ActionView::Helpers::JavaScriptHelper
|
||||
include ActionView::Helpers::CaptureHelper
|
||||
|
||||
def test_update_element_function
|
||||
assert_deprecated 'update_element_function' do
|
||||
|
||||
assert_equal %($('myelement').innerHTML = 'blub';\n),
|
||||
update_element_function('myelement', :content => 'blub')
|
||||
assert_equal %($('myelement').innerHTML = 'blub';\n),
|
||||
update_element_function('myelement', :action => :update, :content => 'blub')
|
||||
assert_equal %($('myelement').innerHTML = '';\n),
|
||||
update_element_function('myelement', :action => :empty)
|
||||
assert_equal %(Element.remove('myelement');\n),
|
||||
update_element_function('myelement', :action => :remove)
|
||||
|
||||
assert_equal %(new Insertion.Bottom('myelement','blub');\n),
|
||||
update_element_function('myelement', :position => 'bottom', :content => 'blub')
|
||||
assert_equal %(new Insertion.Bottom('myelement','blub');\n),
|
||||
update_element_function('myelement', :action => :update, :position => :bottom, :content => 'blub')
|
||||
|
||||
_erbout = ""
|
||||
assert_equal %($('myelement').innerHTML = 'test';\n),
|
||||
update_element_function('myelement') { _erbout << "test" }
|
||||
|
||||
_erbout = ""
|
||||
assert_equal %($('myelement').innerHTML = 'blockstuff';\n),
|
||||
update_element_function('myelement', :content => 'paramstuff') { _erbout << "blockstuff" }
|
||||
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
@@ -396,7 +396,31 @@ class FormHelperTest < Test::Unit::TestCase
|
||||
|
||||
assert_dom_equal expected, _erbout
|
||||
end
|
||||
|
||||
|
||||
def test_default_form_builder
|
||||
old_default_form_builder, ActionView::Base.default_form_builder =
|
||||
ActionView::Base.default_form_builder, LabelledFormBuilder
|
||||
|
||||
_erbout = ''
|
||||
form_for(:post, @post) do |f|
|
||||
_erbout.concat f.text_field(:title)
|
||||
_erbout.concat f.text_area(:body)
|
||||
_erbout.concat f.check_box(:secret)
|
||||
end
|
||||
|
||||
expected =
|
||||
"<form action='http://www.example.com' method='post'>" +
|
||||
"<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" +
|
||||
"<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" +
|
||||
"<label for='secret'>Secret:</label> <input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
|
||||
"<input name='post[secret]' type='hidden' value='0' /><br/>" +
|
||||
"</form>"
|
||||
|
||||
assert_dom_equal expected, _erbout
|
||||
ensure
|
||||
ActionView::Base.default_form_builder = old_default_form_builder
|
||||
end
|
||||
|
||||
# Perhaps this test should be moved to prototype helper tests.
|
||||
def test_remote_form_for_with_labelled_builder
|
||||
self.extend ActionView::Helpers::PrototypeHelper
|
||||
|
||||
@@ -143,30 +143,6 @@ class PrototypeHelperTest < Test::Unit::TestCase
|
||||
assert_dom_equal %(<script type=\"text/javascript\">\n//<![CDATA[\nnew Form.Observer('cart', 2, function(element, value) {alert('Form changed')})\n//]]>\n</script>),
|
||||
observe_form("cart", :frequency => 2, :function => "alert('Form changed')")
|
||||
end
|
||||
|
||||
def test_update_element_function
|
||||
assert_equal %($('myelement').innerHTML = 'blub';\n),
|
||||
update_element_function('myelement', :content => 'blub')
|
||||
assert_equal %($('myelement').innerHTML = 'blub';\n),
|
||||
update_element_function('myelement', :action => :update, :content => 'blub')
|
||||
assert_equal %($('myelement').innerHTML = '';\n),
|
||||
update_element_function('myelement', :action => :empty)
|
||||
assert_equal %(Element.remove('myelement');\n),
|
||||
update_element_function('myelement', :action => :remove)
|
||||
|
||||
assert_equal %(new Insertion.Bottom('myelement','blub');\n),
|
||||
update_element_function('myelement', :position => 'bottom', :content => 'blub')
|
||||
assert_equal %(new Insertion.Bottom('myelement','blub');\n),
|
||||
update_element_function('myelement', :action => :update, :position => :bottom, :content => 'blub')
|
||||
|
||||
_erbout = ""
|
||||
assert_equal %($('myelement').innerHTML = 'test';\n),
|
||||
update_element_function('myelement') { _erbout << "test" }
|
||||
|
||||
_erbout = ""
|
||||
assert_equal %($('myelement').innerHTML = 'blockstuff';\n),
|
||||
update_element_function('myelement', :content => 'paramstuff') { _erbout << "blockstuff" }
|
||||
end
|
||||
|
||||
def test_update_page
|
||||
block = Proc.new { |page| page.replace_html('foo', 'bar') }
|
||||
|
||||
@@ -7,8 +7,9 @@ class TagHelperTest < Test::Unit::TestCase
|
||||
include ActionView::Helpers::CaptureHelper
|
||||
|
||||
def test_tag
|
||||
assert_equal "<p class=\"show\" />", tag("p", "class" => "show")
|
||||
assert_equal tag("p", "class" => "show"), tag("p", :class => "show")
|
||||
assert_equal "<br />", tag("br")
|
||||
assert_equal "<br clear=\"left\" />", tag(:br, :clear => "left")
|
||||
assert_equal "<br>", tag("br", nil, true)
|
||||
end
|
||||
|
||||
def test_tag_options
|
||||
|
||||
@@ -11,17 +11,21 @@ class TextHelperTest < Test::Unit::TestCase
|
||||
# a view is rendered. The cycle helper depends on this behavior.
|
||||
@_cycles = nil if (defined? @_cycles)
|
||||
end
|
||||
|
||||
|
||||
def test_simple_format
|
||||
assert_equal "<p></p>", simple_format(nil)
|
||||
|
||||
assert_equal "<p>crazy\n<br /> cross\n<br /> platform linebreaks</p>", simple_format("crazy\r\n cross\r platform linebreaks")
|
||||
assert_equal "<p>A paragraph</p>\n\n<p>and another one!</p>", simple_format("A paragraph\n\nand another one!")
|
||||
assert_equal "<p>A paragraph\n<br /> With a newline</p>", simple_format("A paragraph\n With a newline")
|
||||
|
||||
text = "A\nB\nC\nD"
|
||||
|
||||
text = "A\nB\nC\nD".freeze
|
||||
assert_equal "<p>A\n<br />B\n<br />C\n<br />D</p>", simple_format(text)
|
||||
assert_equal text, "A\nB\nC\nD"
|
||||
|
||||
text = "A\r\n \nB\n\n\r\n\t\nC\nD".freeze
|
||||
assert_equal "<p>A\n<br /> \n<br />B</p>\n\n<p>\t\n<br />C\n<br />D</p>", simple_format(text)
|
||||
end
|
||||
|
||||
|
||||
def test_truncate
|
||||
assert_equal "Hello World!", truncate("Hello World!", 12)
|
||||
assert_equal "Hello Wor...", truncate("Hello World!!", 12)
|
||||
@@ -193,7 +197,7 @@ class TextHelperTest < Test::Unit::TestCase
|
||||
def test_sanitize_form
|
||||
raw = "<form action=\"/foo/bar\" method=\"post\"><input></form>"
|
||||
result = sanitize(raw)
|
||||
assert_equal "<form action='/foo/bar' method='post'><input></form>", result
|
||||
assert_equal %(<form action="/foo/bar" method="post"><input></form>), result
|
||||
end
|
||||
|
||||
def test_sanitize_plaintext
|
||||
@@ -205,25 +209,25 @@ class TextHelperTest < Test::Unit::TestCase
|
||||
def test_sanitize_script
|
||||
raw = "<script language=\"Javascript\">blah blah blah</script>"
|
||||
result = sanitize(raw)
|
||||
assert_equal "<script language='Javascript'>blah blah blah</script>", result
|
||||
assert_equal %(<script language="Javascript">blah blah blah</script>), result
|
||||
end
|
||||
|
||||
def test_sanitize_js_handlers
|
||||
raw = %{onthis="do that" <a href="#" onclick="hello" name="foo" onbogus="remove me">hello</a>}
|
||||
result = sanitize(raw)
|
||||
assert_equal %{onthis="do that" <a name='foo' href='#'>hello</a>}, result
|
||||
assert_equal %{onthis="do that" <a name="foo" href="#">hello</a>}, result
|
||||
end
|
||||
|
||||
def test_sanitize_javascript_href
|
||||
raw = %{href="javascript:bang" <a href="javascript:bang" name="hello">foo</a>, <span href="javascript:bang">bar</span>}
|
||||
result = sanitize(raw)
|
||||
assert_equal %{href="javascript:bang" <a name='hello'>foo</a>, <span>bar</span>}, result
|
||||
assert_equal %{href="javascript:bang" <a name="hello">foo</a>, <span>bar</span>}, result
|
||||
end
|
||||
|
||||
def test_sanitize_image_src
|
||||
raw = %{src="javascript:bang" <img src="javascript:bang" width="5">foo</img>, <span src="javascript:bang">bar</span>}
|
||||
result = sanitize(raw)
|
||||
assert_equal %{src="javascript:bang" <img width='5'>foo</img>, <span>bar</span>}, result
|
||||
assert_equal %{src="javascript:bang" <img width="5">foo</img>, <span>bar</span>}, result
|
||||
end
|
||||
|
||||
def test_cycle_class
|
||||
@@ -316,6 +320,6 @@ class TextHelperTest < Test::Unit::TestCase
|
||||
%{This is a test.\n\n\nIt no longer contains any HTML.\n}, strip_tags(
|
||||
%{<title>This is <b>a <a href="" target="_blank">test</a></b>.</title>\n\n<!-- it has a comment -->\n\n<p>It no <b>longer <strong>contains <em>any <strike>HTML</strike></em>.</strong></b></p>\n}))
|
||||
assert_equal "This has a here.", strip_tags("This has a <!-- comment --> here.")
|
||||
[nil, '', ' '].each { |blank| assert_nil strip_tags(blank) }
|
||||
[nil, '', ' '].each { |blank| assert_equal blank, strip_tags(blank) }
|
||||
end
|
||||
end
|
||||
|
||||
@@ -4,7 +4,7 @@ require File.dirname(__FILE__) + '/../../lib/action_view/helpers/url_helper'
|
||||
require File.dirname(__FILE__) + '/../../lib/action_view/helpers/asset_tag_helper'
|
||||
require File.dirname(__FILE__) + '/../../lib/action_view/helpers/tag_helper'
|
||||
|
||||
RequestMock = Struct.new("Request", :request_uri)
|
||||
RequestMock = Struct.new("Request", :request_uri, :protocol, :host_with_port)
|
||||
|
||||
class UrlHelperTest < Test::Unit::TestCase
|
||||
include ActionView::Helpers::AssetTagHelper
|
||||
@@ -202,12 +202,16 @@ class UrlHelperTest < Test::Unit::TestCase
|
||||
@controller.request = RequestMock.new("http://www.example.com/weblog/show")
|
||||
@controller.url = "http://www.example.com/weblog/show"
|
||||
assert_equal "Showing", link_to_unless_current("Showing", { :action => "show", :controller => "weblog" })
|
||||
assert_equal "Showing", link_to_unless_current("Showing", "http://www.example.com/weblog/show")
|
||||
|
||||
@controller.request = RequestMock.new("http://www.example.com/weblog/show")
|
||||
@controller.url = "http://www.example.com/weblog/list"
|
||||
assert_equal "<a href=\"http://www.example.com/weblog/list\">Listing</a>", link_to_unless_current("Listing", :action => "list", :controller => "weblog")
|
||||
assert_equal "<a href=\"http://www.example.com/weblog/list\">Listing</a>",
|
||||
link_to_unless_current("Listing", :action => "list", :controller => "weblog")
|
||||
assert_equal "<a href=\"http://www.example.com/weblog/list\">Listing</a>",
|
||||
link_to_unless_current("Listing", "http://www.example.com/weblog/list")
|
||||
end
|
||||
|
||||
|
||||
def test_mail_to
|
||||
assert_dom_equal "<a href=\"mailto:david@loudthinking.com\">david@loudthinking.com</a>", mail_to("david@loudthinking.com")
|
||||
assert_dom_equal "<a href=\"mailto:david@loudthinking.com\">David Heinemeier Hansson</a>", mail_to("david@loudthinking.com", "David Heinemeier Hansson")
|
||||
@@ -301,3 +305,62 @@ class UrlHelperWithControllerTest < Test::Unit::TestCase
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
class LinkToUnlessCurrentWithControllerTest < Test::Unit::TestCase
|
||||
class TasksController < ActionController::Base
|
||||
self.template_root = "#{File.dirname(__FILE__)}/../fixtures/"
|
||||
|
||||
def self.controller_path; 'tasks' end
|
||||
|
||||
def index
|
||||
render_default
|
||||
end
|
||||
|
||||
def show
|
||||
render_default
|
||||
end
|
||||
|
||||
def rescue_action(e) raise e end
|
||||
|
||||
protected
|
||||
def render_default
|
||||
render :inline =>
|
||||
"<%= link_to_unless_current(\"tasks\", tasks_path) %>\n" +
|
||||
"<%= link_to_unless_current(\"tasks\", tasks_url) %>"
|
||||
end
|
||||
end
|
||||
|
||||
include ActionView::Helpers::UrlHelper
|
||||
|
||||
def setup
|
||||
@request = ActionController::TestRequest.new
|
||||
@response = ActionController::TestResponse.new
|
||||
@controller = TasksController.new
|
||||
end
|
||||
|
||||
def test_link_to_unless_current_to_current
|
||||
with_restful_routing do
|
||||
get :index
|
||||
assert_equal "tasks\ntasks", @response.body
|
||||
end
|
||||
end
|
||||
|
||||
def test_link_to_unless_current_shows_link
|
||||
with_restful_routing do
|
||||
get :show, :id => 1
|
||||
assert_equal "<a href=\"/tasks\">tasks</a>\n" +
|
||||
"<a href=\"#{@request.protocol}#{@request.host_with_port}/tasks\">tasks</a>",
|
||||
@response.body
|
||||
end
|
||||
end
|
||||
|
||||
protected
|
||||
def with_restful_routing
|
||||
with_routing do |set|
|
||||
set.draw do |map|
|
||||
map.resources :tasks
|
||||
end
|
||||
yield
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,28 +1,37 @@
|
||||
*SVN*
|
||||
|
||||
* Removed deprecated @request and @response usages. [Kent Sibilev]
|
||||
*1.2.0* (January 16th, 2007)
|
||||
|
||||
* Removed invocation of deprecated before_action and around_action filter methods. Corresponding before_invocation and after_invocation methods should be used instead. #6275 [Kent Sibilev]
|
||||
|
||||
* Provide access to the underlying SOAP driver. #6212 [bmilekic, Kent Sibilev]
|
||||
|
||||
* Deprecation: update docs. #5998 [jakob@mentalized.net, Kevin Clark]
|
||||
|
||||
* ActionWebService WSDL generation ignores HTTP_X_FORWARDED_HOST [Paul Butcher <paul@paulbutcher.com>]
|
||||
|
||||
* Tighten rescue clauses. #5985 [james@grayproductions.net]
|
||||
|
||||
* Fixed XMLRPC multicall when one of the called methods returns a struct object. [Kent Sibilev]
|
||||
|
||||
* Replace Reloadable with Reloadable::Deprecated. [Nicholas Seckar]
|
||||
|
||||
* Fix invoke_layered since api_method didn't declare :expects. Closes #4720. [Kevin Ballard <kevin@sb.org>, Kent Sibilev]
|
||||
|
||||
* Replace alias method chaining with Module#alias_method_chain. [Marcel Molina Jr.]
|
||||
|
||||
* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.]
|
||||
*1.1.6* (August 10th, 2006)
|
||||
|
||||
* Rely on Action Pack 1.12.5
|
||||
|
||||
|
||||
*1.1.5* (August 8th, 2006)
|
||||
|
||||
* Rely on Action Pack 1.12.4 and Active Record 1.14.4
|
||||
|
||||
|
||||
*1.1.4* (June 29th, 2006)
|
||||
|
||||
* Rely on Action Pack 1.12.3
|
||||
|
||||
|
||||
*1.1.3* (June 27th, 2006)
|
||||
|
||||
* Rely on Action Pack 1.12.2 and Active Record 1.14.3
|
||||
|
||||
* Fix test database name typo. [Marcel Molina Jr.]
|
||||
|
||||
*1.1.2* (April 9th, 2006)
|
||||
|
||||
|
||||
@@ -71,8 +71,8 @@ spec = Gem::Specification.new do |s|
|
||||
s.rubyforge_project = "aws"
|
||||
s.homepage = "http://www.rubyonrails.org"
|
||||
|
||||
s.add_dependency('actionpack', '= 1.12.5' + PKG_BUILD)
|
||||
s.add_dependency('activerecord', '= 1.14.4' + PKG_BUILD)
|
||||
s.add_dependency('actionpack', '= 1.13.0' + PKG_BUILD)
|
||||
s.add_dependency('activerecord', '= 1.15.0' + PKG_BUILD)
|
||||
|
||||
s.has_rdoc = true
|
||||
s.requirements << 'none'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<h4>Method Invocation Details for <em><%= @scaffold_service %>#<%= @scaffold_method.public_name %></em></h4>
|
||||
|
||||
<%= form_tag :action => @scaffold_action_name + '_submit' %>
|
||||
<% form_tag(:action => @scaffold_action_name + '_submit') do -%>
|
||||
<%= hidden_field_tag "service", @scaffold_service.name %>
|
||||
<%= hidden_field_tag "method", @scaffold_method.public_name %>
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
<% end %>
|
||||
|
||||
<%= submit_tag "Invoke" %>
|
||||
<%= end_form_tag %>
|
||||
<% end -%>
|
||||
|
||||
<p>
|
||||
<%= link_to "Back", :action => @scaffold_action_name %>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
module ActionWebService
|
||||
module VERSION #:nodoc:
|
||||
MAJOR = 1
|
||||
MINOR = 1
|
||||
TINY = 6
|
||||
MINOR = 2
|
||||
TINY = 0
|
||||
|
||||
STRING = [MAJOR, MINOR, TINY].join('.')
|
||||
end
|
||||
|
||||
@@ -84,6 +84,7 @@ class ScaffoldedControllerTest < Test::Unit::TestCase
|
||||
def test_scaffold_invoke_method_params_with_struct
|
||||
get :scaffold_invoke_method_params, :service => 'scaffolded', :method => 'HelloStructParam'
|
||||
assert_template 'parameters.rhtml'
|
||||
assert_tag :tag => 'form'
|
||||
assert_tag :tag => 'input', :attributes => {:name => "method_params[0][name]"}
|
||||
end
|
||||
|
||||
|
||||
@@ -1,10 +1,67 @@
|
||||
*SVN*
|
||||
*1.15.0* (January 16th, 2007)
|
||||
|
||||
* [DOC] clear up some ambiguity with the way has_and_belongs_to_many creates the default join table name. #7072 [jeremymcanally]
|
||||
|
||||
* change_column accepts :default => nil. Skip column options for primary keys. #6956, #7048 [dcmanges, Jeremy Kemper]
|
||||
|
||||
* MySQL, PostgreSQL: change_column_default quotes the default value and doesn't lose column type information. #3987, #6664 [Jonathan Viney, manfred, altano@bigfoot.com]
|
||||
|
||||
* Oracle: create_table takes a :sequence_name option to override the 'tablename_seq' default. #7000 [Michael Schoen]
|
||||
|
||||
* MySQL: retain SSL settings on reconnect. #6976 [randyv2]
|
||||
|
||||
* SQLServer: handle [quoted] table names. #6635 [rrich]
|
||||
|
||||
* acts_as_nested_set works with single-table inheritance. #6030 [Josh Susser]
|
||||
|
||||
* PostgreSQL, Oracle: correctly perform eager finds with :limit and :order. #4668, #7021 [eventualbuddha, Michael Schoen]
|
||||
|
||||
* Fix the Oracle adapter for serialized attributes stored in CLOBs. Closes #6825 [mschoen, tdfowler]
|
||||
|
||||
* [DOCS] Apply more documentation for ActiveRecord Reflection. Closes #4055 [Robby Russell]
|
||||
|
||||
* [DOCS] Document :allow_nil option of #validate_uniqueness_of. Closes #3143 [Caio Chassot]
|
||||
|
||||
* Bring the sybase adapter up to scratch for 1.2 release. [jsheets]
|
||||
|
||||
* Oracle: fix connection reset failure. #6846 [leonlleslie]
|
||||
|
||||
* Subclass instantiation doesn't try to explicitly require the corresponding subclass. #6840 [leei, Jeremy Kemper]
|
||||
|
||||
* fix faulty inheritance tests and that eager loading grabs the wrong inheritance column when the class of your association is an STI subclass. Closes #6859 [protocool]
|
||||
|
||||
* find supports :lock with :include. Check whether your database allows SELECT ... FOR UPDATE with outer joins before using. #6764 [vitaly, Jeremy Kemper]
|
||||
|
||||
* Support nil and Array in :conditions => { attr => value } hashes. #6548 [Assaf, Jeremy Kemper]
|
||||
find(:all, :conditions => { :topic_id => [1, 2, 3], :last_read => nil }
|
||||
|
||||
* Quote ActiveSupport::Multibyte::Chars. #6653 [Julian Tarkhanov]
|
||||
|
||||
* MySQL: detect when a NOT NULL column without a default value is misreported as default ''. Can't detect for string, text, and binary columns since '' is a legitimate default. #6156 [simon@redhillconsulting.com.au, obrie, Jonathan Viney, Jeremy Kemper]
|
||||
|
||||
* validates_numericality_of uses \A \Z to ensure the entire string matches rather than ^ $ which may match one valid line of a multiline string. #5716 [Andreas Schwarz]
|
||||
|
||||
* Oracle: automatically detect the primary key. #6594 [vesaria, Michael Schoen]
|
||||
|
||||
* Oracle: to increase performance, prefetch 100 rows and enable similar cursor sharing. Both are configurable in database.yml. #6607 [philbogle@gmail.com, ray.fortna@jobster.com, Michael Schoen]
|
||||
|
||||
* Firebird: decimal/numeric support. #6408 [macrnic]
|
||||
|
||||
* Find with :include respects scoped :order. #5850
|
||||
|
||||
* Dynamically generate reader methods for serialized attributes. #6362 [Stefan Kaes]
|
||||
|
||||
* Deprecation: object transactions warning. [Jeremy Kemper]
|
||||
|
||||
* has_one :dependent => :nullify ignores nil associates. #6528 [janovetz, Jeremy Kemper]
|
||||
|
||||
* Oracle: resolve test failures, use prefetched primary key for inserts, check for null defaults, fix limited id selection for eager loading. Factor out some common methods from all adapters. #6515 [Michael Schoen]
|
||||
|
||||
* Make add_column use the options hash with the Sqlite Adapter. Closes #6464 [obrie]
|
||||
|
||||
* Document other options available to migration's add_column. #6419 [grg]
|
||||
|
||||
* MySQL: all_hashes compatibility with old MysqlRes class. #6429 [Jeremy Kemper]
|
||||
* MySQL: all_hashes compatibility with old MysqlRes class. #6429, #6601 [Jeremy Kemper]
|
||||
|
||||
* Fix has_many :through to add the appropriate conditions when going through an association using STI. Closes #5783. [Jonathan Viney]
|
||||
|
||||
@@ -58,20 +115,12 @@
|
||||
|
||||
* Deprecation: use :dependent => :delete_all rather than :exclusively_dependent => true. #6024 [Josh Susser]
|
||||
|
||||
* Document validates_presences_of behavior with booleans: you probably want validates_inclusion_of :attr, :in => [true, false]. #2253 [Bob Silva]
|
||||
|
||||
* Optimistic locking: gracefully handle nil versions, treat as zero. #5908 [Tom Ward]
|
||||
|
||||
* to_xml: the :methods option works on arrays of records. #5845 [Josh Starcher]
|
||||
|
||||
* Deprecation: update docs. #5998 [jakob@mentalized.net, Kevin Clark]
|
||||
|
||||
* Add some XmlSerialization tests for ActiveRecord [Rick Olson]
|
||||
|
||||
* has_many :through conditions are sanitized by the associating class. #5971 [martin.emde@gmail.com]
|
||||
|
||||
* Tighten rescue clauses. #5985 [james@grayproductions.net]
|
||||
|
||||
* Fix spurious newlines and spaces in AR::Base#to_xml output [Jamis Buck]
|
||||
|
||||
* has_one supports the :dependent => :delete option which skips the typical callback chain and deletes the associated object directly from the database. #5927 [Chris Mear, Jonathan Viney]
|
||||
@@ -80,8 +129,6 @@
|
||||
|
||||
* SQLServer: work around bug where some unambiguous date formats are not correctly identified if the session language is set to german. #5894 [Tom Ward, kruth@bfpi]
|
||||
|
||||
* SQLServer: fix eager association test. #5901 [Tom Ward]
|
||||
|
||||
* Clashing type columns due to a sloppy join shouldn't wreck single-table inheritance. #5838 [Kevin Clark]
|
||||
|
||||
* Fixtures: correct escaping of \n and \r. #5859 [evgeny.zislis@gmail.com]
|
||||
@@ -132,16 +179,12 @@
|
||||
|
||||
* Remove ActiveRecord::Base.reset since Dispatcher doesn't use it anymore. [Rick Olson]
|
||||
|
||||
* Document find's :from option. Closes #5762. [andrew@redlinesoftware.com]
|
||||
|
||||
* PostgreSQL: autodetected sequences work correctly with multiple schemas. Rely on the schema search_path instead of explicitly qualifying the sequence name with its schema. #5280 [guy.naor@famundo.com]
|
||||
|
||||
* Replace Reloadable with Reloadable::Deprecated. [Nicholas Seckar]
|
||||
|
||||
* Cache nil results for has_one associations so multiple calls don't call the database. Closes #5757. [Michael A. Schoen]
|
||||
|
||||
* Add documentation for how to disable timestamps on a per model basis. Closes #5684. [matt@mattmargolis.net Marcel Molina Jr.]
|
||||
|
||||
* Don't save has_one associations unnecessarily. #5735 [Jonathan Viney]
|
||||
|
||||
* Refactor ActiveRecord::Base.reset_subclasses to #reset, and add global observer resetting. [Rick Olson]
|
||||
@@ -190,8 +233,6 @@
|
||||
|
||||
* PostgreSQL: create/drop as postgres user. #4790 [mail@matthewpainter.co.uk, mlaster@metavillage.com]
|
||||
|
||||
* Update callbacks documentation. #3970 [Robby Russell <robby@planetargon.com>]
|
||||
|
||||
* PostgreSQL: correctly quote the ' in pk_and_sequence_for. #5462 [tietew@tietew.net]
|
||||
|
||||
* PostgreSQL: correctly quote microseconds in timestamps. #5641 [rick@rickbradley.com]
|
||||
@@ -204,8 +245,6 @@
|
||||
|
||||
* Added :group to available options for finds done on associations #5516 [mike@michaeldewey.org]
|
||||
|
||||
* Minor tweak to improve performance of ActiveRecord::Base#to_param.
|
||||
|
||||
* Observers also watch subclasses created after they are declared. #5535 [daniels@pronto.com.au]
|
||||
|
||||
* Removed deprecated timestamps_gmt class methods. [Jeremy Kemper]
|
||||
@@ -305,22 +344,10 @@
|
||||
|
||||
* Allow AR::Base#to_xml to include methods too. Closes #4921. [johan@textdrive.com]
|
||||
|
||||
* Replace superfluous name_to_class_name variant with camelize. [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.]
|
||||
|
||||
* Remove duplicate fixture entry in comments.yml. Closes #4923. [Blair Zajac <blair@orcaware.com>]
|
||||
|
||||
* Update FrontBase adapter to check binding version. Closes #4920. [mlaster@metavillage.com]
|
||||
|
||||
* New Frontbase connections don't start in auto-commit mode. Closes #4922. [mlaster@metavillage.com]
|
||||
|
||||
* When grouping, use the appropriate option key. [Marcel Molina Jr.]
|
||||
|
||||
* Only modify the sequence name in the FrontBase adapter if the FrontBase adapter is actually being used. [Marcel Molina Jr.]
|
||||
|
||||
* Add support for FrontBase (http://www.frontbase.com/) with a new adapter thanks to the hard work of one Mike Laster. Closes #4093. [mlaster@metavillage.com]
|
||||
|
||||
* Add warning about the proper way to validate the presence of a foreign key. Closes #4147. [Francois Beausoleil <francois.beausoleil@gmail.com>]
|
||||
@@ -348,8 +375,6 @@
|
||||
|
||||
* Allow all calculations to take the :include option, not just COUNT (closes #4840) [Rick]
|
||||
|
||||
* Update inconsistent migrations documentation. #4683 [machomagna@gmail.com]
|
||||
|
||||
* Add ActiveRecord::Errors#to_xml [Jamis Buck]
|
||||
|
||||
* Properly quote index names in migrations (closes #4764) [John Long]
|
||||
@@ -360,10 +385,6 @@
|
||||
|
||||
* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. [Rick]
|
||||
|
||||
* DRY up association collection reader method generation. [Marcel Molina Jr.]
|
||||
|
||||
* DRY up and tweak style of the validation error object. [Marcel Molina Jr.]
|
||||
|
||||
* Add :case_sensitive option to validates_uniqueness_of (closes #3090) [Rick]
|
||||
|
||||
class Account < ActiveRecord::Base
|
||||
@@ -377,7 +398,29 @@
|
||||
end
|
||||
|
||||
|
||||
*1.14.2* (April 9th, 2005)
|
||||
*1.14.4* (August 8th, 2006)
|
||||
|
||||
* Add warning about the proper way to validate the presence of a foreign key. #4147 [Francois Beausoleil <francois.beausoleil@gmail.com>]
|
||||
|
||||
* Fix syntax error in documentation. #4679 [mislav@nippur.irb.hr]
|
||||
|
||||
* Update inconsistent migrations documentation. #4683 [machomagna@gmail.com]
|
||||
|
||||
|
||||
*1.14.3* (June 27th, 2006)
|
||||
|
||||
* Fix announcement of very long migration names. #5722 [blake@near-time.com]
|
||||
|
||||
* Update callbacks documentation. #3970 [Robby Russell <robby@planetargon.com>]
|
||||
|
||||
* Properly quote index names in migrations (closes #4764) [John Long]
|
||||
|
||||
* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions [Rick]
|
||||
|
||||
* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. [Rick]
|
||||
|
||||
|
||||
*1.14.2* (April 9th, 2006)
|
||||
|
||||
* Fixed calculations for the Oracle Adapter (closes #4626) [Michael Schoen]
|
||||
|
||||
|
||||
@@ -151,7 +151,7 @@ spec = Gem::Specification.new do |s|
|
||||
s.files = s.files + Dir.glob( "#{dir}/**/*" ).delete_if { |item| item.include?( "\.svn" ) }
|
||||
end
|
||||
|
||||
s.add_dependency('activesupport', '= 1.3.1' + PKG_BUILD)
|
||||
s.add_dependency('activesupport', '= 1.4.0' + PKG_BUILD)
|
||||
|
||||
s.files.delete "test/fixtures/fixture_database.sqlite"
|
||||
s.files.delete "test/fixtures/fixture_database_2.sqlite"
|
||||
|
||||
@@ -163,9 +163,9 @@ module ActiveRecord
|
||||
child[left_col_name] = right_bound
|
||||
child[right_col_name] = right_bound + 1
|
||||
self[right_col_name] += 2
|
||||
self.class.transaction {
|
||||
self.class.update_all( "#{left_col_name} = (#{left_col_name} + 2)", "#{scope_condition} AND #{left_col_name} >= #{right_bound}" )
|
||||
self.class.update_all( "#{right_col_name} = (#{right_col_name} + 2)", "#{scope_condition} AND #{right_col_name} >= #{right_bound}" )
|
||||
self.class.base_class.transaction {
|
||||
self.class.base_class.update_all( "#{left_col_name} = (#{left_col_name} + 2)", "#{scope_condition} AND #{left_col_name} >= #{right_bound}" )
|
||||
self.class.base_class.update_all( "#{right_col_name} = (#{right_col_name} + 2)", "#{scope_condition} AND #{right_col_name} >= #{right_bound}" )
|
||||
self.save
|
||||
child.save
|
||||
}
|
||||
@@ -180,17 +180,17 @@ module ActiveRecord
|
||||
|
||||
# Returns a set of itself and all of its nested children
|
||||
def full_set
|
||||
self.class.find(:all, :conditions => "#{scope_condition} AND (#{left_col_name} BETWEEN #{self[left_col_name]} and #{self[right_col_name]})" )
|
||||
self.class.base_class.find(:all, :conditions => "#{scope_condition} AND (#{left_col_name} BETWEEN #{self[left_col_name]} and #{self[right_col_name]})" )
|
||||
end
|
||||
|
||||
# Returns a set of all of its children and nested children
|
||||
def all_children
|
||||
self.class.find(:all, :conditions => "#{scope_condition} AND (#{left_col_name} > #{self[left_col_name]}) and (#{right_col_name} < #{self[right_col_name]})" )
|
||||
self.class.base_class.find(:all, :conditions => "#{scope_condition} AND (#{left_col_name} > #{self[left_col_name]}) and (#{right_col_name} < #{self[right_col_name]})" )
|
||||
end
|
||||
|
||||
# Returns a set of only this entry's immediate children
|
||||
def direct_children
|
||||
self.class.find(:all, :conditions => "#{scope_condition} and #{parent_column} = #{self.id}")
|
||||
self.class.base_class.find(:all, :conditions => "#{scope_condition} and #{parent_column} = #{self.id}")
|
||||
end
|
||||
|
||||
# Prunes a branch off of the tree, shifting all of the elements on the right
|
||||
@@ -199,10 +199,10 @@ module ActiveRecord
|
||||
return if self[right_col_name].nil? || self[left_col_name].nil?
|
||||
dif = self[right_col_name] - self[left_col_name] + 1
|
||||
|
||||
self.class.transaction {
|
||||
self.class.delete_all( "#{scope_condition} and #{left_col_name} > #{self[left_col_name]} and #{right_col_name} < #{self[right_col_name]}" )
|
||||
self.class.update_all( "#{left_col_name} = (#{left_col_name} - #{dif})", "#{scope_condition} AND #{left_col_name} >= #{self[right_col_name]}" )
|
||||
self.class.update_all( "#{right_col_name} = (#{right_col_name} - #{dif} )", "#{scope_condition} AND #{right_col_name} >= #{self[right_col_name]}" )
|
||||
self.class.base_class.transaction {
|
||||
self.class.base_class.delete_all( "#{scope_condition} and #{left_col_name} > #{self[left_col_name]} and #{right_col_name} < #{self[right_col_name]}" )
|
||||
self.class.base_class.update_all( "#{left_col_name} = (#{left_col_name} - #{dif})", "#{scope_condition} AND #{left_col_name} >= #{self[right_col_name]}" )
|
||||
self.class.base_class.update_all( "#{right_col_name} = (#{right_col_name} - #{dif} )", "#{scope_condition} AND #{right_col_name} >= #{self[right_col_name]}" )
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -30,7 +30,7 @@ module ActiveRecord
|
||||
end
|
||||
end
|
||||
|
||||
class HasManyThroughSourceAssociationMacroError < ActiveRecordError #:nodoc
|
||||
class HasManyThroughSourceAssociationMacroError < ActiveRecordError #:nodoc:
|
||||
def initialize(reflection)
|
||||
through_reflection = reflection.through_reflection
|
||||
source_reflection = reflection.source_reflection
|
||||
@@ -745,7 +745,13 @@ module ActiveRecord
|
||||
|
||||
# Associates two classes via an intermediate join table. Unless the join table is explicitly specified as
|
||||
# an option, it is guessed using the lexical order of the class names. So a join between Developer and Project
|
||||
# will give the default join table name of "developers_projects" because "D" outranks "P".
|
||||
# will give the default join table name of "developers_projects" because "D" outranks "P". Note that this precedence
|
||||
# is calculated using the <tt><</tt> operator for <tt>String</tt>. This means that if the strings are of different lengths,
|
||||
# and the strings are equal when compared up to the shortest length, then the longer string is considered of higher
|
||||
# lexical precedence than the shorter one. For example, one would expect the tables <tt>paper_boxes</tt> and <tt>papers</tt>
|
||||
# to generate a join table name of <tt>papers_paper_boxes</tt> because of the length of the name <tt>paper_boxes</tt>,
|
||||
# but it in fact generates a join table name of <tt>paper_boxes_papers</tt>. Be aware of this caveat, and use the
|
||||
# custom <tt>join_table</tt> option if you need to.
|
||||
#
|
||||
# Deprecated: Any additional fields added to the join table will be placed as attributes when pulling records out through
|
||||
# has_and_belongs_to_many associations. Records returned from join tables with additional attributes will be marked as
|
||||
@@ -947,10 +953,6 @@ module ActiveRecord
|
||||
end
|
||||
end
|
||||
|
||||
def require_association_class(class_name)
|
||||
require_association(Inflector.underscore(class_name)) if class_name
|
||||
end
|
||||
|
||||
def add_multiple_associated_save_callbacks(association_name)
|
||||
method_name = "validate_associated_records_for_#{association_name}".to_sym
|
||||
define_method(method_name) do
|
||||
@@ -1060,7 +1062,7 @@ module ActiveRecord
|
||||
when :delete
|
||||
module_eval "before_destroy '#{reflection.class_name}.delete(#{reflection.name}.id) unless #{reflection.name}.nil?'"
|
||||
when :nullify
|
||||
module_eval "before_destroy '#{reflection.name}.update_attribute(\"#{reflection.primary_key_name}\", nil)'"
|
||||
module_eval "before_destroy '#{reflection.name}.update_attribute(\"#{reflection.primary_key_name}\", nil) unless #{reflection.name}.nil?'"
|
||||
when nil, false
|
||||
# pass
|
||||
else
|
||||
@@ -1169,9 +1171,10 @@ module ActiveRecord
|
||||
add_limited_ids_condition!(sql, options, join_dependency) if !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit])
|
||||
|
||||
sql << "GROUP BY #{options[:group]} " if options[:group]
|
||||
sql << "ORDER BY #{options[:order]} " if options[:order]
|
||||
|
||||
add_order!(sql, options[:order], scope)
|
||||
add_limit!(sql, options, scope) if using_limitable_reflections?(join_dependency.reflections)
|
||||
add_lock!(sql, options, scope)
|
||||
|
||||
return sanitize_sql(sql)
|
||||
end
|
||||
@@ -1190,27 +1193,31 @@ module ActiveRecord
|
||||
"#{name} Load IDs For Limited Eager Loading"
|
||||
).collect { |row| connection.quote(row[primary_key]) }.join(", ")
|
||||
end
|
||||
|
||||
|
||||
def construct_finder_sql_for_association_limiting(options, join_dependency)
|
||||
scope = scope(:find)
|
||||
is_distinct = include_eager_conditions?(options) || include_eager_order?(options)
|
||||
sql = "SELECT "
|
||||
if is_distinct
|
||||
ordered_columns = options[:order].to_s.split(',').collect! { |s| s.split.first }
|
||||
options[:order] = "#{table_name}.#{primary_key}, #{options[:order]}" if options[:order] && connection.requires_order_columns_in_distinct_clause?
|
||||
sql << connection.distinct("#{table_name}.#{primary_key}", ordered_columns)
|
||||
sql << connection.distinct("#{table_name}.#{primary_key}", options[:order])
|
||||
else
|
||||
sql << primary_key
|
||||
end
|
||||
sql << " FROM #{table_name} "
|
||||
|
||||
|
||||
if is_distinct
|
||||
sql << join_dependency.join_associations.collect(&:association_join).join
|
||||
add_joins!(sql, options, scope)
|
||||
end
|
||||
|
||||
|
||||
add_conditions!(sql, options[:conditions], scope)
|
||||
sql << "ORDER BY #{options[:order]} " if options[:order]
|
||||
if options[:order]
|
||||
if is_distinct
|
||||
connection.add_order_by_for_association_limiting!(sql, options)
|
||||
else
|
||||
sql << "ORDER BY #{options[:order]}"
|
||||
end
|
||||
end
|
||||
add_limit!(sql, options, scope)
|
||||
return sanitize_sql(sql)
|
||||
end
|
||||
@@ -1570,7 +1577,7 @@ module ActiveRecord
|
||||
end || ''
|
||||
join << %(AND %s.%s = %s ) % [
|
||||
aliased_table_name,
|
||||
reflection.active_record.connection.quote_column_name(reflection.active_record.inheritance_column),
|
||||
reflection.active_record.connection.quote_column_name(klass.inheritance_column),
|
||||
klass.quote_value(klass.name.demodulize)] unless klass.descends_from_active_record?
|
||||
|
||||
[through_reflection, reflection].each do |ref|
|
||||
|
||||
@@ -648,9 +648,10 @@ module ActiveRecord #:nodoc:
|
||||
key
|
||||
end
|
||||
|
||||
# Defines the column name for use with single table inheritance -- can be overridden in subclasses.
|
||||
# Defines the column name for use with single table inheritance
|
||||
# -- can be set in subclasses like so: self.inheritance_column = "type_id"
|
||||
def inheritance_column
|
||||
"type"
|
||||
@inheritance_column ||= "type".freeze
|
||||
end
|
||||
|
||||
# Lazy-set the sequence name to the connection's default. This method
|
||||
@@ -762,7 +763,7 @@ module ActiveRecord #:nodoc:
|
||||
@columns
|
||||
end
|
||||
|
||||
# Returns an array of column objects for the table associated with this class.
|
||||
# Returns a hash of column objects for the table associated with this class.
|
||||
def columns_hash
|
||||
@columns_hash ||= columns.inject({}) { |hash, column| hash[column.name] = column; hash }
|
||||
end
|
||||
@@ -800,7 +801,7 @@ module ActiveRecord #:nodoc:
|
||||
# Resets all the cached information about columns, which will cause them to be reloaded on the next request.
|
||||
def reset_column_information
|
||||
read_methods.each { |name| undef_method(name) }
|
||||
@column_names = @columns = @columns_hash = @content_columns = @dynamic_methods_hash = @read_methods = nil
|
||||
@column_names = @columns = @columns_hash = @content_columns = @dynamic_methods_hash = @read_methods = @inheritance_column = nil
|
||||
end
|
||||
|
||||
def reset_column_information_and_inheritable_attributes_for_all_subclasses#:nodoc:
|
||||
@@ -986,7 +987,7 @@ module ActiveRecord #:nodoc:
|
||||
options.update(:limit => 1) unless options[:include]
|
||||
find_every(options).first
|
||||
end
|
||||
|
||||
|
||||
def find_every(options)
|
||||
records = scoped?(:find, :include) || options[:include] ?
|
||||
find_with_associations(options) :
|
||||
@@ -996,11 +997,11 @@ module ActiveRecord #:nodoc:
|
||||
|
||||
records
|
||||
end
|
||||
|
||||
|
||||
def find_from_ids(ids, options)
|
||||
expects_array = ids.first.kind_of?(Array)
|
||||
expects_array = ids.first.kind_of?(Array)
|
||||
return ids.first if expects_array && ids.first.empty?
|
||||
|
||||
|
||||
ids = ids.flatten.compact.uniq
|
||||
|
||||
case ids.size
|
||||
@@ -1053,11 +1054,9 @@ module ActiveRecord #:nodoc:
|
||||
allocate
|
||||
|
||||
else
|
||||
require_association_class(subclass_name)
|
||||
|
||||
# Ignore type if no column is present since it was probably
|
||||
# pulled in from a sloppy join.
|
||||
unless self.columns_hash.include?(inheritance_column)
|
||||
unless columns_hash.include?(inheritance_column)
|
||||
allocate
|
||||
|
||||
else
|
||||
@@ -1096,7 +1095,7 @@ module ActiveRecord #:nodoc:
|
||||
|
||||
sql << " GROUP BY #{options[:group]} " if options[:group]
|
||||
|
||||
add_order!(sql, options[:order])
|
||||
add_order!(sql, options[:order], scope)
|
||||
add_limit!(sql, options, scope)
|
||||
add_lock!(sql, options, scope)
|
||||
|
||||
@@ -1120,12 +1119,14 @@ module ActiveRecord #:nodoc:
|
||||
end
|
||||
end
|
||||
|
||||
def add_order!(sql, order)
|
||||
def add_order!(sql, order, scope = :auto)
|
||||
scope = scope(:find) if :auto == scope
|
||||
scoped_order = scope[:order] if scope
|
||||
if order
|
||||
sql << " ORDER BY #{order}"
|
||||
sql << ", #{scope(:find, :order)}" if scoped?(:find, :order)
|
||||
sql << ", #{scoped_order}" if scoped_order
|
||||
else
|
||||
sql << " ORDER BY #{scope(:find, :order)}" if scoped?(:find, :order)
|
||||
sql << " ORDER BY #{scoped_order}" if scoped_order
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1139,7 +1140,7 @@ module ActiveRecord #:nodoc:
|
||||
# The optional scope argument is for the current :find scope.
|
||||
# The :lock option has precedence over a scoped :lock.
|
||||
def add_lock!(sql, options, scope = :auto)
|
||||
scope = scope(:find) if :auto == :scope
|
||||
scope = scope(:find) if :auto == scope
|
||||
options = options.reverse_merge(:lock => scope[:lock]) if scope
|
||||
connection.add_lock!(sql, options)
|
||||
end
|
||||
@@ -1158,7 +1159,7 @@ module ActiveRecord #:nodoc:
|
||||
segments = []
|
||||
segments << sanitize_sql(scope[:conditions]) if scope && scope[:conditions]
|
||||
segments << sanitize_sql(conditions) unless conditions.nil?
|
||||
segments << type_condition unless descends_from_active_record?
|
||||
segments << type_condition unless descends_from_active_record?
|
||||
segments.compact!
|
||||
sql << "WHERE (#{segments.join(") AND (")}) " unless segments.empty?
|
||||
end
|
||||
@@ -1186,22 +1187,22 @@ module ActiveRecord #:nodoc:
|
||||
# It's even possible to use all the additional parameters to find. For example, the full interface for find_all_by_amount
|
||||
# is actually find_all_by_amount(amount, options).
|
||||
def method_missing(method_id, *arguments)
|
||||
if match = /find_(all_by|by)_([_a-zA-Z]\w*)/.match(method_id.to_s)
|
||||
if match = /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(method_id.to_s)
|
||||
finder, deprecated_finder = determine_finder(match), determine_deprecated_finder(match)
|
||||
|
||||
attribute_names = extract_attribute_names_from_match(match)
|
||||
super unless all_attributes_exists?(attribute_names)
|
||||
|
||||
conditions = construct_conditions_from_arguments(attribute_names, arguments)
|
||||
attributes = construct_attributes_from_arguments(attribute_names, arguments)
|
||||
|
||||
case extra_options = arguments[attribute_names.size]
|
||||
when nil
|
||||
options = { :conditions => conditions }
|
||||
options = { :conditions => attributes }
|
||||
set_readonly_option!(options)
|
||||
ActiveSupport::Deprecation.silence { send(finder, options) }
|
||||
|
||||
when Hash
|
||||
finder_options = extra_options.merge(:conditions => conditions)
|
||||
finder_options = extra_options.merge(:conditions => attributes)
|
||||
validate_find_options(finder_options)
|
||||
set_readonly_option!(finder_options)
|
||||
|
||||
@@ -1215,17 +1216,19 @@ module ActiveRecord #:nodoc:
|
||||
|
||||
else
|
||||
ActiveSupport::Deprecation.silence do
|
||||
send(deprecated_finder, conditions, *arguments[attribute_names.length..-1])
|
||||
send(deprecated_finder, sanitize_sql(attributes), *arguments[attribute_names.length..-1])
|
||||
end
|
||||
end
|
||||
elsif match = /find_or_(initialize|create)_by_([_a-zA-Z]\w*)/.match(method_id.to_s)
|
||||
elsif match = /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/.match(method_id.to_s)
|
||||
instantiator = determine_instantiator(match)
|
||||
attribute_names = extract_attribute_names_from_match(match)
|
||||
super unless all_attributes_exists?(attribute_names)
|
||||
|
||||
options = { :conditions => construct_conditions_from_arguments(attribute_names, arguments) }
|
||||
attributes = construct_attributes_from_arguments(attribute_names, arguments)
|
||||
options = { :conditions => attributes }
|
||||
set_readonly_option!(options)
|
||||
find_initial(options) || send(instantiator, construct_attributes_from_arguments(attribute_names, arguments))
|
||||
|
||||
find_initial(options) || send(instantiator, attributes)
|
||||
else
|
||||
super
|
||||
end
|
||||
@@ -1247,12 +1250,6 @@ module ActiveRecord #:nodoc:
|
||||
match.captures.last.split('_and_')
|
||||
end
|
||||
|
||||
def construct_conditions_from_arguments(attribute_names, arguments)
|
||||
conditions = []
|
||||
attribute_names.each_with_index { |name, idx| conditions << "#{table_name}.#{connection.quote_column_name(name)} #{attribute_condition(arguments[idx])} " }
|
||||
[ conditions.join(" AND "), *arguments[0...attribute_names.length] ]
|
||||
end
|
||||
|
||||
def construct_attributes_from_arguments(attribute_names, arguments)
|
||||
attributes = {}
|
||||
attribute_names.each_with_index { |name, idx| attributes[name] = arguments[idx] }
|
||||
@@ -1275,7 +1272,7 @@ module ActiveRecord #:nodoc:
|
||||
def expand_id_conditions(id_or_conditions)
|
||||
case id_or_conditions
|
||||
when Array, Hash then id_or_conditions
|
||||
else construct_conditions_from_arguments([primary_key], [id_or_conditions])
|
||||
else sanitize_sql(primary_key => id_or_conditions)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1355,9 +1352,9 @@ module ActiveRecord #:nodoc:
|
||||
def compute_type(type_name)
|
||||
modularized_name = type_name_with_module(type_name)
|
||||
begin
|
||||
instance_eval(modularized_name)
|
||||
rescue NameError => e
|
||||
instance_eval(type_name)
|
||||
class_eval(modularized_name, __FILE__, __LINE__)
|
||||
rescue NameError
|
||||
class_eval(type_name, __FILE__, __LINE__)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1377,26 +1374,32 @@ module ActiveRecord #:nodoc:
|
||||
klass.base_class.name
|
||||
end
|
||||
|
||||
#Accepts an array, hash, or string of sql conditions and
|
||||
#deals with them accordingly
|
||||
# Accepts an array, hash, or string of sql conditions and sanitizes
|
||||
# them into a valid SQL fragment.
|
||||
# ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
|
||||
# { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id='4'"
|
||||
# "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'"
|
||||
def sanitize_sql(condition)
|
||||
return sanitize_sql_array(condition) if condition.is_a?(Array)
|
||||
return sanitize_sql_hash(condition) if condition.is_a?(Hash)
|
||||
condition
|
||||
case condition
|
||||
when Array; sanitize_sql_array(condition)
|
||||
when Hash; sanitize_sql_hash(condition)
|
||||
else condition
|
||||
end
|
||||
end
|
||||
|
||||
# Accepts a hash of conditions. The hash has each key/value or attribute/value pair
|
||||
# sanitized and interpolated into the sql statement.
|
||||
# { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id= 4"
|
||||
def sanitize_sql_hash(hash)
|
||||
hash.collect { |attrib, value|
|
||||
"#{table_name}.#{connection.quote_column_name(attrib)} = #{quote_value(value)}"
|
||||
}.join(" AND ")
|
||||
|
||||
# Sanitizes a hash of attribute/value pairs into SQL conditions.
|
||||
# { :name => "foo'bar", :group_id => 4 }
|
||||
# # => "name='foo''bar' and group_id= 4"
|
||||
# { :status => nil, :group_id => [1,2,3] }
|
||||
# # => "status IS NULL and group_id IN (1,2,3)"
|
||||
def sanitize_sql_hash(attrs)
|
||||
conditions = attrs.map do |attr, value|
|
||||
"#{table_name}.#{connection.quote_column_name(attr)} #{attribute_condition(value)}"
|
||||
end.join(' AND ')
|
||||
|
||||
replace_bind_variables(conditions, attrs.values)
|
||||
end
|
||||
|
||||
|
||||
# Accepts an array of conditions. The array has each value
|
||||
# sanitized and interpolated into the sql statement.
|
||||
# ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
|
||||
@@ -1874,9 +1877,16 @@ module ActiveRecord #:nodoc:
|
||||
# ActiveRecord::Base.generate_read_methods is set to true.
|
||||
def define_read_methods
|
||||
self.class.columns_hash.each do |name, column|
|
||||
unless self.class.serialized_attributes[name]
|
||||
define_read_method(name.to_sym, name, column) unless respond_to_without_attributes?(name)
|
||||
define_question_method(name) unless respond_to_without_attributes?("#{name}?")
|
||||
unless respond_to_without_attributes?(name)
|
||||
if self.class.serialized_attributes[name]
|
||||
define_read_method_for_serialized_attribute(name)
|
||||
else
|
||||
define_read_method(name.to_sym, name, column)
|
||||
end
|
||||
end
|
||||
|
||||
unless respond_to_without_attributes?("#{name}?")
|
||||
define_question_method(name)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1894,6 +1904,15 @@ module ActiveRecord #:nodoc:
|
||||
evaluate_read_method attr_name, "def #{symbol}; #{access_code}; end"
|
||||
end
|
||||
|
||||
# Define read method for serialized attribute.
|
||||
def define_read_method_for_serialized_attribute(attr_name)
|
||||
unless attr_name.to_s == self.class.primary_key.to_s
|
||||
self.class.read_methods << attr_name
|
||||
end
|
||||
|
||||
evaluate_read_method attr_name, "def #{attr_name}; unserialize_attribute('#{attr_name}'); end"
|
||||
end
|
||||
|
||||
# Define an attribute ? method.
|
||||
def define_question_method(attr_name)
|
||||
unless attr_name.to_s == self.class.primary_key.to_s
|
||||
|
||||
@@ -157,6 +157,9 @@ module ActiveRecord
|
||||
end
|
||||
|
||||
def construct_calculation_sql(operation, column_name, options) #:nodoc:
|
||||
operation = operation.to_s.downcase
|
||||
options = options.symbolize_keys
|
||||
|
||||
scope = scope(:find)
|
||||
merged_includes = merge_includes(scope ? scope[:include] : [], options[:include])
|
||||
aggregate_alias = column_alias_for(operation, column_name)
|
||||
|
||||
@@ -86,6 +86,16 @@ module ActiveRecord
|
||||
conn.disconnect!
|
||||
end
|
||||
end
|
||||
|
||||
# Clears the cache which maps classes
|
||||
def clear_reloadable_connections!
|
||||
@@active_connections.each do |name, conn|
|
||||
if conn.requires_reloading?
|
||||
conn.disconnect!
|
||||
@@active_connections.delete(name)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Verify active connections.
|
||||
def verify_active_connections! #:nodoc:
|
||||
|
||||
@@ -4,11 +4,14 @@ module ActiveRecord
|
||||
# Returns an array of record hashes with the column names as keys and
|
||||
# column values as values.
|
||||
def select_all(sql, name = nil)
|
||||
select(sql, name)
|
||||
end
|
||||
|
||||
# Returns a record hash with the column names as keys and column values
|
||||
# as values.
|
||||
def select_one(sql, name = nil)
|
||||
result = select(sql, name)
|
||||
result.first if result
|
||||
end
|
||||
|
||||
# Returns a single value from a record
|
||||
@@ -25,19 +28,24 @@ module ActiveRecord
|
||||
end
|
||||
|
||||
# Executes the SQL statement in the context of this connection.
|
||||
# This abstract method raises a NotImplementedError.
|
||||
def execute(sql, name = nil)
|
||||
raise NotImplementedError, "execute is an abstract method"
|
||||
end
|
||||
|
||||
# Returns the last auto-generated ID from the affected table.
|
||||
def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) end
|
||||
def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
|
||||
raise NotImplementedError, "insert is an abstract method"
|
||||
end
|
||||
|
||||
# Executes the update statement and returns the number of rows affected.
|
||||
def update(sql, name = nil) end
|
||||
def update(sql, name = nil)
|
||||
execute(sql, name)
|
||||
end
|
||||
|
||||
# Executes the delete statement and returns the number of rows affected.
|
||||
def delete(sql, name = nil) end
|
||||
def delete(sql, name = nil)
|
||||
update(sql, name)
|
||||
end
|
||||
|
||||
# Wrap a block in a transaction. Returns result of block.
|
||||
def transaction(start_db_transaction = true)
|
||||
@@ -110,6 +118,13 @@ module ActiveRecord
|
||||
def reset_sequence!(table, column, sequence = nil)
|
||||
# Do nothing by default. Implement for PostgreSQL, Oracle, ...
|
||||
end
|
||||
|
||||
protected
|
||||
# Returns an array of record hashes with the column names as keys and
|
||||
# column values as values.
|
||||
def select(sql, name = nil)
|
||||
raise NotImplementedError, "select is an abstract method"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -8,7 +8,8 @@ module ActiveRecord
|
||||
return value.quoted_id if value.respond_to?(:quoted_id)
|
||||
|
||||
case value
|
||||
when String
|
||||
when String, ActiveSupport::Multibyte::Chars
|
||||
value = value.to_s
|
||||
if column && column.type == :binary && column.class.respond_to?(:string_to_binary)
|
||||
"'#{quote_string(column.class.string_to_binary(value))}'" # ' (for ruby-mode)
|
||||
elsif column && [:integer, :float].include?(column.type)
|
||||
|
||||
@@ -203,17 +203,19 @@ module ActiveRecord
|
||||
end
|
||||
|
||||
class ColumnDefinition < Struct.new(:base, :name, :type, :limit, :precision, :scale, :default, :null) #:nodoc:
|
||||
|
||||
def sql_type
|
||||
base.type_to_sql(type.to_sym, limit, precision, scale) rescue type
|
||||
end
|
||||
|
||||
def to_sql
|
||||
column_sql = "#{base.quote_column_name(name)} #{type_to_sql(type.to_sym, limit, precision, scale)}"
|
||||
add_column_options!(column_sql, :null => null, :default => default)
|
||||
column_sql = "#{base.quote_column_name(name)} #{sql_type}"
|
||||
add_column_options!(column_sql, :null => null, :default => default) unless type.to_sym == :primary_key
|
||||
column_sql
|
||||
end
|
||||
alias to_s :to_sql
|
||||
|
||||
private
|
||||
def type_to_sql(name, limit, precision, scale)
|
||||
base.type_to_sql(name, limit, precision, scale) rescue name
|
||||
end
|
||||
|
||||
def add_column_options!(sql, options)
|
||||
base.add_column_options!(sql, options.merge(:column => self))
|
||||
@@ -233,7 +235,7 @@ module ActiveRecord
|
||||
# Appends a primary key definition to the table definition.
|
||||
# Can be called multiple times, but this is probably not a good idea.
|
||||
def primary_key(name)
|
||||
column(name, native[:primary_key])
|
||||
column(name, :primary_key)
|
||||
end
|
||||
|
||||
# Returns a ColumnDefinition for the column with name +name+.
|
||||
@@ -253,9 +255,7 @@ module ActiveRecord
|
||||
# Requests a maximum column length (<tt>:string</tt>, <tt>:text</tt>,
|
||||
# <tt>:binary</tt> or <tt>:integer</tt> columns only)
|
||||
# * <tt>:default</tt>:
|
||||
# The column's default value. You cannot explicitely set the default
|
||||
# value to +NULL+. Simply leave off this option if you want a +NULL+
|
||||
# default value.
|
||||
# The column's default value. Use nil for NULL.
|
||||
# * <tt>:null</tt>:
|
||||
# Allows or disallows +NULL+ values in the column. This option could
|
||||
# have been named <tt>:null_allowed</tt>.
|
||||
@@ -271,11 +271,11 @@ module ActiveRecord
|
||||
# <tt>:precision</tt>.
|
||||
# * MySQL: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..30].
|
||||
# Default is (10,0).
|
||||
# * PostGres?: <tt>:precision</tt> [1..infinity],
|
||||
# * PostgreSQL: <tt>:precision</tt> [1..infinity],
|
||||
# <tt>:scale</tt> [0..infinity]. No default.
|
||||
# * Sqlite2: Any <tt>:precision</tt> and <tt>:scale</tt> may be used.
|
||||
# * SQLite2: Any <tt>:precision</tt> and <tt>:scale</tt> may be used.
|
||||
# Internal storage as strings. No default.
|
||||
# * Sqlite3: No restrictions on <tt>:precision</tt> and <tt>:scale</tt>,
|
||||
# * SQLite3: No restrictions on <tt>:precision</tt> and <tt>:scale</tt>,
|
||||
# but the maximum supported <tt>:precision</tt> is 16. No default.
|
||||
# * Oracle: <tt>:precision</tt> [1..38], <tt>:scale</tt> [-84..127].
|
||||
# Default is (38,0).
|
||||
|
||||
@@ -94,7 +94,7 @@ module ActiveRecord
|
||||
yield table_definition
|
||||
|
||||
if options[:force]
|
||||
drop_table(name) rescue nil
|
||||
drop_table(name, options) rescue nil
|
||||
end
|
||||
|
||||
create_sql = "CREATE#{' TEMPORARY' if options[:temporary]} TABLE "
|
||||
@@ -112,7 +112,7 @@ module ActiveRecord
|
||||
end
|
||||
|
||||
# Drops a table from the database.
|
||||
def drop_table(name)
|
||||
def drop_table(name, options = {})
|
||||
execute "DROP TABLE #{name}"
|
||||
end
|
||||
|
||||
@@ -254,7 +254,7 @@ module ActiveRecord
|
||||
|
||||
def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
|
||||
native = native_database_types[type]
|
||||
column_type_sql = native[:name]
|
||||
column_type_sql = native.is_a?(Hash) ? native[:name] : native
|
||||
if type == :decimal # ignore limit, use precison and scale
|
||||
precision ||= native[:precision]
|
||||
scale ||= native[:scale]
|
||||
@@ -265,7 +265,7 @@ module ActiveRecord
|
||||
column_type_sql << "(#{precision})"
|
||||
end
|
||||
else
|
||||
raise ArgumentError, "Error adding decimal column: precision cannot be empty if scale if specifed" if scale
|
||||
raise ArgumentError, "Error adding decimal column: precision cannot be empty if scale if specified" if scale
|
||||
end
|
||||
column_type_sql
|
||||
else
|
||||
@@ -273,17 +273,31 @@ module ActiveRecord
|
||||
column_type_sql << "(#{limit})" if limit
|
||||
column_type_sql
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
def add_column_options!(sql, options) #:nodoc:
|
||||
sql << " DEFAULT #{quote(options[:default], options[:column])}" unless options[:default].nil?
|
||||
sql << " DEFAULT #{quote(options[:default], options[:column])}" if options_include_default?(options)
|
||||
sql << " NOT NULL" if options[:null] == false
|
||||
end
|
||||
|
||||
# SELECT DISTINCT clause for a given set of columns. PostgreSQL overrides this for custom DISTINCT syntax.
|
||||
def distinct(columns, *order_columns)
|
||||
# SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
|
||||
# Both PostgreSQL and Oracle overrides this for custom DISTINCT syntax.
|
||||
#
|
||||
# distinct("posts.id", "posts.created_at desc")
|
||||
def distinct(columns, order_by)
|
||||
"DISTINCT #{columns}"
|
||||
end
|
||||
|
||||
# ORDER BY clause for the passed order option.
|
||||
# PostgreSQL overrides this due to its stricter standards compliance.
|
||||
def add_order_by_for_association_limiting!(sql, options)
|
||||
sql << "ORDER BY #{options[:order]}"
|
||||
end
|
||||
|
||||
protected
|
||||
def options_include_default?(options)
|
||||
options.include?(:default) && !(options[:null] == false && options[:default].nil?)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -56,12 +56,6 @@ module ActiveRecord
|
||||
false
|
||||
end
|
||||
|
||||
# Does this adapter require the order columns to be in the select clause
|
||||
# of a DISTINCT query? This is +false+ in all adapters except postgresql.
|
||||
def requires_order_columns_in_distinct_clause?
|
||||
false
|
||||
end
|
||||
|
||||
def reset_runtime #:nodoc:
|
||||
rt, @runtime = @runtime, 0
|
||||
rt
|
||||
@@ -85,6 +79,12 @@ module ActiveRecord
|
||||
@active = false
|
||||
end
|
||||
|
||||
# Returns true if its safe to reload the connection between requests for development mode.
|
||||
# This is not the case for Ruby/MySQL and it's not necessary for any adapters except SQLite.
|
||||
def requires_reloading?
|
||||
false
|
||||
end
|
||||
|
||||
# Lazily verify this connection, calling +active?+ only if it hasn't
|
||||
# been called for +timeout+ seconds.
|
||||
def verify!(timeout)
|
||||
|
||||
@@ -47,14 +47,6 @@ begin
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def select_all(sql, name = nil)
|
||||
select(sql, name)
|
||||
end
|
||||
|
||||
def select_one(sql, name = nil)
|
||||
select(sql, name).first
|
||||
end
|
||||
|
||||
def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
|
||||
execute(sql, name = nil)
|
||||
@@ -72,9 +64,6 @@ begin
|
||||
rows_affected
|
||||
end
|
||||
|
||||
alias_method :update, :execute
|
||||
alias_method :delete, :execute
|
||||
|
||||
def begin_db_transaction
|
||||
@connection.set_auto_commit_off
|
||||
end
|
||||
|
||||
@@ -50,7 +50,7 @@ module ActiveRecord
|
||||
|
||||
@default = parse_default(default_source) if default_source
|
||||
@limit = decide_limit(length)
|
||||
@domain, @sub_type, @precision, @scale = domain, sub_type, precision, scale
|
||||
@domain, @sub_type, @precision, @scale = domain, sub_type, precision, scale.abs
|
||||
end
|
||||
|
||||
def type
|
||||
@@ -293,6 +293,8 @@ module ActiveRecord
|
||||
:string => { :name => "varchar", :limit => 255 },
|
||||
:text => { :name => "blob sub_type text" },
|
||||
:integer => { :name => "bigint" },
|
||||
:decimal => { :name => "decimal" },
|
||||
:numeric => { :name => "numeric" },
|
||||
:float => { :name => "float" },
|
||||
:datetime => { :name => "timestamp" },
|
||||
:timestamp => { :name => "timestamp" },
|
||||
@@ -503,8 +505,8 @@ module ActiveRecord
|
||||
|
||||
def change_column(table_name, column_name, type, options = {}) # :nodoc:
|
||||
change_column_type(table_name, column_name, type, options)
|
||||
change_column_position(table_name, column_name, options[:position]) if options[:position]
|
||||
change_column_default(table_name, column_name, options[:default]) if options.has_key?(:default)
|
||||
change_column_position(table_name, column_name, options[:position]) if options.include?(:position)
|
||||
change_column_default(table_name, column_name, options[:default]) if options_include_default?(options)
|
||||
end
|
||||
|
||||
def change_column_default(table_name, column_name, default) # :nodoc:
|
||||
@@ -534,12 +536,7 @@ module ActiveRecord
|
||||
end
|
||||
|
||||
def remove_index(table_name, options) #:nodoc:
|
||||
if Hash === options
|
||||
index_name = options[:name]
|
||||
else
|
||||
index_name = "#{table_name}_#{options}_index"
|
||||
end
|
||||
execute "DROP INDEX #{index_name}"
|
||||
execute "DROP INDEX #{quote_column_name(index_name(table_name, options))}"
|
||||
end
|
||||
|
||||
def rename_table(name, new_name) # :nodoc:
|
||||
@@ -568,12 +565,12 @@ module ActiveRecord
|
||||
super << ";\n"
|
||||
end
|
||||
|
||||
def type_to_sql(type, limit = nil) # :nodoc:
|
||||
def type_to_sql(type, limit = nil, precision = nil, scale = nil) # :nodoc:
|
||||
case type
|
||||
when :integer then integer_sql_type(limit)
|
||||
when :float then float_sql_type(limit)
|
||||
when :string then super
|
||||
else super(type)
|
||||
when :string then super(type, limit, precision, scale)
|
||||
else super(type, limit, precision, scale)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ module ActiveRecord
|
||||
# Assigns a world-wide unique ID made up of:
|
||||
# < Sequence [2], ProcessID [2] , Time [4], IP Addr [4] >
|
||||
|
||||
class TwelveByteKey < String #:nodoc
|
||||
class TwelveByteKey < String #:nodoc:
|
||||
@@mutex = Mutex.new
|
||||
@@sequence_number = rand(65536)
|
||||
@@key_cached_pid_component = nil
|
||||
@@ -271,8 +271,7 @@ module ActiveRecord
|
||||
true
|
||||
end
|
||||
|
||||
def native_database_types #:nodoc
|
||||
{
|
||||
def native_database_types #:nodoc: {
|
||||
:primary_key => "INTEGER DEFAULT UNIQUE PRIMARY KEY",
|
||||
:string => { :name => "VARCHAR", :limit => 255 },
|
||||
:text => { :name => "CLOB" },
|
||||
@@ -564,8 +563,7 @@ module ActiveRecord
|
||||
execute "SET COMMIT TRUE"
|
||||
end
|
||||
|
||||
def add_limit_offset!(sql, options) #:nodoc
|
||||
if limit = options[:limit]
|
||||
def add_limit_offset!(sql, options) #:nodoc: if limit = options[:limit]
|
||||
offset = options[:offset] || 0
|
||||
|
||||
# Here is the full syntax FrontBase supports:
|
||||
@@ -778,7 +776,7 @@ module ActiveRecord
|
||||
end
|
||||
|
||||
# Drops a table from the database.
|
||||
def drop_table(name)
|
||||
def drop_table(name, options = {})
|
||||
execute "DROP TABLE #{name} RESTRICT"
|
||||
rescue ActiveRecord::StatementInvalid => e
|
||||
raise e unless e.message.match(/Referenced TABLE - \w* - does not exist/)
|
||||
@@ -795,12 +793,12 @@ module ActiveRecord
|
||||
|
||||
def add_column_options!(sql, options) #:nodoc:
|
||||
default_value = quote(options[:default], options[:column])
|
||||
if options[:default]
|
||||
if options_include_default?(options)
|
||||
if options[:type] == :boolean
|
||||
default_value = options[:default] == 0 ? quoted_false : quoted_true
|
||||
end
|
||||
sql << " DEFAULT #{default_value}"
|
||||
end
|
||||
sql << " DEFAULT #{default_value}" unless options[:default].nil?
|
||||
sql << " NOT NULL" if options[:null] == false
|
||||
end
|
||||
|
||||
@@ -828,17 +826,15 @@ module ActiveRecord
|
||||
execute(change_column_sql)
|
||||
change_column_sql = %( ALTER TABLE "#{table_name}" ALTER COLUMN "#{column_name}" )
|
||||
|
||||
default_value = quote(options[:default], options[:column])
|
||||
if options[:default]
|
||||
if options_include_default?(options)
|
||||
default_value = quote(options[:default], options[:column])
|
||||
if type == :boolean
|
||||
default_value = options[:default] == 0 ? quoted_false : quoted_true
|
||||
end
|
||||
change_column_sql << " SET DEFAULT #{default_value}"
|
||||
end
|
||||
|
||||
if default_value != "NULL"
|
||||
change_column_sql << " SET DEFAULT #{default_value}"
|
||||
execute(change_column_sql)
|
||||
end
|
||||
execute(change_column_sql)
|
||||
|
||||
# change_column_sql = "ALTER TABLE #{table_name} CHANGE #{column_name} #{column_name} #{type_to_sql(type, options[:limit])}"
|
||||
# add_column_options!(change_column_sql, options)
|
||||
|
||||
@@ -1,34 +1,29 @@
|
||||
require 'active_record/connection_adapters/abstract_adapter'
|
||||
require 'set'
|
||||
|
||||
module MysqlCompat
|
||||
module MysqlCompat #:nodoc:
|
||||
# add all_hashes method to standard mysql-c bindings or pure ruby version
|
||||
def self.define_all_hashes_method!
|
||||
raise 'Mysql not loaded' unless defined?(::Mysql)
|
||||
|
||||
# for compatibility
|
||||
Object.const_set(:MysqlRes, Mysql::Result) unless defined?(::MysqlRes)
|
||||
Object.const_set(:MysqlField, Mysql::Field) unless defined?(::MysqlField)
|
||||
Object.const_set(:MysqlError, Mysql::Error) unless defined?(::MysqlError)
|
||||
|
||||
return if ::MysqlRes.instance_methods.include?('all_hashes')
|
||||
target = defined?(Mysql::Result) ? Mysql::Result : MysqlRes
|
||||
return if target.instance_methods.include?('all_hashes')
|
||||
|
||||
# Ruby driver has a version string and returns null values in each_hash
|
||||
# C driver >= 2.7 returns null values in each_hash
|
||||
if Mysql.const_defined?(:VERSION)
|
||||
if Mysql::VERSION.is_a?(String) || Mysql::VERSION >= 20700
|
||||
::MysqlRes.class_eval <<-'end_eval'
|
||||
def all_hashes
|
||||
rows = []
|
||||
each_hash { |row| rows << row }
|
||||
rows
|
||||
end
|
||||
end_eval
|
||||
if Mysql.const_defined?(:VERSION) && (Mysql::VERSION.is_a?(String) || Mysql::VERSION >= 20700)
|
||||
target.class_eval <<-'end_eval'
|
||||
def all_hashes
|
||||
rows = []
|
||||
each_hash { |row| rows << row }
|
||||
rows
|
||||
end
|
||||
end_eval
|
||||
|
||||
# adapters before 2.7 don't have a version constant
|
||||
# and don't return null values in each_hash
|
||||
else
|
||||
::MysqlRes.class_eval <<-'end_eval'
|
||||
target.class_eval <<-'end_eval'
|
||||
def all_hashes
|
||||
rows = []
|
||||
all_fields = fetch_fields.inject({}) { |fields, f| fields[f.name] = nil; fields }
|
||||
@@ -37,19 +32,22 @@ module MysqlCompat
|
||||
end
|
||||
end_eval
|
||||
end
|
||||
|
||||
unless target.instance_methods.include?('all_hashes')
|
||||
raise "Failed to defined #{target.name}#all_hashes method. Mysql::VERSION = #{Mysql::VERSION.inspect}"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
module ActiveRecord
|
||||
class Base
|
||||
# Establishes a connection to the database that's used by all Active Record objects.
|
||||
def self.mysql_connection(config) # :nodoc:
|
||||
# Only include the MySQL driver if one hasn't already been loaded
|
||||
def self.require_mysql
|
||||
# Include the MySQL driver if one hasn't already been loaded
|
||||
unless defined? Mysql
|
||||
begin
|
||||
require_library_or_gem 'mysql'
|
||||
rescue LoadError => cannot_require_mysql
|
||||
# Only use the supplied backup Ruby/MySQL driver if no driver is already in place
|
||||
# Use the bundled Ruby/MySQL driver if no driver is already in place
|
||||
begin
|
||||
require 'active_record/vendor/mysql'
|
||||
rescue LoadError
|
||||
@@ -60,7 +58,10 @@ module ActiveRecord
|
||||
|
||||
# Define Mysql::Result.all_hashes
|
||||
MysqlCompat.define_all_hashes_method!
|
||||
end
|
||||
|
||||
# Establishes a connection to the database that's used by all Active Record objects.
|
||||
def self.mysql_connection(config) # :nodoc:
|
||||
config = config.symbolize_keys
|
||||
host = config[:host]
|
||||
port = config[:port]
|
||||
@@ -74,20 +75,41 @@ module ActiveRecord
|
||||
raise ArgumentError, "No database specified. Missing argument: database."
|
||||
end
|
||||
|
||||
require_mysql
|
||||
mysql = Mysql.init
|
||||
mysql.ssl_set(config[:sslkey], config[:sslcert], config[:sslca], config[:sslcapath], config[:sslcipher]) if config[:sslkey]
|
||||
|
||||
ConnectionAdapters::MysqlAdapter.new(mysql, logger, [host, username, password, database, port, socket], config)
|
||||
end
|
||||
end
|
||||
|
||||
module ConnectionAdapters
|
||||
class MysqlColumn < Column #:nodoc:
|
||||
TYPES_ALLOWING_EMPTY_STRING_DEFAULT = Set.new([:binary, :string, :text])
|
||||
|
||||
def initialize(name, default, sql_type = nil, null = true)
|
||||
@original_default = default
|
||||
super
|
||||
@default = nil if missing_default_forged_as_empty_string?
|
||||
end
|
||||
|
||||
private
|
||||
def simplified_type(field_type)
|
||||
return :boolean if MysqlAdapter.emulate_booleans && field_type.downcase.index("tinyint(1)")
|
||||
return :string if field_type =~ /enum/i
|
||||
super
|
||||
end
|
||||
|
||||
# MySQL misreports NOT NULL column default when none is given.
|
||||
# We can't detect this for columns which may have a legitimate ''
|
||||
# default (string, text, binary) but we can for others (integer,
|
||||
# datetime, boolean, and the rest).
|
||||
#
|
||||
# Test whether the column has default '', is not null, and is not
|
||||
# a type allowing default ''.
|
||||
def missing_default_forged_as_empty_string?
|
||||
!null && @original_default == '' && !TYPES_ALLOWING_EMPTY_STRING_DEFAULT.include?(type)
|
||||
end
|
||||
end
|
||||
|
||||
# The MySQL adapter will work with both Ruby/MySQL, which is a Ruby-based MySQL adapter that comes bundled with Active Record, and with
|
||||
@@ -138,8 +160,7 @@ module ActiveRecord
|
||||
true
|
||||
end
|
||||
|
||||
def native_database_types #:nodoc
|
||||
{
|
||||
def native_database_types #:nodoc: {
|
||||
:primary_key => "int(11) DEFAULT NULL auto_increment PRIMARY KEY",
|
||||
:string => { :name => "varchar", :limit => 255 },
|
||||
:text => { :name => "text" },
|
||||
@@ -217,16 +238,7 @@ module ActiveRecord
|
||||
|
||||
# DATABASE STATEMENTS ======================================
|
||||
|
||||
def select_all(sql, name = nil) #:nodoc:
|
||||
select(sql, name)
|
||||
end
|
||||
|
||||
def select_one(sql, name = nil) #:nodoc:
|
||||
result = select(sql, name)
|
||||
result.nil? ? nil : result.first
|
||||
end
|
||||
|
||||
def execute(sql, name = nil, retries = 2) #:nodoc:
|
||||
def execute(sql, name = nil) #:nodoc:
|
||||
log(sql, name) { @connection.query(sql) }
|
||||
rescue ActiveRecord::StatementInvalid => exception
|
||||
if exception.message.split(":").first =~ /Packets out of order/
|
||||
@@ -246,9 +258,6 @@ module ActiveRecord
|
||||
@connection.affected_rows
|
||||
end
|
||||
|
||||
alias_method :delete, :update #:nodoc:
|
||||
|
||||
|
||||
def begin_db_transaction #:nodoc:
|
||||
execute "BEGIN"
|
||||
rescue Exception
|
||||
@@ -268,8 +277,7 @@ module ActiveRecord
|
||||
end
|
||||
|
||||
|
||||
def add_limit_offset!(sql, options) #:nodoc
|
||||
if limit = options[:limit]
|
||||
def add_limit_offset!(sql, options) #:nodoc: if limit = options[:limit]
|
||||
unless offset = options[:offset]
|
||||
sql << " LIMIT #{limit}"
|
||||
else
|
||||
@@ -350,14 +358,14 @@ module ActiveRecord
|
||||
def change_column_default(table_name, column_name, default) #:nodoc:
|
||||
current_type = select_one("SHOW COLUMNS FROM #{table_name} LIKE '#{column_name}'")["Type"]
|
||||
|
||||
change_column(table_name, column_name, current_type, { :default => default })
|
||||
execute("ALTER TABLE #{table_name} CHANGE #{column_name} #{column_name} #{current_type} DEFAULT #{quote(default)}")
|
||||
end
|
||||
|
||||
def change_column(table_name, column_name, type, options = {}) #:nodoc:
|
||||
if options[:default].nil?
|
||||
unless options_include_default?(options)
|
||||
options[:default] = select_one("SHOW COLUMNS FROM #{table_name} LIKE '#{column_name}'")["Default"]
|
||||
end
|
||||
|
||||
|
||||
change_column_sql = "ALTER TABLE #{table_name} CHANGE #{column_name} #{column_name} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
|
||||
add_column_options!(change_column_sql, options)
|
||||
execute(change_column_sql)
|
||||
@@ -375,6 +383,7 @@ module ActiveRecord
|
||||
if encoding
|
||||
@connection.options(Mysql::SET_CHARSET_NAME, encoding) rescue nil
|
||||
end
|
||||
@connection.ssl_set(@config[:sslkey], @config[:sslcert], @config[:sslca], @config[:sslcapath], @config[:sslcipher]) if @config[:sslkey]
|
||||
@connection.real_connect(*@connection_options)
|
||||
execute("SET NAMES '#{encoding}'") if encoding
|
||||
end
|
||||
|
||||
@@ -122,8 +122,7 @@ module ActiveRecord
|
||||
|
||||
# DATABASE STATEMENTS ======================================
|
||||
|
||||
def add_limit_offset!(sql, options) #:nodoc
|
||||
if limit = options[:limit]
|
||||
def add_limit_offset!(sql, options) #:nodoc: if limit = options[:limit]
|
||||
unless offset = options[:offset]
|
||||
sql << " RETURN RESULTS #{limit}"
|
||||
else
|
||||
|
||||
@@ -41,28 +41,17 @@ begin
|
||||
self.oracle_connection(config)
|
||||
end
|
||||
|
||||
# Enable the id column to be bound into the sql later, by the adapter's insert method.
|
||||
# This is preferable to inserting the hard-coded value here, because the insert method
|
||||
# needs to know the id value explicitly.
|
||||
alias :attributes_with_quotes_pre_oracle :attributes_with_quotes
|
||||
def attributes_with_quotes(include_primary_key = true) #:nodoc:
|
||||
aq = attributes_with_quotes_pre_oracle(include_primary_key)
|
||||
if connection.class == ConnectionAdapters::OracleAdapter
|
||||
aq[self.class.primary_key] = ":id" if include_primary_key && aq[self.class.primary_key].nil?
|
||||
end
|
||||
aq
|
||||
end
|
||||
|
||||
# After setting large objects to empty, select the OCI8::LOB
|
||||
# and write back the data.
|
||||
after_save :write_lobs
|
||||
after_save :write_lobs
|
||||
def write_lobs() #:nodoc:
|
||||
if connection.is_a?(ConnectionAdapters::OracleAdapter)
|
||||
self.class.columns.select { |c| c.sql_type =~ /LOB$/i }.each { |c|
|
||||
value = self[c.name]
|
||||
value = value.to_yaml if unserializable_attribute?(c.name, c)
|
||||
next if value.nil? || (value == '')
|
||||
lob = connection.select_one(
|
||||
"SELECT #{c.name} FROM #{self.class.table_name} WHERE #{self.class.primary_key} = #{quote(id)}",
|
||||
"SELECT #{c.name} FROM #{self.class.table_name} WHERE #{self.class.primary_key} = #{quote_value(id)}",
|
||||
'Writable Large Object')[c.name]
|
||||
lob.write value
|
||||
}
|
||||
@@ -77,7 +66,6 @@ begin
|
||||
class OracleColumn < Column #:nodoc:
|
||||
|
||||
def type_cast(value)
|
||||
return nil if value =~ /^\s*null\s*$/i
|
||||
return guess_date_or_time(value) if type == :datetime && OracleAdapter.emulate_dates
|
||||
super
|
||||
end
|
||||
@@ -145,9 +133,8 @@ begin
|
||||
def supports_migrations? #:nodoc:
|
||||
true
|
||||
end
|
||||
|
||||
def native_database_types #:nodoc
|
||||
{
|
||||
|
||||
def native_database_types #:nodoc: {
|
||||
:primary_key => "NUMBER(38) NOT NULL PRIMARY KEY",
|
||||
:string => { :name => "VARCHAR2", :limit => 255 },
|
||||
:text => { :name => "CLOB" },
|
||||
@@ -183,7 +170,7 @@ begin
|
||||
|
||||
def quote(value, column = nil) #:nodoc:
|
||||
if column && [:text, :binary].include?(column.type)
|
||||
%Q{empty_#{ column.sql_type rescue 'blob' }()}
|
||||
%Q{empty_#{ column.sql_type.downcase rescue 'blob' }()}
|
||||
else
|
||||
super
|
||||
end
|
||||
@@ -192,7 +179,7 @@ begin
|
||||
def quoted_true
|
||||
"1"
|
||||
end
|
||||
|
||||
|
||||
def quoted_false
|
||||
"0"
|
||||
end
|
||||
@@ -204,7 +191,7 @@ begin
|
||||
# Returns true if the connection is active.
|
||||
def active?
|
||||
# Pings the connection to check if it's still good. Note that an
|
||||
# #active? method is also available, but that simply returns the
|
||||
# #active? method is also available, but that simply returns the
|
||||
# last known state, which isn't good enough if the connection has
|
||||
# gone stale since the last use.
|
||||
@connection.ping
|
||||
@@ -230,34 +217,23 @@ begin
|
||||
#
|
||||
# see: abstract/database_statements.rb
|
||||
|
||||
def select_all(sql, name = nil) #:nodoc:
|
||||
select(sql, name)
|
||||
end
|
||||
|
||||
def select_one(sql, name = nil) #:nodoc:
|
||||
result = select_all(sql, name)
|
||||
result.size > 0 ? result.first : nil
|
||||
end
|
||||
|
||||
def execute(sql, name = nil) #:nodoc:
|
||||
log(sql, name) { @connection.exec sql }
|
||||
end
|
||||
|
||||
def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc:
|
||||
if pk.nil? # Who called us? What does the sql look like? No idea!
|
||||
execute sql, name
|
||||
elsif id_value # Pre-assigned id
|
||||
log(sql, name) { @connection.exec sql }
|
||||
else # Assume the sql contains a bind-variable for the id
|
||||
id_value = select_one("select #{sequence_name}.nextval id from dual")['id'].to_i
|
||||
log(sql.sub(/\B:id\b/, id_value.to_s), name) { @connection.exec sql, id_value }
|
||||
end
|
||||
|
||||
id_value
|
||||
# Returns the next sequence value from a sequence generator. Not generally
|
||||
# called directly; used by ActiveRecord to get the next primary key value
|
||||
# when inserting a new database record (see #prefetch_primary_key?).
|
||||
def next_sequence_value(sequence_name)
|
||||
id = 0
|
||||
@connection.exec("select #{sequence_name}.nextval id from dual") { |r| id = r[0].to_i }
|
||||
id
|
||||
end
|
||||
|
||||
alias :update :execute #:nodoc:
|
||||
alias :delete :execute #:nodoc:
|
||||
def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc:
|
||||
execute(sql, name)
|
||||
id_value
|
||||
end
|
||||
|
||||
def begin_db_transaction #:nodoc:
|
||||
@connection.autocommit = false
|
||||
@@ -285,6 +261,12 @@ begin
|
||||
end
|
||||
end
|
||||
|
||||
# Returns true for Oracle adapter (since Oracle requires primary key
|
||||
# values to be pre-fetched before insert). See also #next_sequence_value.
|
||||
def prefetch_primary_key?(table_name = nil)
|
||||
true
|
||||
end
|
||||
|
||||
def default_sequence_name(table, column) #:nodoc:
|
||||
"#{table}_seq"
|
||||
end
|
||||
@@ -332,7 +314,7 @@ begin
|
||||
def columns(table_name, name = nil) #:nodoc:
|
||||
(owner, table_name) = @connection.describe(table_name)
|
||||
|
||||
table_cols = %Q{
|
||||
table_cols = <<-SQL
|
||||
select column_name as name, data_type as sql_type, data_default, nullable,
|
||||
decode(data_type, 'NUMBER', data_precision,
|
||||
'FLOAT', data_precision,
|
||||
@@ -343,7 +325,7 @@ begin
|
||||
where owner = '#{owner}'
|
||||
and table_name = '#{table_name}'
|
||||
order by column_id
|
||||
}
|
||||
SQL
|
||||
|
||||
select_all(table_cols, name).map do |row|
|
||||
limit, scale = row['limit'], row['scale']
|
||||
@@ -355,6 +337,7 @@ begin
|
||||
if row['data_default']
|
||||
row['data_default'].sub!(/^(.*?)\s*$/, '\1')
|
||||
row['data_default'].sub!(/^'(.*)'$/, '\1')
|
||||
row['data_default'] = nil if row['data_default'] =~ /^null$/i
|
||||
end
|
||||
|
||||
OracleColumn.new(oracle_downcase(row['name']),
|
||||
@@ -366,17 +349,19 @@ begin
|
||||
|
||||
def create_table(name, options = {}) #:nodoc:
|
||||
super(name, options)
|
||||
execute "CREATE SEQUENCE #{name}_seq START WITH 10000" unless options[:id] == false
|
||||
seq_name = options[:sequence_name] || "#{name}_seq"
|
||||
execute "CREATE SEQUENCE #{seq_name} START WITH 10000" unless options[:id] == false
|
||||
end
|
||||
|
||||
def rename_table(name, new_name) #:nodoc:
|
||||
execute "RENAME #{name} TO #{new_name}"
|
||||
execute "RENAME #{name}_seq TO #{new_name}_seq" rescue nil
|
||||
end
|
||||
end
|
||||
|
||||
def drop_table(name) #:nodoc:
|
||||
def drop_table(name, options = {}) #:nodoc:
|
||||
super(name)
|
||||
execute "DROP SEQUENCE #{name}_seq" rescue nil
|
||||
seq_name = options[:sequence_name] || "#{name}_seq"
|
||||
execute "DROP SEQUENCE #{seq_name}" rescue nil
|
||||
end
|
||||
|
||||
def remove_index(table_name, options = {}) #:nodoc:
|
||||
@@ -401,26 +386,45 @@ begin
|
||||
execute "ALTER TABLE #{table_name} DROP COLUMN #{column_name}"
|
||||
end
|
||||
|
||||
# Find a table's primary key and sequence.
|
||||
# *Note*: Only primary key is implemented - sequence will be nil.
|
||||
def pk_and_sequence_for(table_name)
|
||||
(owner, table_name) = @connection.describe(table_name)
|
||||
|
||||
pks = select_values(<<-SQL, 'Primary Key')
|
||||
select cc.column_name
|
||||
from all_constraints c, all_cons_columns cc
|
||||
where c.owner = '#{owner}'
|
||||
and c.table_name = '#{table_name}'
|
||||
and c.constraint_type = 'P'
|
||||
and cc.owner = c.owner
|
||||
and cc.constraint_name = c.constraint_name
|
||||
SQL
|
||||
|
||||
# only support single column keys
|
||||
pks.size == 1 ? [oracle_downcase(pks.first), nil] : nil
|
||||
end
|
||||
|
||||
def structure_dump #:nodoc:
|
||||
s = select_all("select sequence_name from user_sequences").inject("") do |structure, seq|
|
||||
structure << "create sequence #{seq.to_a.first.last};\n\n"
|
||||
end
|
||||
|
||||
select_all("select table_name from user_tables").inject(s) do |structure, table|
|
||||
ddl = "create table #{table.to_a.first.last} (\n "
|
||||
ddl = "create table #{table.to_a.first.last} (\n "
|
||||
cols = select_all(%Q{
|
||||
select column_name, data_type, data_length, data_precision, data_scale, data_default, nullable
|
||||
from user_tab_columns
|
||||
where table_name = '#{table.to_a.first.last}'
|
||||
order by column_id
|
||||
}).map do |row|
|
||||
col = "#{row['column_name'].downcase} #{row['data_type'].downcase}"
|
||||
}).map do |row|
|
||||
col = "#{row['column_name'].downcase} #{row['data_type'].downcase}"
|
||||
if row['data_type'] =='NUMBER' and !row['data_precision'].nil?
|
||||
col << "(#{row['data_precision'].to_i}"
|
||||
col << ",#{row['data_scale'].to_i}" if !row['data_scale'].nil?
|
||||
col << ')'
|
||||
elsif row['data_type'].include?('CHAR')
|
||||
col << "(#{row['data_length'].to_i})"
|
||||
col << "(#{row['data_length'].to_i})"
|
||||
end
|
||||
col << " default #{row['data_default']}" if !row['data_default'].nil?
|
||||
col << ' not null' if row['nullable'] == 'N'
|
||||
@@ -442,6 +446,41 @@ begin
|
||||
end
|
||||
end
|
||||
|
||||
# SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
|
||||
#
|
||||
# Oracle requires the ORDER BY columns to be in the SELECT list for DISTINCT
|
||||
# queries. However, with those columns included in the SELECT DISTINCT list, you
|
||||
# won't actually get a distinct list of the column you want (presuming the column
|
||||
# has duplicates with multiple values for the ordered-by columns. So we use the
|
||||
# FIRST_VALUE function to get a single (first) value for each column, effectively
|
||||
# making every row the same.
|
||||
#
|
||||
# distinct("posts.id", "posts.created_at desc")
|
||||
def distinct(columns, order_by)
|
||||
return "DISTINCT #{columns}" if order_by.blank?
|
||||
|
||||
# construct a valid DISTINCT clause, ie. one that includes the ORDER BY columns, using
|
||||
# FIRST_VALUE such that the inclusion of these columns doesn't invalidate the DISTINCT
|
||||
order_columns = order_by.split(',').map { |s| s.strip }.reject(&:blank?)
|
||||
order_columns = order_columns.zip((0...order_columns.size).to_a).map do |c, i|
|
||||
"FIRST_VALUE(#{c.split.first}) OVER (PARTITION BY #{columns} ORDER BY #{c}) AS alias_#{i}__"
|
||||
end
|
||||
sql = "DISTINCT #{columns}, "
|
||||
sql << order_columns * ", "
|
||||
end
|
||||
|
||||
# ORDER BY clause for the passed order option.
|
||||
#
|
||||
# Uses column aliases as defined by #distinct.
|
||||
def add_order_by_for_association_limiting!(sql, options)
|
||||
return sql if options[:order].blank?
|
||||
|
||||
order = options[:order].split(',').collect { |s| s.strip }.reject(&:blank?)
|
||||
order.map! {|s| $1 if s =~ / (.*)/}
|
||||
order = order.zip((0...order.size).to_a).map { |s,i| "alias_#{i}__ #{s}" }.join(', ')
|
||||
|
||||
sql << "ORDER BY #{order}"
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
@@ -518,7 +557,7 @@ begin
|
||||
def describe(name)
|
||||
@desc ||= @@env.alloc(OCIDescribe)
|
||||
@desc.attrSet(OCI_ATTR_DESC_PUBLIC, -1) if VERSION >= '0.1.14'
|
||||
@desc.describeAny(@svc, name.to_s, OCI_PTYPE_UNK)
|
||||
@desc.describeAny(@svc, name.to_s, OCI_PTYPE_UNK) rescue raise %Q{"DESC #{name}" failed; does it exist?}
|
||||
info = @desc.attrGet(OCI_ATTR_PARAM)
|
||||
|
||||
case info.attrGet(OCI_ATTR_PTYPE)
|
||||
@@ -530,6 +569,7 @@ begin
|
||||
schema = info.attrGet(OCI_ATTR_SCHEMA_NAME)
|
||||
name = info.attrGet(OCI_ATTR_NAME)
|
||||
describe(schema + '.' + name)
|
||||
else raise %Q{"DESC #{name}" failed; not a table or view.}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -539,12 +579,14 @@ begin
|
||||
# The OracleConnectionFactory factors out the code necessary to connect and
|
||||
# configure an Oracle/OCI connection.
|
||||
class OracleConnectionFactory #:nodoc:
|
||||
def new_connection(username, password, database, async)
|
||||
def new_connection(username, password, database, async, prefetch_rows, cursor_sharing)
|
||||
conn = OCI8.new username, password, database
|
||||
conn.exec %q{alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'}
|
||||
conn.exec %q{alter session set nls_timestamp_format = 'YYYY-MM-DD HH24:MI:SS'} rescue nil
|
||||
conn.autocommit = true
|
||||
conn.non_blocking = true if async
|
||||
conn.prefetch_rows = prefetch_rows
|
||||
conn.exec "alter session set cursor_sharing = #{cursor_sharing}" rescue nil
|
||||
conn
|
||||
end
|
||||
end
|
||||
@@ -552,10 +594,10 @@ begin
|
||||
|
||||
# The OCI8AutoRecover class enhances the OCI8 driver with auto-recover and
|
||||
# reset functionality. If a call to #exec fails, and autocommit is turned on
|
||||
# (ie., we're not in the middle of a longer transaction), it will
|
||||
# (ie., we're not in the middle of a longer transaction), it will
|
||||
# automatically reconnect and try again. If autocommit is turned off,
|
||||
# this would be dangerous (as the earlier part of the implied transaction
|
||||
# may have failed silently if the connection died) -- so instead the
|
||||
# may have failed silently if the connection died) -- so instead the
|
||||
# connection is marked as dead, to be reconnected on it's next use.
|
||||
class OCI8AutoRecover < DelegateClass(OCI8) #:nodoc:
|
||||
attr_accessor :active
|
||||
@@ -571,8 +613,10 @@ begin
|
||||
@active = true
|
||||
@username, @password, @database, = config[:username], config[:password], config[:database]
|
||||
@async = config[:allow_concurrency]
|
||||
@prefetch_rows = config[:prefetch_rows] || 100
|
||||
@cursor_sharing = config[:cursor_sharing] || 'similar'
|
||||
@factory = factory
|
||||
@connection = @factory.new_connection @username, @password, @database, @async
|
||||
@connection = @factory.new_connection @username, @password, @database, @async, @prefetch_rows, @cursor_sharing
|
||||
super @connection
|
||||
end
|
||||
|
||||
@@ -591,7 +635,7 @@ begin
|
||||
def reset!
|
||||
logoff rescue nil
|
||||
begin
|
||||
@connection = @factory.new_connection @username, @password, @database, @async
|
||||
@connection = @factory.new_connection @username, @password, @database, @async, @prefetch_rows, @cursor_sharing
|
||||
__setobj__ @connection
|
||||
@active = true
|
||||
rescue
|
||||
@@ -601,7 +645,7 @@ begin
|
||||
end
|
||||
|
||||
# ORA-00028: your session has been killed
|
||||
# ORA-01012: not logged on
|
||||
# ORA-01012: not logged on
|
||||
# ORA-03113: end-of-file on communication channel
|
||||
# ORA-03114: not connected to ORACLE
|
||||
LOST_CONNECTION_ERROR_CODES = [ 28, 1012, 3113, 3114 ]
|
||||
@@ -630,13 +674,14 @@ rescue LoadError
|
||||
# OCI8 driver is unavailable.
|
||||
module ActiveRecord # :nodoc:
|
||||
class Base
|
||||
@@oracle_error_message = "Oracle/OCI libraries could not be loaded: #{$!.to_s}"
|
||||
def self.oracle_connection(config) # :nodoc:
|
||||
# Set up a reasonable error message
|
||||
raise LoadError, "Oracle/OCI libraries could not be loaded."
|
||||
raise LoadError, @@oracle_error_message
|
||||
end
|
||||
def self.oci_connection(config) # :nodoc:
|
||||
# Set up a reasonable error message
|
||||
raise LoadError, "Oracle/OCI libraries could not be loaded."
|
||||
raise LoadError, @@oracle_error_message
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -111,10 +111,6 @@ module ActiveRecord
|
||||
63
|
||||
end
|
||||
|
||||
def requires_order_columns_in_distinct_clause?
|
||||
true
|
||||
end
|
||||
|
||||
# QUOTING ==================================================
|
||||
|
||||
def quote(value, column = nil)
|
||||
@@ -136,15 +132,6 @@ module ActiveRecord
|
||||
|
||||
# DATABASE STATEMENTS ======================================
|
||||
|
||||
def select_all(sql, name = nil) #:nodoc:
|
||||
select(sql, name)
|
||||
end
|
||||
|
||||
def select_one(sql, name = nil) #:nodoc:
|
||||
result = select(sql, name)
|
||||
result.first if result
|
||||
end
|
||||
|
||||
def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc:
|
||||
execute(sql, name)
|
||||
table = sql.split(" ", 4)[2]
|
||||
@@ -175,9 +162,6 @@ module ActiveRecord
|
||||
execute(sql, name).cmdtuples
|
||||
end
|
||||
|
||||
alias_method :delete, :update #:nodoc:
|
||||
|
||||
|
||||
def begin_db_transaction #:nodoc:
|
||||
execute "BEGIN"
|
||||
end
|
||||
@@ -337,10 +321,10 @@ module ActiveRecord
|
||||
execute("ALTER TABLE #{table_name} ADD COLUMN #{column_name} #{type_to_sql(type, options[:limit])}")
|
||||
|
||||
# Set optional default. If not null, update nulls to the new default.
|
||||
unless default.nil?
|
||||
if options_include_default?(options)
|
||||
change_column_default(table_name, column_name, default)
|
||||
if notnull
|
||||
execute("UPDATE #{table_name} SET #{column_name}='#{default}' WHERE #{column_name} IS NULL")
|
||||
execute("UPDATE #{table_name} SET #{column_name}=#{quote(default, options[:column])} WHERE #{column_name} IS NULL")
|
||||
end
|
||||
end
|
||||
|
||||
@@ -361,11 +345,14 @@ module ActiveRecord
|
||||
rename_column(table_name, "#{column_name}_ar_tmp", column_name)
|
||||
commit_db_transaction
|
||||
end
|
||||
change_column_default(table_name, column_name, options[:default]) unless options[:default].nil?
|
||||
|
||||
if options_include_default?(options)
|
||||
change_column_default(table_name, column_name, options[:default])
|
||||
end
|
||||
end
|
||||
|
||||
def change_column_default(table_name, column_name, default) #:nodoc:
|
||||
execute "ALTER TABLE #{table_name} ALTER COLUMN #{quote_column_name(column_name)} SET DEFAULT '#{default}'"
|
||||
execute "ALTER TABLE #{table_name} ALTER COLUMN #{quote_column_name(column_name)} SET DEFAULT #{quote(default)}"
|
||||
end
|
||||
|
||||
def rename_column(table_name, column_name, new_column_name) #:nodoc:
|
||||
@@ -388,14 +375,39 @@ module ActiveRecord
|
||||
end
|
||||
end
|
||||
|
||||
# PostgreSQL requires the ORDER BY columns in the select list for distinct queries.
|
||||
# If you select distinct by a column though, you must pass that column in the order by clause too:
|
||||
# SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
|
||||
#
|
||||
# distinct("posts.id", 'posts.id', 'posts.created_at')
|
||||
def distinct(columns, *order_columns)
|
||||
# PostgreSQL requires the ORDER BY columns in the select list for distinct queries, and
|
||||
# requires that the ORDER BY include the distinct column.
|
||||
#
|
||||
# distinct("posts.id", "posts.created_at desc")
|
||||
def distinct(columns, order_by)
|
||||
return "DISTINCT #{columns}" if order_by.blank?
|
||||
|
||||
# construct a clean list of column names from the ORDER BY clause, removing
|
||||
# any asc/desc modifiers
|
||||
order_columns = order_by.split(',').collect { |s| s.split.first }
|
||||
order_columns.delete_if &:blank?
|
||||
sql = "DISTINCT ON (#{columns}) #{columns}"
|
||||
sql << (order_columns.any? ? ", #{order_columns * ', '}" : '')
|
||||
order_columns = order_columns.zip((0...order_columns.size).to_a).map { |s,i| "#{s} AS alias_#{i}" }
|
||||
|
||||
# return a DISTINCT ON() clause that's distinct on the columns we want but includes
|
||||
# all the required columns for the ORDER BY to work properly
|
||||
sql = "DISTINCT ON (#{columns}) #{columns}, "
|
||||
sql << order_columns * ', '
|
||||
end
|
||||
|
||||
# ORDER BY clause for the passed order option.
|
||||
#
|
||||
# PostgreSQL does not allow arbitrary ordering when using DISTINCT ON, so we work around this
|
||||
# by wrapping the sql as a sub-select and ordering in that query.
|
||||
def add_order_by_for_association_limiting!(sql, options)
|
||||
return sql if options[:order].blank?
|
||||
|
||||
order = options[:order].split(',').collect { |s| s.strip }.reject(&:blank?)
|
||||
order.map! { |s| 'DESC' if s =~ /\bdesc$/i }
|
||||
order = order.zip((0...order.size).to_a).map { |s,i| "id_list.alias_#{i} #{s}" }.join(', ')
|
||||
|
||||
sql.replace "SELECT * FROM (#{sql}) AS id_list ORDER BY #{order}"
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
@@ -101,6 +101,10 @@ module ActiveRecord
|
||||
def supports_migrations? #:nodoc:
|
||||
true
|
||||
end
|
||||
|
||||
def requires_reloading?
|
||||
true
|
||||
end
|
||||
|
||||
def supports_count_distinct? #:nodoc:
|
||||
false
|
||||
@@ -250,10 +254,11 @@ module ActiveRecord
|
||||
|
||||
def change_column(table_name, column_name, type, options = {}) #:nodoc:
|
||||
alter_table(table_name) do |definition|
|
||||
include_default = options_include_default?(options)
|
||||
definition[column_name].instance_eval do
|
||||
self.type = type
|
||||
self.limit = options[:limit] if options[:limit]
|
||||
self.default = options[:default] unless options[:default].nil?
|
||||
self.limit = options[:limit] if options.include?(:limit)
|
||||
self.default = options[:default] if include_default
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user