Added record identifications to FormHelper#form_for and PrototypeHelper#remote_form_for [DHH]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@6731 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
上级 50253ede
*SVN*
* Added record identifications to FormHelper#form_for and PrototypeHelper#remote_form_for [DHH]. Examples:
<% form_for(@post) do |f| %>
...
<% end %>
This will expand to be the same as:
<% form_for :post, @post, :url => post_path(@post), :html => { :method => :put, :class => "edit_post", :id => "edit_post_45" } do |f| %>
...
<% end %>
And for new records:
<% form_for(Post.new) do |f| %>
...
<% end %>
This will expand to be the same as:
<% form_for :post, @post, :url => posts_path, :html => { :class => "new_post", :id => "new_post" } do |f| %>
...
<% end %>
* Rationalize route path escaping according to RFC 2396 section 3.3. #7544, #8307. [Jeremy Kemper, chrisroos, begemot, jugend]
* Added record identification with polymorphic routes for ActionController::Base#url_for and ActionView::Base#url_for [DHH]. Examples:
......
......@@ -999,6 +999,7 @@ def default_url_options(options) #:doc:
# Redirects the browser to the target specified in +options+. This parameter can take one of three forms:
#
# * <tt>Hash</tt>: The URL will be generated by calling url_for with the +options+.
# * <tt>Record</tt>: The URL will be generated by calling url_for with the +options+, which will reference a named URL for that record.
# * <tt>String starting with protocol:// (like http://)</tt>: Is passed straight through as the target for redirection.
# * <tt>String not containing a protocol</tt>: The current protocol and host is prepended to the string.
# * <tt>:back</tt>: Back to the page that issued the request. Useful for forms that are triggered from multiple places.
......@@ -1006,6 +1007,7 @@ def default_url_options(options) #:doc:
#
# Examples:
# redirect_to :action => "show", :id => 5
# redirect_to post
# redirect_to "http://www.rubyonrails.org"
# redirect_to "/images/screenshot.jpg"
# redirect_to :back
......
......@@ -7,10 +7,14 @@ def polymorphic_url(record_or_hash, url_writer, options = {})
case
when options[:action] == "new"
url_writer.send(action_prefix(options) + RecordIdentifier.singular_class_name(record) + routing_type(options))
url_writer.send(
action_prefix(options) + RecordIdentifier.singular_class_name(record) + routing_type(options)
)
when record.respond_to?(:new_record?) && record.new_record?
url_writer.send(RecordIdentifier.plural_class_name(record) + routing_type(options))
url_writer.send(
action_prefix(options) + RecordIdentifier.plural_class_name(record) + routing_type(options)
)
else
url_writer.send(
......
......@@ -63,7 +63,7 @@ def dom_class(record_or_class, prefix = nil)
#
# dom_class(Post.new(:id => 45), :edit) # => "edit_post_45"
def dom_id(record, prefix = nil)
prefix ||= 'new' unless record.id
prefix ||= 'new' unless record.id
[ prefix, singular_class_name(record), record.id ].compact * '_'
end
......
......@@ -103,6 +103,41 @@ module FormHelper
# The above form will then have the <tt>id</tt> attribute with the value </tt>person_form</tt>, which you can then
# style with CSS or manipulate with JavaScript.
#
# === Relying on record identification
#
# In addition to manually configuring the form_for call, you can also rely on record identification, which will use
# the conventions and named routes of that approach. Examples:
#
# <% form_for(@post) do |f| %>
# ...
# <% end %>
#
# This will expand to be the same as:
#
# <% form_for :post, @post, :url => post_path(@post), :html => { :method => :put, :class => "edit_post", :id => "edit_post_45" } do |f| %>
# ...
# <% end %>
#
# And for new records:
#
# <% form_for(Post.new) do |f| %>
# ...
# <% end %>
#
# This will expand to be the same as:
#
# <% form_for :post, @post, :url => posts_path, :html => { :class => "new_post", :id => "new_post" } do |f| %>
# ...
# <% end %>
#
# You can also overwrite the individual conventions, like this:
#
# <% form_for(@post, :url => super_post_path(@post)) do |f| %>
# ...
# <% end %>
#
# === Customized form builders
#
# You can also build forms using a customized FormBuilder class. Subclass FormBuilder and override or define some more helpers,
# then use your custom builder. For example, let's say you made a helper to automatically add labels to form inputs.
#
......@@ -120,13 +155,37 @@ module FormHelper
# end
#
# If you don't need to attach a form to a model instance, then check out FormTagHelper#form_tag.
def form_for(object_name, *args, &proc)
def form_for(record_or_name, *args, &proc)
raise ArgumentError, "Missing block" unless block_given?
options = args.last.is_a?(Hash) ? args.pop : {}
case record_or_name
when String, Symbol
object_name = record_or_name
else
object = record_or_name
object_name = ActionController::RecordIdentifier.singular_class_name(record_or_name)
apply_form_for_options!(object, options)
end
concat(form_tag(options.delete(:url) || {}, options.delete(:html) || {}), proc.binding)
fields_for(object_name, *(args << options), &proc)
concat('</form>', proc.binding)
end
def apply_form_for_options!(object, options) #:nodoc:
html_options = if object.respond_to?(:new_record?) && object.new_record?
{ :class => dom_class(object, :new), :id => dom_id(object), :method => :post }
else
{ :class => dom_class(object, :edit), :id => dom_id(object, :edit), :method => :put }
end
options[:html] ||= {}
options[:html].reverse_merge!(html_options)
options[:url] ||= polymorphic_path(object, self)
end
# Creates a scope around a specific model object like form_for, but doesn't create the form tags themselves. This makes
# fields_for suitable for specifying additional model objects in the same form:
......
......@@ -181,8 +181,18 @@ def form_remote_tag(options = {}, &block)
end
# Works like form_remote_tag, but uses form_for semantics.
def remote_form_for(object_name, *args, &proc)
def remote_form_for(record_or_name, *args, &proc)
options = args.last.is_a?(Hash) ? args.pop : {}
case record_or_name
when String, Symbol
object_name = record_or_name
else
object = record_or_name
object_name = ActionController::RecordIdentifier.singular_class_name(record_or_name)
apply_form_for_options!(object, options)
end
concat(form_remote_tag(options), proc.binding)
fields_for(object_name, *(args << options), &proc)
concat('</form>', proc.binding)
......
module RecordIdentificationHelper
# See ActionController::RecordIdentifier.partial_path -- this is just a delegate to that for convenient access in the view.
def partial_path(*args, &block)
ActionController::RecordIdentifier.partial_path(*args, &block)
end
module ActionView
module Helpers
module RecordIdentificationHelper
# See ActionController::RecordIdentifier.partial_path -- this is just a delegate to that for convenient access in the view.
def partial_path(*args, &block)
ActionController::RecordIdentifier.partial_path(*args, &block)
end
# See ActionController::RecordIdentifier.dom_class -- this is just a delegate to that for convenient access in the view.
def dom_class(*args, &block)
ActionController::RecordIdentifier.dom_class(*args, &block)
end
# See ActionController::RecordIdentifier.dom_class -- this is just a delegate to that for convenient access in the view.
def dom_class(*args, &block)
ActionController::RecordIdentifier.dom_class(*args, &block)
end
# See ActionController::RecordIdentifier.dom_id -- this is just a delegate to that for convenient access in the view.
def dom_id(*args, &block)
ActionController::RecordIdentifier.dom_id(*args, &block)
# See ActionController::RecordIdentifier.dom_id -- this is just a delegate to that for convenient access in the view.
def dom_id(*args, &block)
ActionController::RecordIdentifier.dom_id(*args, &block)
end
end
end
end
\ No newline at end of file
module RecordTagHelper
# Produces a wrapper DIV element with id and class parameters that
# relate to the specified ActiveRecord object. Usage example:
#
# <% div_for(@person, :class => "foo") do %>
# <%=h @person.name %>
# <% end %>
#
# produces:
#
# <div id="person_123" class="person foo"> Joe Bloggs </div>
#
def div_for(record, *args, &block)
content_tag_for(:div, record, *args, &block)
end
module ActionView
module Helpers
module RecordTagHelper
# Produces a wrapper DIV element with id and class parameters that
# relate to the specified ActiveRecord object. Usage example:
#
# <% div_for(@person, :class => "foo") do %>
# <%=h @person.name %>
# <% end %>
#
# produces:
#
# <div id="person_123" class="person foo"> Joe Bloggs </div>
#
def div_for(record, *args, &block)
content_tag_for(:div, record, *args, &block)
end
# content_tag_for creates an HTML element with id and class parameters
# that relate to the specified ActiveRecord object. For example:
#
# <% content_tag_for(:tr, @person) do %>
# <td><%=h @person.first_name %></td>
# <td><%=h @person.last_name %></td>
# <% end %>
#
# would produce hthe following HTML (assuming @person is an instance of
# a Person object, with an id value of 123):
#
# <tr id="person_123" class="person">....</tr>
#
# If you require the HTML id attribute to have a prefix, you can specify it:
#
# <% content_tag_for(:tr, @person, :foo) do %> ...
#
# produces:
#
# <tr id="foo_person_123" class="person">...
#
# content_tag_for also accepts a hash of options, which will be converted to
# additional HTML attributes. If you specify a +:class+ value, it will be combined
# with the default class name for your object. For example:
#
# <% content_tag_for(:li, @person, :class => "bar") %>...
#
# produces:
#
# <li id="person_123" class="person bar">...
#
def content_tag_for(tag_name, record, *args, &block)
prefix = args.first.is_a?(Hash) ? nil : args.shift
options = args.first.is_a?(Hash) ? args.shift : {}
concat content_tag(tag_name, capture(&block),
options.merge({ :class => "#{dom_class(record)} #{options[:class]}".strip, :id => dom_id(record, prefix) })),
block.binding
# content_tag_for creates an HTML element with id and class parameters
# that relate to the specified ActiveRecord object. For example:
#
# <% content_tag_for(:tr, @person) do %>
# <td><%=h @person.first_name %></td>
# <td><%=h @person.last_name %></td>
# <% end %>
#
# would produce hthe following HTML (assuming @person is an instance of
# a Person object, with an id value of 123):
#
# <tr id="person_123" class="person">....</tr>
#
# If you require the HTML id attribute to have a prefix, you can specify it:
#
# <% content_tag_for(:tr, @person, :foo) do %> ...
#
# produces:
#
# <tr id="foo_person_123" class="person">...
#
# content_tag_for also accepts a hash of options, which will be converted to
# additional HTML attributes. If you specify a +:class+ value, it will be combined
# with the default class name for your object. For example:
#
# <% content_tag_for(:li, @person, :class => "bar") %>...
#
# produces:
#
# <li id="person_123" class="person bar">...
#
def content_tag_for(tag_name, record, *args, &block)
prefix = args.first.is_a?(Hash) ? nil : args.shift
options = args.first.is_a?(Hash) ? args.shift : {}
concat content_tag(tag_name, capture(&block),
options.merge({ :class => "#{dom_class(record)} #{options[:class]}".strip, :id => dom_id(record, prefix) })),
block.binding
end
end
end
end
\ No newline at end of file
require File.dirname(__FILE__) + '/../abstract_unit'
class Post
class Comment
attr_reader :id
def save; @id = 1 end
def new_record?; @id.nil? end
def name
@id.nil? ? 'new post' : "post ##{@id}"
@id.nil? ? 'new comment' : "comment ##{@id}"
end
class Nested < Post; end
end
class Comment::Nested < Comment; end
class Test::Unit::TestCase
protected
def posts_url
'http://www.example.com/posts'
def comments_url
'http://www.example.com/comments'
end
def post_url(post)
"http://www.example.com/posts/#{post.id}"
def comment_url(comment)
"http://www.example.com/comments/#{comment.id}"
end
end
......@@ -26,10 +27,10 @@ class RecordIdentifierTest < Test::Unit::TestCase
include ActionController::RecordIdentifier
def setup
@klass = Post
@klass = Comment
@record = @klass.new
@singular = 'post'
@plural = 'posts'
@singular = 'comment'
@plural = 'comments'
end
def test_dom_id_with_new_record
......@@ -53,7 +54,7 @@ def test_dom_id_with_prefix
def test_partial_path
expected = "#{@plural}/#{@singular}"
assert_equal expected, partial_path(@record)
assert_equal expected, partial_path(Post)
assert_equal expected, partial_path(Comment)
end
def test_dom_class
......@@ -88,15 +89,15 @@ def method_missing(method, *args)
class NestedRecordIdentifierTest < RecordIdentifierTest
def setup
@klass = Post::Nested
@klass = Comment::Nested
@record = @klass.new
@singular = 'post_nested'
@plural = 'post_nesteds'
@singular = 'comment_nested'
@plural = 'comment_nesteds'
end
def test_partial_path
expected = "post/nesteds/nested"
expected = "comment/nesteds/nested"
assert_equal expected, partial_path(@record)
assert_equal expected, partial_path(Post::Nested)
assert_equal expected, partial_path(Comment::Nested)
end
end
\ No newline at end of file
require "#{File.dirname(__FILE__)}/../abstract_unit"
silence_warnings do
Post = Struct.new(:title, :author_name, :body, :secret, :written_on, :cost)
Post.class_eval do
alias_method :title_before_type_cast, :title unless respond_to?(:title_before_type_cast)
alias_method :body_before_type_cast, :body unless respond_to?(:body_before_type_cast)
alias_method :author_name_before_type_cast, :author_name unless respond_to?(:author_name_before_type_cast)
def new_record=(boolean)
@new_record = boolean
end
def new_record?
@new_record
end
end
end
class FormHelperTest < Test::Unit::TestCase
include ActionView::Helpers::FormHelper
include ActionView::Helpers::FormTagHelper
......@@ -7,15 +24,7 @@ class FormHelperTest < Test::Unit::TestCase
include ActionView::Helpers::TagHelper
include ActionView::Helpers::TextHelper
include ActionView::Helpers::ActiveRecordHelper
silence_warnings do
Post = Struct.new("Post", :title, :author_name, :body, :secret, :written_on, :cost)
Post.class_eval do
alias_method :title_before_type_cast, :title unless respond_to?(:title_before_type_cast)
alias_method :body_before_type_cast, :body unless respond_to?(:body_before_type_cast)
alias_method :author_name_before_type_cast, :author_name unless respond_to?(:author_name_before_type_cast)
end
end
include ActionView::Helpers::RecordIdentificationHelper
def setup
@post = Post.new
......@@ -546,6 +555,38 @@ def test_form_for_with_record_url_option
form_for(:post, @post, :url => @post) do |f| end
expected = "<form action=\"/posts/123\" method=\"post\"></form>"
assert_equal expected, _erbout
end
def test_form_for_with_existing_object
_erbout = ''
form_for(@post) do |f| end
expected = "<form action=\"/posts/123\" class=\"edit_post\" id=\"edit_post_123\" method=\"post\"><div style=\"margin:0;padding:0\"><input name=\"_method\" type=\"hidden\" value=\"put\" /></div></form>"
assert_equal expected, _erbout
end
def test_form_for_with_new_object
_erbout = ''
post = Post.new
post.new_record = true
def post.id() nil end
form_for(post) do |f| end
expected = "<form action=\"/posts\" class=\"new_post\" id=\"new_post\" method=\"post\"></form>"
assert_equal expected, _erbout
end
def test_form_for_with_existing_object_and_custom_url
_erbout = ''
form_for(@post, :url => "/super_posts") do |f| end
expected = "<form action=\"/super_posts\" class=\"edit_post\" id=\"edit_post_123\" method=\"post\"><div style=\"margin:0;padding:0\"><input name=\"_method\" type=\"hidden\" value=\"put\" /></div></form>"
assert_equal expected, _erbout
end
def test_remote_form_for_with_html_options_adds_options_to_form_tag
......@@ -561,6 +602,10 @@ def test_remote_form_for_with_html_options_adds_options_to_form_tag
protected
def polymorphic_path(record, url_writer)
"/posts/#{record.id}"
if record.new_record?
"/posts"
else
"/posts/#{record.id}"
end
end
end
\ No newline at end of file
......@@ -2,6 +2,18 @@
Bunny = Struct.new(:Bunny, :id)
class Author
attr_reader :id
def save; @id = 1 end
def new_record?; @id.nil? end
def name
@id.nil? ? 'new author' : "author ##{@id}"
end
end
class Author::Nested < Author; end
module BaseTest
include ActionView::Helpers::JavaScriptHelper
include ActionView::Helpers::PrototypeHelper
......@@ -13,6 +25,7 @@ module BaseTest
include ActionView::Helpers::FormTagHelper
include ActionView::Helpers::FormHelper
include ActionView::Helpers::CaptureHelper
include ActionView::Helpers::RecordIdentificationHelper
def setup
@template = nil
......@@ -41,17 +54,22 @@ def create_generator
class PrototypeHelperTest < Test::Unit::TestCase
include BaseTest
def setup
@record = Author.new
super
end
def test_link_to_remote
assert_dom_equal %(<a class=\"fine\" href=\"#\" onclick=\"new Ajax.Request('http://www.example.com/whatnot', {asynchronous:true, evalScripts:true}); return false;\">Remote outpost</a>),
link_to_remote("Remote outpost", { :url => { :action => "whatnot" }}, { :class => "fine" })
assert_dom_equal %(<a href=\"#\" onclick=\"new Ajax.Request('http://www.example.com/whatnot', {asynchronous:true, evalScripts:true, onComplete:function(request){alert(request.reponseText)}}); return false;\">Remote outpost</a>),
link_to_remote("Remote outpost", :complete => "alert(request.reponseText)", :url => { :action => "whatnot" })
assert_dom_equal %(<a href=\"#\" onclick=\"new Ajax.Request('http://www.example.com/whatnot', {asynchronous:true, evalScripts:true, onSuccess:function(request){alert(request.reponseText)}}); return false;\">Remote outpost</a>),
link_to_remote("Remote outpost", :success => "alert(request.reponseText)", :url => { :action => "whatnot" })
assert_dom_equal %(<a href=\"#\" onclick=\"new Ajax.Request('http://www.example.com/whatnot', {asynchronous:true, evalScripts:true, onFailure:function(request){alert(request.reponseText)}}); return false;\">Remote outpost</a>),
link_to_remote("Remote outpost", :failure => "alert(request.reponseText)", :url => { :action => "whatnot" })
assert_dom_equal %(<a href=\"#\" onclick=\"new Ajax.Request('http://www.example.com/whatnot?a=10&amp;b=20', {asynchronous:true, evalScripts:true, onFailure:function(request){alert(request.reponseText)}}); return false;\">Remote outpost</a>),
link_to_remote("Remote outpost", :failure => "alert(request.reponseText)", :url => { :action => "whatnot", :a => '10', :b => '20' })
assert_dom_equal %(<a class=\"fine\" href=\"#\" onclick=\"new Ajax.Request('http://www.example.com/whatnot', {asynchronous:true, evalScripts:true}); return false;\">Remote outauthor</a>),
link_to_remote("Remote outauthor", { :url => { :action => "whatnot" }}, { :class => "fine" })
assert_dom_equal %(<a href=\"#\" onclick=\"new Ajax.Request('http://www.example.com/whatnot', {asynchronous:true, evalScripts:true, onComplete:function(request){alert(request.reponseText)}}); return false;\">Remote outauthor</a>),
link_to_remote("Remote outauthor", :complete => "alert(request.reponseText)", :url => { :action => "whatnot" })
assert_dom_equal %(<a href=\"#\" onclick=\"new Ajax.Request('http://www.example.com/whatnot', {asynchronous:true, evalScripts:true, onSuccess:function(request){alert(request.reponseText)}}); return false;\">Remote outauthor</a>),
link_to_remote("Remote outauthor", :success => "alert(request.reponseText)", :url => { :action => "whatnot" })
assert_dom_equal %(<a href=\"#\" onclick=\"new Ajax.Request('http://www.example.com/whatnot', {asynchronous:true, evalScripts:true, onFailure:function(request){alert(request.reponseText)}}); return false;\">Remote outauthor</a>),
link_to_remote("Remote outauthor", :failure => "alert(request.reponseText)", :url => { :action => "whatnot" })
assert_dom_equal %(<a href=\"#\" onclick=\"new Ajax.Request('http://www.example.com/whatnot?a=10&amp;b=20', {asynchronous:true, evalScripts:true, onFailure:function(request){alert(request.reponseText)}}); return false;\">Remote outauthor</a>),
link_to_remote("Remote outauthor", :failure => "alert(request.reponseText)", :url => { :action => "whatnot", :a => '10', :b => '20' })
end
def test_periodically_call_remote
......@@ -80,7 +98,32 @@ def test_form_remote_tag_with_block
form_remote_tag(:update => "glass_of_beer", :url => { :action => :fast }) { _erbout.concat "Hello world!" }
assert_dom_equal %(<form action=\"http://www.example.com/fast\" method=\"post\" onsubmit=\"new Ajax.Updater('glass_of_beer', 'http://www.example.com/fast', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;\">Hello world!</form>), _erbout
end
def test_remote_form_for_with_record_identification_with_new_record
_erbout = ''
remote_form_for(@record, {:html => { :id => 'create-author' }}) {}
expected = %(<form action='#{authors_url}' onsubmit="new Ajax.Request('#{authors_url}', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;" class='new_author' id='create-author' method='post'></form>)
assert_dom_equal expected, _erbout
end
def test_remote_form_for_with_record_identification_without_html_options
_erbout = ''
remote_form_for(@record) {}
expected = %(<form action='#{authors_url}' onsubmit="new Ajax.Request('#{authors_url}', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;" class='new_author' method='post' id='new_author'></form>)
assert_dom_equal expected, _erbout
end
def test_remote_form_for_with_record_identification_with_existing_record
@record.save
_erbout = ''
remote_form_for(@record) {}
expected = %(<form action='#{author_url(@record)}' id='edit_author_1' method='post' onsubmit="new Ajax.Request('#{author_url(@record)}', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;" class='edit_author'><div style='margin:0;padding:0'><input name='_method' type='hidden' value='put' /></div></form>)
assert_dom_equal expected, _erbout
end
def test_on_callbacks
callbacks = [:uninitialized, :loading, :loaded, :interactive, :complete, :success, :failure]
callbacks.each do |callback|
......@@ -161,6 +204,23 @@ def test_update_page_tag_with_html_options
assert_equal javascript_tag(create_generator(&block).to_s, {:defer => 'true'}), update_page_tag({:defer => 'true'}, &block)
end
protected
def author_url(record)
"/authors/#{record.id}"
end
def authors_url
"/authors"
end
def polymorphic_path(record, url_writer)
if record.new_record?
"/authors"
else
"/authors/#{record.id}"
end
end
end
class JavaScriptGeneratorTest < Test::Unit::TestCase
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册