aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/lib/action_view
diff options
context:
space:
mode:
Diffstat (limited to 'actionpack/lib/action_view')
-rw-r--r--actionpack/lib/action_view/base.rb264
-rw-r--r--actionpack/lib/action_view/helpers/active_record_helper.rb171
-rwxr-xr-xactionpack/lib/action_view/helpers/date_helper.rb230
-rw-r--r--actionpack/lib/action_view/helpers/debug_helper.rb17
-rw-r--r--actionpack/lib/action_view/helpers/form_helper.rb182
-rw-r--r--actionpack/lib/action_view/helpers/form_options_helper.rb212
-rw-r--r--actionpack/lib/action_view/helpers/tag_helper.rb59
-rw-r--r--actionpack/lib/action_view/helpers/text_helper.rb111
-rw-r--r--actionpack/lib/action_view/helpers/url_helper.rb78
-rw-r--r--actionpack/lib/action_view/partials.rb64
-rw-r--r--actionpack/lib/action_view/template_error.rb84
-rw-r--r--actionpack/lib/action_view/vendor/builder.rb13
-rw-r--r--actionpack/lib/action_view/vendor/builder/blankslate.rb51
-rw-r--r--actionpack/lib/action_view/vendor/builder/xmlbase.rb143
-rw-r--r--actionpack/lib/action_view/vendor/builder/xmlevents.rb63
-rw-r--r--actionpack/lib/action_view/vendor/builder/xmlmarkup.rb288
16 files changed, 2030 insertions, 0 deletions
diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb
new file mode 100644
index 0000000000..84c8040760
--- /dev/null
+++ b/actionpack/lib/action_view/base.rb
@@ -0,0 +1,264 @@
+require 'erb'
+
+module ActionView #:nodoc:
+ class ActionViewError < StandardError #:nodoc:
+ end
+
+ # Action View templates can be written in two ways. If the template file has a +.rhtml+ extension then it uses a mixture of ERb
+ # (included in Ruby) and HTML. If the template file has a +.rxml+ extension then Jim Weirich's Builder::XmlMarkup library is used.
+ #
+ # = ERb
+ #
+ # You trigger ERb by using embeddings such as <% %> and <%= %>. The difference is whether you want output or not. Consider the
+ # following loop for names:
+ #
+ # <b>Names of all the people</b>
+ # <% for person in @people %>
+ # Name: <%= person.name %><br/>
+ # <% end %>
+ #
+ # The loop is setup in regular embedding tags (<% %>) and the name is written using the output embedding tag (<%= %>). Note that this
+ # is not just a usage suggestion. Regular output functions like print or puts won't work with ERb templates. So this would be wrong:
+ #
+ # Hi, Mr. <% puts "Frodo" %>
+ #
+ # (If you absolutely must write from within a function, you can use the TextHelper#concat)
+ #
+ # == Using sub templates
+ #
+ # Using sub templates allows you to sidestep tedious replication and extract common display structures in shared templates. The
+ # classic example is the use of a header and footer (even though the Action Pack-way would be to use Layouts):
+ #
+ # <%= render "shared/header" %>
+ # Something really specific and terrific
+ # <%= render "shared/footer" %>
+ #
+ # As you see, we use the output embeddings for the render methods. The render call itself will just return a string holding the
+ # result of the rendering. The output embedding writes it to the current template.
+ #
+ # But you don't have to restrict yourself to static includes. Templates can share variables amongst themselves by using instance
+ # variables defined in using the regular embedding tags. Like this:
+ #
+ # <% @page_title = "A Wonderful Hello" %>
+ # <%= render "shared/header" %>
+ #
+ # Now the header can pick up on the @page_title variable and use it for outputting a title tag:
+ #
+ # <title><%= @page_title %></title>
+ #
+ # == Passing local variables to sub templates
+ #
+ # You can pass local variables to sub templates by using a hash with the variable names as keys and the objects as values:
+ #
+ # <%= render "shared/header", { "headline" => "Welcome", "person" => person } %>
+ #
+ # These can now be accessed in shared/header with:
+ #
+ # Headline: <%= headline %>
+ # First name: <%= person.first_name %>
+ #
+ # == Template caching
+ #
+ # The parsing of ERb templates are cached by default, but the reading of them are not. This means that the application by default
+ # will reflect changes to the templates immediatly. If you'd like to sacrifice that immediacy for the speed gain given by also
+ # caching the loading of templates (reading from the file systen), you can turn that on with
+ # <tt>ActionView::Base.cache_template_loading = true</tt>.
+ #
+ # == Builder
+ #
+ # Builder templates are a more programatic alternative to ERb. They are especially useful for generating XML content. An +XmlMarkup+ object
+ # named +xml+ is automatically made available to templates with a +.rxml+ extension.
+ #
+ # Here are some basic examples:
+ #
+ # xml.em("emphasized") # => <em>emphasized</em>
+ # xml.em { xml.b("emp & bold") } # => <em><b>emph &amp; bold</b></em>
+ # xml.a("A Link", "href"=>"http://onestepback.org") # => <a href="http://onestepback.org">A Link</a>
+ # xm.target("name"=>"compile", "option"=>"fast") # => <target option="fast" name="compile"\>
+ # # NOTE: order of attributes is not specified.
+ #
+ # Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
+ #
+ # xml.div {
+ # xml.h1(@person.name)
+ # xml.p(@person.bio)
+ # }
+ #
+ # would produce something like:
+ #
+ # <div>
+ # <h1>David Heinemeier Hansson</h1>
+ # <p>A product of Danish Design during the Winter of '79...</p>
+ # </div>
+ #
+ # A full-length RSS example actually used on Basecamp:
+ #
+ # xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
+ # xml.channel do
+ # xml.title(@feed_title)
+ # xml.link(@url)
+ # xml.description "Basecamp: Recent items"
+ # xml.language "en-us"
+ # xml.ttl "40"
+ #
+ # for item in @recent_items
+ # xml.item do
+ # xml.title(item_title(item))
+ # xml.description(item_description(item)) if item_description(item)
+ # xml.pubDate(item_pubDate(item))
+ # xml.guid(@person.firm.account.url + @recent_items.url(item))
+ # xml.link(@person.firm.account.url + @recent_items.url(item))
+ #
+ # xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
+ # end
+ # end
+ # end
+ # end
+ #
+ # More builder documentation can be found at http://builder.rubyforge.org.
+ class Base
+ include ERB::Util
+
+ attr_reader :first_render
+ attr_accessor :base_path, :assigns, :template_extension
+ attr_accessor :controller
+
+ # Turn on to cache the reading of templates from the file system. Doing so means that you have to restart the server
+ # when changing templates, but that rendering will be faster.
+ @@cache_template_loading = false
+ cattr_accessor :cache_template_loading
+
+ @@compiled_erb_templates = {}
+ @@loaded_templates = {}
+
+ def self.load_helpers(helper_dir)#:nodoc:
+ Dir.foreach(helper_dir) do |helper_file|
+ next unless helper_file =~ /_helper.rb$/
+ require helper_dir + helper_file
+ helper_module_name = helper_file.capitalize.gsub(/_([a-z])/) { |m| $1.capitalize }[0..-4]
+
+ class_eval("include ActionView::Helpers::#{helper_module_name}") if Helpers.const_defined?(helper_module_name)
+ end
+ end
+
+ def self.controller_delegate(*methods)
+ methods.flatten.each do |method|
+ class_eval <<-end_eval
+ def #{method}(*args, &block)
+ controller.send(%(#{method}), *args, &block)
+ end
+ end_eval
+ end
+ end
+
+ def initialize(base_path = nil, assigns_for_first_render = {}, controller = nil)#:nodoc:
+ @base_path, @assigns = base_path, assigns_for_first_render
+ @controller = controller
+ end
+
+ # Renders the template present at <tt>template_path</tt>. If <tt>use_full_path</tt> is set to true,
+ # it's relative to the template_root, otherwise it's absolute. The hash in <tt>local_assigns</tt>
+ # is made available as local variables.
+ def render_file(template_path, use_full_path = true, local_assigns = {})
+ @first_render = template_path if @first_render.nil?
+
+ if use_full_path
+ template_extension = pick_template_extension(template_path)
+ template_file_name = full_template_path(template_path, template_extension)
+ else
+ template_file_name = template_path
+ template_extension = template_path.split(".").last
+ end
+
+ template_source = read_template_file(template_file_name)
+
+ begin
+ render_template(template_extension, template_source, local_assigns)
+ rescue Exception => e
+ if TemplateError === e
+ e.sub_template_of(template_file_name)
+ raise e
+ else
+ raise TemplateError.new(@base_path, template_file_name, @assigns, template_source, e)
+ end
+ end
+ end
+
+ # Renders the template present at <tt>template_path</tt> (relative to the template_root).
+ # The hash in <tt>local_assigns</tt> is made available as local variables.
+ def render(template_path, local_assigns = {})
+ render_file(template_path, true, local_assigns)
+ end
+
+ # Renders the +template+ which is given as a string as either rhtml or rxml depending on <tt>template_extension</tt>.
+ # The hash in <tt>local_assigns</tt> is made available as local variables.
+ def render_template(template_extension, template, local_assigns = {})
+ b = binding
+ local_assigns.each { |key, value| eval "#{key} = local_assigns[\"#{key}\"]", b }
+ @assigns.each { |key, value| instance_variable_set "@#{key}", value }
+ xml = Builder::XmlMarkup.new(:indent => 2)
+
+ send(pick_rendering_method(template_extension), template, binding)
+ end
+
+ def pick_template_extension(template_path)#:nodoc:
+ if erb_template_exists?(template_path)
+ "rhtml"
+ elsif builder_template_exists?(template_path)
+ "rxml"
+ else
+ raise ActionViewError, "No rhtml or rxml template found for #{template_path}"
+ end
+ end
+
+ def pick_rendering_method(template_extension)#:nodoc:
+ (template_extension == "rxml" ? "rxml" : "rhtml") + "_render"
+ end
+
+ def erb_template_exists?(template_path)#:nodoc:
+ template_exists?(template_path, "rhtml")
+ end
+
+ def builder_template_exists?(template_path)#:nodoc:
+ template_exists?(template_path, "rxml")
+ end
+
+ def file_exists?(template_path)#:nodoc:
+ erb_template_exists?(template_path) || builder_template_exists?(template_path)
+ end
+
+ # Returns true is the file may be rendered implicitly.
+ def file_public?(template_path)#:nodoc:
+ template_path.split("/").last[0,1] != "_"
+ end
+
+ private
+ def full_template_path(template_path, extension)
+ "#{@base_path}/#{template_path}.#{extension}"
+ end
+
+ def template_exists?(template_path, extension)
+ FileTest.exists?(full_template_path(template_path, extension))
+ end
+
+ def read_template_file(template_path)
+ unless cache_template_loading && @@loaded_templates[template_path]
+ @@loaded_templates[template_path] = File.read(template_path)
+ end
+
+ @@loaded_templates[template_path]
+ end
+
+ def rhtml_render(template, binding)
+ @@compiled_erb_templates[template] ||= ERB.new(template)
+ @@compiled_erb_templates[template].result(binding)
+ end
+
+ def rxml_render(template, binding)
+ @controller.headers["Content-Type"] ||= 'text/xml'
+ eval(template, binding)
+ end
+ end
+end
+
+require 'action_view/template_error'
diff --git a/actionpack/lib/action_view/helpers/active_record_helper.rb b/actionpack/lib/action_view/helpers/active_record_helper.rb
new file mode 100644
index 0000000000..b02b807fe1
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/active_record_helper.rb
@@ -0,0 +1,171 @@
+require 'cgi'
+require File.dirname(__FILE__) + '/form_helper'
+
+module ActionView
+ class Base
+ @@field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"fieldWithErrors\">#{html_tag}</div>" }
+ cattr_accessor :field_error_proc
+ end
+
+ module Helpers
+ # The Active Record Helper makes it easier to create forms for records kept in instance variables. The most far-reaching is the form
+ # method that creates a complete form for all the basic content types of the record (not associations or aggregations, though). This
+ # is a great of making the record quickly available for editing, but likely to prove lacklusters for a complicated real-world form.
+ # In that case, it's better to use the input method and the specialized form methods in link:classes/ActionView/Helpers/FormHelper.html
+ module ActiveRecordHelper
+ # Returns a default input tag for the type of object returned by the method. Example
+ # (title is a VARCHAR column and holds "Hello World"):
+ # input("post", "title") =>
+ # <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
+ def input(record_name, method)
+ InstanceTag.new(record_name, method, self).to_tag
+ end
+
+ # Returns an entire form with input tags and everything for a specified Active Record object. Example
+ # (post is a new record that has a title using VARCHAR and a body using TEXT):
+ # form("post") =>
+ # <form action='create' method='POST'>
+ # <p>
+ # <label for="post_title">Title</label><br />
+ # <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
+ # </p>
+ # <p>
+ # <label for="post_body">Body</label><br />
+ # <textarea cols="40" id="post_body" name="post[body]" rows="20" wrap="virtual">
+ # Back to the hill and over it again!
+ # </textarea>
+ # </p>
+ # <input type='submit' value='Create' />
+ # </form>
+ #
+ # It's possible to specialize the form builder by using a different action name and by supplying another
+ # block renderer. Example (entry is a new record that has a message attribute using VARCHAR):
+ #
+ # form("entry", :action => "sign", :input_block =>
+ # Proc.new { |record, column| "#{column.human_name}: #{input(record, column.name)}<br />" }) =>
+ #
+ # <form action='sign' method='POST'>
+ # Message:
+ # <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" /><br />
+ # <input type='submit' value='Sign' />
+ # </form>
+ def form(record_name, options = {})
+ record = instance_eval("@#{record_name}")
+ action = options[:action] || (record.new_record? ? "create" : "update")
+ id_field = record.new_record? ? "" : InstanceTag.new(record_name, "id", self).to_input_field_tag("hidden")
+
+ "<form action='#{action}' method='POST'>" +
+ id_field + all_input_tags(record, record_name, options) +
+ "<input type='submit' value='#{action.gsub(/[^A-Za-z]/, "").capitalize}' />" +
+ "</form>"
+ end
+
+ # Returns a string containing the error message attached to the +method+ on the +object+, if one exists.
+ # This error message is wrapped in a DIV tag, which can be specialized to include both a +prepend_text+ and +append_text+
+ # to properly introduce the error and a +css_class+ to style it accordingly. Examples (post has an error message
+ # "can't be empty" on the title attribute):
+ #
+ # <%= error_message_on "post", "title" %> =>
+ # <div class="formError">can't be empty</div>
+ #
+ # <%= 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_eval("@#{object}").errors.on(method)
+ "<div class=\"#{css_class}\">#{prepend_text + (errors.is_a?(Array) ? errors.first : errors) + append_text}</div>"
+ end
+ end
+
+ def error_messages_for(object_name)
+ object = instance_eval("@#{object_name}")
+ unless object.errors.empty?
+ "<div id=\"errorExplanation\">" +
+ "<h2>#{object.errors.count} error#{"s" unless object.errors.count == 1} prohibited this #{object_name.gsub("_", " ")} from being saved</h2>" +
+ "<p>There were problems with the following fields (marked in red below):</p>" +
+ "<ul>#{object.errors.full_messages.collect { |msg| "<li>#{msg}</li>"}}</ul>" +
+ "</div>"
+ end
+ end
+
+ private
+ def all_input_tags(record, record_name, options)
+ input_block = options[:input_block] || default_input_block
+ record.class.content_columns.collect{ |column| input_block.call(record_name, column) }.join("\n")
+ end
+
+ def default_input_block
+ Proc.new { |record, column| "<p><label for=\"#{record}_#{column.name}\">#{column.human_name}</label><br />#{input(record, column.name)}</p>" }
+ end
+ end
+
+ class InstanceTag #:nodoc:
+ def to_tag(options = {})
+ case column_type
+ when :string
+ field_type = @method_name.include?("password") ? "password" : "text"
+ to_input_field_tag(field_type, options)
+ when :text
+ to_text_area_tag(options)
+ when :integer, :float
+ to_input_field_tag("text", options)
+ when :date
+ to_date_select_tag(options)
+ when :datetime
+ to_datetime_select_tag(options)
+ when :boolean
+ to_boolean_select_tag(options)
+ end
+ end
+
+ alias_method :tag_without_error_wrapping, :tag
+
+ def tag(name, options)
+ if object.respond_to?("errors") && object.errors.respond_to?("on")
+ error_wrapping(tag_without_error_wrapping(name, options), object.errors.on(@method_name))
+ else
+ tag_without_error_wrapping(name, options)
+ end
+ end
+
+ alias_method :content_tag_without_error_wrapping, :content_tag
+
+ def content_tag(name, value, options)
+ if object.respond_to?("errors") && object.errors.respond_to?("on")
+ error_wrapping(content_tag_without_error_wrapping(name, value, options), object.errors.on(@method_name))
+ else
+ content_tag_without_error_wrapping(name, value, options)
+ end
+ end
+
+ alias_method :to_date_select_tag_without_error_wrapping, :to_date_select_tag
+ def to_date_select_tag(options = {})
+ if object.respond_to?("errors") && object.errors.respond_to?("on")
+ error_wrapping(to_date_select_tag_without_error_wrapping(options), object.errors.on(@method_name))
+ else
+ to_date_select_tag_without_error_wrapping(options)
+ end
+ end
+
+ alias_method :to_datetime_select_tag_without_error_wrapping, :to_datetime_select_tag
+ def to_datetime_select_tag(options = {})
+ if object.respond_to?("errors") && object.errors.respond_to?("on")
+ error_wrapping(to_datetime_select_tag_without_error_wrapping(options), object.errors.on(@method_name))
+ else
+ to_datetime_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
+
+ def error_message
+ object.errors.on(@method_name)
+ end
+
+ def column_type
+ object.send("column_for_attribute", @method_name).type
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb
new file mode 100755
index 0000000000..5526c3eef4
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/date_helper.rb
@@ -0,0 +1,230 @@
+require "date"
+
+module ActionView
+ module Helpers
+ # The Date Helper primarily creates select/option tags for different kinds of dates and date elements. All of the select-type methods
+ # share a number of common options that are as follows:
+ #
+ # * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday" would give
+ # birthday[month] instead of date[month] if passed to the select_month method.
+ # * <tt>:include_blank</tt> - set to true if it should be possible to set an empty date.
+ # * <tt>:discard_type</tt> - set to true if you want to discard the type part of the select name. If set to true, the select_month
+ # method would use simply "date" (which can be overwritten using <tt>:prefix</tt>) instead of "date[month]".
+ module DateHelper
+ DEFAULT_PREFIX = "date" unless const_defined?("DEFAULT_PREFIX")
+
+ # Reports the approximate distance in time between to Time objects. For example, if the distance is 47 minutes, it'll return
+ # "about 1 hour". See the source for the complete wording list.
+ def distance_of_time_in_words(from_time, to_time)
+ distance_in_minutes = ((to_time - from_time) / 60).round
+
+ case distance_in_minutes
+ when 0 then "less than a minute"
+ when 1 then "1 minute"
+ when 2..45 then "#{distance_in_minutes} minutes"
+ when 46..90 then "about 1 hour"
+ when 90..1440 then "about #{(distance_in_minutes.to_f / 60.0).round} hours"
+ when 1441..2880 then "1 day"
+ else "#{(distance_in_minutes / 1440).round} days"
+ end
+ end
+
+ # Like distance_of_time_in_words, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.
+ def distance_of_time_in_words_to_now(from_time)
+ distance_of_time_in_words(from_time, Time.now)
+ end
+
+ # Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute (identified by
+ # +method+) on an object assigned to the template (identified by +object+). It's possible to tailor the selects through the +options+ hash,
+ # which both accepts all the keys that each of the individual select builders does (like :use_month_numbers for select_month) and a range
+ # of discard options. The discard options are <tt>:discard_month</tt> and <tt>:discard_day</tt>. Set to true, they'll drop the respective
+ # select. Discarding the month select will also automatically discard the day select.
+ #
+ # NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed. Additionally, you can get the
+ # month select before the year by setting :month_before_year to true in the options. This is especially useful for credit card forms.
+ # Examples:
+ #
+ # date_select("post", "written_on")
+ # date_select("post", "written_on", :start_year => 1995)
+ # date_select("post", "written_on", :start_year => 1995, :use_month_numbers => true,
+ # :discard_day => true, :include_blank => true)
+ #
+ # The selects are prepared for multi-parameter assignment to an Active Record object.
+ def date_select(object, method, options = {})
+ InstanceTag.new(object, method, self).to_date_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:
+ #
+ # datetime_select("post", "written_on")
+ # datetime_select("post", "written_on", :start_year => 1995)
+ #
+ # The selects are prepared for multi-parameter assignment to an Active Record object.
+ def datetime_select(object, method, options = {})
+ InstanceTag.new(object, method, self).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) preselected 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)
+ end
+
+ # Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
+ # The <tt>minute</tt> can also be substituted for a minute number.
+ def select_minute(datetime, options = {})
+ minute_options = []
+
+ 0.upto(59) do |minute|
+ minute_options << ((datetime.kind_of?(Fixnum) ? datetime : datetime.min) == minute ?
+ "<option selected=\"selected\">#{leading_zero_on_single_digits(minute)}</option>\n" :
+ "<option>#{leading_zero_on_single_digits(minute)}</option>\n"
+ )
+ end
+
+ select_html("minute", minute_options, options[:prefix], options[:include_blank], options[:discard_type])
+ 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.
+ def select_hour(datetime, options = {})
+ hour_options = []
+
+ 0.upto(23) do |hour|
+ hour_options << ((datetime.kind_of?(Fixnum) ? datetime : datetime.hour) == hour ?
+ "<option selected=\"selected\">#{leading_zero_on_single_digits(hour)}</option>\n" :
+ "<option>#{leading_zero_on_single_digits(hour)}</option>\n"
+ )
+ end
+
+ select_html("hour", hour_options, options[:prefix], options[:include_blank], options[:discard_type])
+ 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.
+ def select_day(date, options = {})
+ day_options = []
+
+ 1.upto(31) do |day|
+ day_options << ((date.kind_of?(Fixnum) ? date : date.day) == day ?
+ "<option selected=\"selected\">#{day}</option>\n" :
+ "<option>#{day}</option>\n"
+ )
+ end
+
+ select_html("day", day_options, options[:prefix], options[:include_blank], options[:discard_type])
+ 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:
+ #
+ # 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"
+ def select_month(date, options = {})
+ month_options = []
+
+ 1.upto(12) do |month_number|
+ month_name = if options[:use_month_numbers]
+ month_number
+ elsif options[:add_month_numbers]
+ month_number.to_s + " - " + Date::MONTHNAMES[month_number]
+ else
+ Date::MONTHNAMES[month_number]
+ end
+
+ month_options << ((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"
+ )
+ end
+
+ select_html("month", month_options, options[:prefix], options[:include_blank], options[:discard_type])
+ 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
+ # can be changed using the <tt>:start_year</tt> and <tt>:end_year</tt> keys in the +options+. The <tt>date</tt> can also be substituted
+ # for a year given as a number. Example:
+ #
+ # select_year(Date.today, :start_year => 1992, :end_year => 2007)
+ def select_year(date, options = {})
+ year_options = []
+ unless date.kind_of?(Fixnum) then default_start_year, default_end_year = date.year - 5, date.year + 5 end
+
+ (options[:start_year] || default_start_year).upto(options[:end_year] || default_end_year) do |year|
+ year_options << ((date.kind_of?(Fixnum) ? date : date.year) == year ?
+ "<option selected=\"selected\">#{year}</option>\n" :
+ "<option>#{year}</option>\n"
+ )
+ end
+
+ select_html("year", year_options, options[:prefix], options[:include_blank], options[:discard_type])
+ end
+
+ private
+ def select_html(type, options, prefix = nil, include_blank = false, discard_type = false)
+ select_html = "<select name='#{prefix || DEFAULT_PREFIX}"
+ select_html << "[#{type}]" unless discard_type
+ select_html << "'>\n"
+ select_html << "<option></option>\n" if include_blank
+ select_html << options.to_s
+ select_html << "</select>\n"
+
+ return select_html
+ end
+
+ def leading_zero_on_single_digits(number)
+ number > 9 ? number : "0#{number}"
+ end
+ end
+
+ class InstanceTag #:nodoc:
+ include DateHelper
+
+ def to_date_select_tag(options = {})
+ defaults = { :discard_type => true }
+ options = defaults.merge(options)
+ options_with_prefix = Proc.new { |position| options.update({ :prefix => "#{@object_name}[#{@method_name}(#{position}i)]" }) }
+ date = options[:include_blank] ? (value || 0) : (value || Date.today)
+
+ date_select = ""
+
+ if options[:month_before_year]
+ date_select << select_month(date, options_with_prefix.call(2)) unless options[:discard_month]
+ date_select << select_year(date, options_with_prefix.call(1))
+ else
+ date_select << select_year(date, options_with_prefix.call(1))
+ date_select << select_month(date, options_with_prefix.call(2)) unless options[:discard_month]
+ end
+
+ date_select << select_day(date, options_with_prefix.call(3)) unless options[:discard_day] || options[:discard_month]
+
+ return date_select
+ end
+
+ def to_datetime_select_tag(options = {})
+ defaults = { :discard_type => true }
+ options = defaults.merge(options)
+ options_with_prefix = Proc.new { |position| options.update({ :prefix => "#{@object_name}[#{@method_name}(#{position}i)]" }) }
+ datetime = options[:include_blank] ? (value || 0) : (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 << " &mdash; " + 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]
+
+ return datetime_select
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/debug_helper.rb b/actionpack/lib/action_view/helpers/debug_helper.rb
new file mode 100644
index 0000000000..8baea6f450
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/debug_helper.rb
@@ -0,0 +1,17 @@
+module ActionView
+ module Helpers
+ # Provides a set of methods for making it easier to locate problems.
+ module DebugHelper
+ # Returns a <pre>-tag set with the +object+ dumped by YAML. Very readable way to inspect an object.
+ def debug(object)
+ begin
+ Marshal::dump(object)
+ "<pre class='debug_dump'>#{h(object.to_yaml).gsub(" ", "&nbsp; ")}</pre>"
+ rescue Object => e
+ # Object couldn't be dumped, perhaps because of singleton methods -- this is the fallback
+ "<code class='debug_dump'>#{h(object.inspect)}</code>"
+ end
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
new file mode 100644
index 0000000000..389aa302a9
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -0,0 +1,182 @@
+require 'cgi'
+require File.dirname(__FILE__) + '/date_helper'
+require File.dirname(__FILE__) + '/tag_helper'
+
+module ActionView
+ module Helpers
+ # Provides a set of methods for working with forms and especially forms related to objects assigned to the template.
+ # The following is an example of a complete form for a person object that works for both creates and updates built
+ # with all the form helpers. The <tt>@person</tt> object was assigned by an action on the controller:
+ # <form action="save_person" method="post">
+ # Name:
+ # <%= text_field "person", "name", "size" => 20 %>
+ #
+ # Password:
+ # <%= password_field "person", "password", "maxsize" => 20 %>
+ #
+ # Single?:
+ # <%= check_box "person", "single" %>
+ #
+ # Description:
+ # <%= text_area "person", "description", "cols" => 20 %>
+ #
+ # <input type="submit" value="Save">
+ # </form>
+ #
+ # ...is compiled to:
+ #
+ # <form action="save_person" method="post">
+ # Name:
+ # <input type="text" id="person_name" name="person[name]"
+ # size="20" value="<%= @person.name %>" />
+ #
+ # Password:
+ # <input type="password" id="person_password" name="person[password]"
+ # size="20" maxsize="20" value="<%= @person.password %>" />
+ #
+ # Single?:
+ # <input type="checkbox" id="person_single" name="person[single] value="1" />
+ #
+ # Description:
+ # <textarea cols="20" rows="40" id="person_description" name="person[description]">
+ # <%= @person.description %>
+ # </textarea>
+ #
+ # <input type="submit" value="Save">
+ # </form>
+ #
+ # There's also methods for helping to build form tags in link:classes/ActionView/Helpers/FormOptionsHelper.html,
+ # link:classes/ActionView/Helpers/DateHelper.html, and link:classes/ActionView/Helpers/ActiveRecordHelper.html
+ module FormHelper
+ # Returns an input tag of the "text" type tailored for accessing a specified attribute (identified by +method+) on an object
+ # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
+ # hash with +options+.
+ #
+ # Examples (call, result):
+ # text_field("post", "title", "size" => 20)
+ # <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" />
+ def text_field(object, method, options = {})
+ InstanceTag.new(object, method, self).to_input_field_tag("text", options)
+ end
+
+ # Works just like text_field, but returns a input tag of the "password" type instead.
+ def password_field(object, method, options = {})
+ InstanceTag.new(object, method, self).to_input_field_tag("password", options)
+ end
+
+ # Works just like text_field, but returns a input tag of the "hidden" type instead.
+ def hidden_field(object, method, options = {})
+ InstanceTag.new(object, method, self).to_input_field_tag("hidden", options)
+ end
+
+ # Returns a textarea opening and closing tag set tailored for accessing a specified attribute (identified by +method+)
+ # on an object assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
+ # hash with +options+.
+ #
+ # Example (call, result):
+ # text_area("post", "body", "cols" => 20, "rows" => 40)
+ # <textarea cols="20" rows="40" id="post_body" name="post[body]">
+ # #{@post.body}
+ # </textarea>
+ def text_area(object, method, options = {})
+ InstanceTag.new(object, method, self).to_text_area_tag(options)
+ end
+
+ # Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object
+ # assigned to the template (identified by +object+). It's intended that +method+ returns an integer and if that
+ # integer is above zero, then the checkbox is checked. Additional options on the input tag can be passed as a
+ # hash with +options+. The +checked_value+ defaults to 1 while the default +unchecked_value+
+ # is set to 0 which is convenient for boolean values. Usually unchecked checkboxes don't post anything.
+ # We work around this problem by adding a hidden value with the same name as the checkbox.
+ #
+ # Example (call, result). Imagine that @post.validated? returns 1:
+ # check_box("post", "validated")
+ # <input type="checkbox" id="post_validate" name="post[validated] value="1" checked="checked" /><input name="post[validated]" type="hidden" value="0" />
+ #
+ # Example (call, result). Imagine that @puppy.gooddog returns no:
+ # check_box("puppy", "gooddog", {}, "yes", "no")
+ # <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog] value="yes" /><input name="puppy[gooddog]" type="hidden" value="no" />
+ def check_box(object, method, options = {}, checked_value = "1", unchecked_value = "0")
+ InstanceTag.new(object, method, self).to_check_box_tag(options, checked_value, unchecked_value)
+ end
+ end
+
+ class InstanceTag #:nodoc:
+ include Helpers::TagHelper
+
+ attr_reader :method_name, :object_name
+
+ DEFAULT_FIELD_OPTIONS = { "size" => 30 } unless const_defined?("DEFAULT_FIELD_OPTIONS")
+ DEFAULT_TEXT_AREA_OPTIONS = { "wrap" => "virtual", "cols" => 40, "rows" => 20 } unless const_defined?("DEFAULT_TEXT_AREA_OPTIONS")
+
+ def initialize(object_name, method_name, template_object, local_binding = nil)
+ @object_name, @method_name = object_name, method_name
+ @template_object, @local_binding = template_object, local_binding
+ end
+
+ def to_input_field_tag(field_type, options = {})
+ html_options = DEFAULT_FIELD_OPTIONS.merge(options)
+ html_options.merge!({ "size" => options["maxlength"]}) if options["maxlength"] && !options["size"]
+ html_options.merge!({ "type" => field_type, "value" => value.to_s })
+ add_default_name_and_id(html_options)
+ tag("input", html_options)
+ end
+
+ def to_text_area_tag(options = {})
+ options = DEFAULT_TEXT_AREA_OPTIONS.merge(options)
+ add_default_name_and_id(options)
+ content_tag("textarea", html_escape(value), options)
+ end
+
+ def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0")
+ options.merge!({"checked" => "checked"}) if !value.nil? && ((value.is_a?(TrueClass) || value.is_a?(FalseClass)) ? value : value.to_i > 0)
+ options.merge!({ "type" => "checkbox", "value" => checked_value })
+ add_default_name_and_id(options)
+ tag("input", options) << tag("input", ({ "name" => options['name'], "type" => "hidden", "value" => unchecked_value }))
+ end
+
+ def to_date_tag()
+ defaults = { "discard_type" => true }
+ date = value || Date.today
+ options = Proc.new { |position| defaults.update({ :prefix => "#{@object_name}[#{@method_name}(#{position}i)]" }) }
+
+ html_day_select(date, options.call(3)) +
+ html_month_select(date, options.call(2)) +
+ html_year_select(date, options.call(1))
+ end
+
+ def to_boolean_select_tag(options = {})
+ add_default_name_and_id(options)
+ tag_text = "<select"
+ tag_text << tag_options(options)
+ tag_text << "><option value=\"false\""
+ tag_text << " selected" if value == false
+ tag_text << ">False</option><option value=\"true\""
+ tag_text << " selected" if value
+ tag_text << ">True</option></select>"
+ end
+
+ def object
+ @template_object.instance_variable_get "@#{@object_name}"
+ end
+
+ def value
+ object.send(@method_name) unless object.nil?
+ end
+
+ private
+ def add_default_name_and_id(options)
+ options['name'] = tag_name unless options.has_key? "name"
+ options['id'] = tag_id unless options.has_key? "id"
+ end
+
+ def tag_name
+ "#{@object_name}[#{@method_name}]"
+ end
+
+ def tag_id
+ "#{@object_name}_#{@method_name}"
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb
new file mode 100644
index 0000000000..ca3798ede6
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/form_options_helper.rb
@@ -0,0 +1,212 @@
+require 'cgi'
+require 'erb'
+require File.dirname(__FILE__) + '/form_helper'
+
+module ActionView
+ module Helpers
+ # Provides a number of methods for turning different kinds of containers into a set of option tags. Neither of the methods provide
+ # the actual select tag, so you'll need to construct that in HTML manually.
+ module FormOptionsHelper
+ include ERB::Util
+
+ def select(object, method, choices, options = {}, html_options = {})
+ InstanceTag.new(object, method, self).to_select_tag(choices, options, html_options)
+ end
+
+ def collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
+ InstanceTag.new(object, method, self).to_collection_select_tag(collection, value_method, text_method, options, html_options)
+ end
+
+ def country_select(object, method, priority_countries = nil, options = {}, html_options = {})
+ InstanceTag.new(object, method, self).to_country_select_tag(priority_countries, options, html_options)
+ end
+
+ # Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. Given a container
+ # where the elements respond to first and last (such as a two-element array), the "lasts" serve as option values and
+ # the "firsts" as option text. Hashes are turned into this form automatically, so the keys become "firsts" and values
+ # become lasts. If +selected+ is specified, the matching "last" or element will get the selected option-tag. +Selected+
+ # may also be an array of values to be selected when using a multiple select.
+ #
+ # Examples (call, result):
+ # options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
+ # <option value="$">Dollar</option>\n<option value="DKK">Kroner</option>
+ #
+ # options_for_select([ "VISA", "Mastercard" ], "Mastercard")
+ # <option>VISA</option>\n<option selected="selected">Mastercard</option>
+ #
+ # options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40")
+ # <option value="$20">Basic</option>\n<option value="$40" selected="selected">Plus</option>
+ #
+ # options_for_select([ "VISA", "Mastercard", "Discover" ], ["VISA", "Discover"])
+ # <option selected="selected">VISA</option>\n<option>Mastercard</option>\n<option selected="selected">Discover</option>
+ def options_for_select(container, selected = nil)
+ container = container.to_a if Hash === container
+
+ options_for_select = container.inject([]) do |options, element|
+ if element.respond_to?(:first) && element.respond_to?(:last)
+ is_selected = ( (selected.respond_to?(:include?) ? selected.include?(element.last) : element.last == selected) )
+ if is_selected
+ options << "<option value=\"#{html_escape(element.last.to_s)}\" selected=\"selected\">#{html_escape(element.first.to_s)}</option>"
+ else
+ options << "<option value=\"#{html_escape(element.last.to_s)}\">#{html_escape(element.first.to_s)}</option>"
+ end
+ else
+ is_selected = ( (selected.respond_to?(:include?) ? selected.include?(element) : element == selected) )
+ options << ((is_selected) ? "<option selected=\"selected\">#{html_escape(element.to_s)}</option>" : "<option>#{html_escape(element.to_s)}</option>")
+ end
+ end
+
+ options_for_select.join("\n")
+ end
+
+ # Returns a string of option tags that has been compiled by iterating over the +collection+ and assigning the
+ # the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
+ # If +selected_value+ is specified, the element returning a match on +value_method+ will get the selected option tag.
+ #
+ # Example (call, result). Imagine a loop iterating over each +person+ in <tt>@project.people</tt> to generate a input tag:
+ # options_from_collection_for_select(@project.people, "id", "name")
+ # <option value="#{person.id}">#{person.name}</option>
+ def options_from_collection_for_select(collection, value_method, text_method, selected_value = nil)
+ options_for_select(
+ collection.inject([]) { |options, object| options << [ object.send(text_method), object.send(value_method) ] },
+ selected_value
+ )
+ end
+
+ # Returns a string of option tags, like options_from_collection_for_select, but surrounds them by <optgroup> tags.
+ #
+ # An array of group objects are passed. Each group should return an array of options when calling group_method
+ # Each group should should return its name when calling group_label_method.
+ #
+ # html_option_groups_from_collection(@continents, "countries", "contient_name", "country_id", "country_name", @selected_country.id)
+ #
+ # Could become:
+ # <optgroup label="Africa">
+ # <select>Egypt</select>
+ # <select>Rwanda</select>
+ # ...
+ # </optgroup>
+ # <optgroup label="Asia">
+ # <select>China</select>
+ # <select>India</select>
+ # <select>Japan</select>
+ # ...
+ # </optgroup>
+ #
+ # with objects of the following classes:
+ # class Continent
+ # def initialize(p_name, p_countries) @continent_name = p_name; @countries = p_countries; end
+ # def continent_name() @continent_name; end
+ # def countries() @countries; end
+ # end
+ # class Country
+ # def initialize(id, name) @id = id; @name = name end
+ # def country_id() @id; end
+ # def country_name() @name; end
+ # end
+ def option_groups_from_collection_for_select(collection, group_method, group_label_method,
+ option_key_method, option_value_method, selected_key = nil)
+ collection.inject("") do |options_for_select, group|
+ group_label_string = eval("group.#{group_label_method}")
+ options_for_select += "<optgroup label=\"#{html_escape(group_label_string)}\">"
+ options_for_select += options_from_collection_for_select(eval("group.#{group_method}"), option_key_method, option_value_method, selected_key)
+ options_for_select += '</optgroup>'
+ end
+ end
+
+ # Returns a string of option tags for pretty much any country in the world. Supply a country name as +selected+ to
+ # have it marked as the selected option tag. You can also supply an array of countries as +priority_countries+, so
+ # that they will be listed above the rest of the (long) list.
+ def country_options_for_select(selected = nil, priority_countries = nil)
+ country_options = ""
+
+ if priority_countries
+ country_options += options_for_select(priority_countries, selected)
+ country_options += "<option>-------------</option>\n"
+ end
+
+ if priority_countries && priority_countries.include?(selected)
+ country_options += options_for_select(COUNTRIES - priority_countries, selected)
+ else
+ country_options += options_for_select(COUNTRIES, selected)
+ end
+
+ return country_options
+ end
+
+
+ private
+ # All the countries included in the country_options output.
+ COUNTRIES = [ "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla",
+ "Antarctica", "Antigua And Barbuda", "Argentina", "Armenia", "Aruba", "Australia",
+ "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus",
+ "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegowina",
+ "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
+ "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burma", "Burundi", "Cambodia",
+ "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic",
+ "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia",
+ "Comoros", "Congo", "Congo, the Democratic Republic of the", "Cook Islands",
+ "Costa Rica", "Cote d'Ivoire", "Croatia", "Cyprus", "Czech Republic", "Denmark",
+ "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt",
+ "El Salvador", "England", "Equatorial Guinea", "Eritrea", "Espana", "Estonia",
+ "Ethiopia", "Falkland Islands", "Faroe Islands", "Fiji", "Finland", "France",
+ "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia",
+ "Georgia", "Germany", "Ghana", "Gibraltar", "Great Britain", "Greece", "Greenland",
+ "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana",
+ "Haiti", "Heard and Mc Donald Islands", "Honduras", "Hong Kong", "Hungary", "Iceland",
+ "India", "Indonesia", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan",
+ "Kazakhstan", "Kenya", "Kiribati", "Korea, Republic of", "Korea (South)", "Kuwait",
+ "Kyrgyzstan", "Lao People's Democratic Republic", "Latvia", "Lebanon", "Lesotho",
+ "Liberia", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia",
+ "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
+ "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico",
+ "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia",
+ "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal",
+ "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua",
+ "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Ireland",
+ "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Panama",
+ "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland",
+ "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russia", "Rwanda",
+ "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines",
+ "Samoa (Independent)", "San Marino", "Sao Tome and Principe", "Saudi Arabia",
+ "Scotland", "Senegal", "Seychelles", "Sierra Leone", "Singapore", "Slovakia",
+ "Slovenia", "Solomon Islands", "Somalia", "South Africa",
+ "South Georgia and the South Sandwich Islands", "South Korea", "Spain", "Sri Lanka",
+ "St. Helena", "St. Pierre and Miquelon", "Suriname", "Svalbard and Jan Mayen Islands",
+ "Swaziland", "Sweden", "Switzerland", "Taiwan", "Tajikistan", "Tanzania", "Thailand",
+ "Togo", "Tokelau", "Tonga", "Trinidad", "Trinidad and Tobago", "Tunisia", "Turkey",
+ "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine",
+ "United Arab Emirates", "United Kingdom", "United States",
+ "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu",
+ "Vatican City State (Holy See)", "Venezuela", "Viet Nam", "Virgin Islands (British)",
+ "Virgin Islands (U.S.)", "Wales", "Wallis and Futuna Islands", "Western Sahara",
+ "Yemen", "Zambia", "Zimbabwe" ] unless const_defined?("COUNTRIES")
+ end
+
+ class InstanceTag #:nodoc:
+ include FormOptionsHelper
+
+ def to_select_tag(choices, options, html_options)
+ add_default_name_and_id(html_options)
+ content_tag("select", add_blank_option(options_for_select(choices, value), options[:include_blank]), html_options)
+ end
+
+ def to_collection_select_tag(collection, value_method, text_method, options, html_options)
+ add_default_name_and_id(html_options)
+ content_tag(
+ "select", add_blank_option(options_from_collection_for_select(collection, value_method, text_method, value), options[:include_blank]), html_options
+ )
+ end
+
+ def to_country_select_tag(priority_countries, options, html_options)
+ add_default_name_and_id(html_options)
+ content_tag("select", add_blank_option(country_options_for_select(value, priority_countries), options[:include_blank]), html_options)
+ end
+
+ private
+ def add_blank_option(option_tags, add_blank)
+ add_blank ? "<option></option>\n" + option_tags : option_tags
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb
new file mode 100644
index 0000000000..90084c7a8d
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tag_helper.rb
@@ -0,0 +1,59 @@
+require 'cgi'
+
+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 TagHelper
+ include ERB::Util
+
+ # Examples:
+ # * tag("br") => <br />
+ # * tag("input", { "type" => "text"}) => <input type="text" />
+ def tag(name, options = {}, open = false)
+ "<#{name + tag_options(options)}" + (open ? ">" : " />")
+ end
+
+ # Examples:
+ # * 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>
+ def content_tag(name, content, options = {})
+ "<#{name + tag_options(options)}>#{content}</#{name}>"
+ end
+
+ # Starts a form tag that points the action to an url configured with <tt>url_for_options</tt> just like
+ # ActionController::Base#url_for.
+ def form_tag(url_for_options, options = {}, *parameters_for_url)
+ html_options = { "method" => "POST" }.merge(options)
+
+ if html_options[:multipart]
+ html_options["enctype"] = "multipart/form-data"
+ html_options.delete(:multipart)
+ end
+
+ html_options["action"] = url_for(url_for_options, *parameters_for_url)
+
+ tag("form", html_options, true)
+ end
+
+ alias_method :start_form_tag, :form_tag
+
+ # Outputs "</form>"
+ def end_form_tag
+ "</form>"
+ end
+
+
+ private
+ def tag_options(options)
+ if options.empty?
+ ""
+ else
+ " " + options.collect { |pair|
+ "#{pair.first}=\"#{html_escape(pair.last)}\""
+ }.sort.join(" ")
+ end
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb
new file mode 100644
index 0000000000..7e05e468b8
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/text_helper.rb
@@ -0,0 +1,111 @@
+module ActionView
+ module Helpers #:nodoc:
+ # Provides a set of methods for working with text strings that can help unburden the level of inline Ruby code in the
+ # templates. In the example below we iterate over a collection of posts provided to the template and prints each title
+ # after making sure it doesn't run longer than 20 characters:
+ # <% for post in @posts %>
+ # Title: <%= truncate(post.title, 20) %>
+ # <% end %>
+ module TextHelper
+ # The regular puts and print are outlawed in eRuby. It's recommended to use the <%= "hello" %> form instead of print "hello".
+ # If you absolutely must use a method-based output, you can use concat. It's use like this <% concat "hello", binding %>. Notice that
+ # it doesn't have an equal sign in front. Using <%= concat "hello" %> would result in a double hello.
+ def concat(string, binding)
+ eval("_erbout", binding).concat(string)
+ end
+
+ # Truncates +text+ to the length of +length+ and replaces the last three characters with the +truncate_string+
+ # if the +text+ is longer than +length+.
+ def truncate(text, length = 30, truncate_string = "...")
+ if text.nil? then return end
+ if text.length > length then text[0..(length - 3)] + truncate_string else text end
+ end
+
+ # Highlights the +phrase+ where it is found in the +text+ by surrounding it like
+ # <strong class="highlight">I'm a highlight phrase</strong>. The highlighter can be specialized by
+ # passing +highlighter+ as single-quoted string with \1 where the phrase is supposed to be inserted.
+ # N.B.: The +phrase+ is sanitized to include only letters, digits, and spaces before use.
+ def highlight(text, phrase, highlighter = '<strong class="highlight">\1</strong>')
+ if text.nil? || phrase.nil? then return end
+ text.gsub(/(#{escape_regexp(phrase)})/i, highlighter) unless text.nil?
+ end
+
+ # Extracts an excerpt from the +text+ surrounding the +phrase+ with a number of characters on each side determined
+ # by +radius+. If the phrase isn't found, nil is returned. Ex:
+ # excerpt("hello my world", "my", 3) => "...lo my wo..."
+ def excerpt(text, phrase, radius = 100, excerpt_string = "...")
+ if text.nil? || phrase.nil? then return end
+ phrase = escape_regexp(phrase)
+
+ if found_pos = text =~ /(#{phrase})/i
+ start_pos = [ found_pos - radius, 0 ].max
+ end_pos = [ found_pos + phrase.length + radius, text.length ].min
+
+ prefix = start_pos > 0 ? excerpt_string : ""
+ postfix = end_pos < text.length ? excerpt_string : ""
+
+ prefix + text[start_pos..end_pos].strip + postfix
+ else
+ nil
+ end
+ end
+
+ # Attempts to pluralize the +singular+ word unless +count+ is 1. See source for pluralization rules.
+ def pluralize(count, singular, plural = nil)
+ "#{count} " + if count == 1
+ singular
+ elsif plural
+ plural
+ elsif Object.const_defined?("Inflector")
+ Inflector.pluralize(singular)
+ else
+ singular + "s"
+ end
+ end
+
+ begin
+ require "redcloth"
+
+ # Returns the text with all the Textile codes turned into HTML-tags.
+ # <i>This method is only available if RedCloth can be required</i>.
+ def textilize(text)
+ RedCloth.new(text).to_html
+ end
+
+ # Returns the text with all the Textile codes turned into HTML-tags, but without the regular bounding <p> tag.
+ # <i>This method is only available if RedCloth can be required</i>.
+ def textilize_without_paragraph(text)
+ textiled = textilize(text)
+ if textiled[0..2] == "<p>" then textiled = textiled[3..-1] end
+ if textiled[-4..-1] == "</p>" then textiled = textiled[0..-5] end
+ return textiled
+ end
+ rescue LoadError
+ # We can't really help what's not there
+ end
+
+ begin
+ require "bluecloth"
+
+ # Returns the text with all the Markdown codes turned into HTML-tags.
+ # <i>This method is only available if BlueCloth can be required</i>.
+ def markdown(text)
+ BlueCloth.new(text).to_html
+ end
+ rescue LoadError
+ # We can't really help what's not there
+ end
+
+ # Turns all links into words, like "<a href="something">else</a>" to "else".
+ def strip_links(text)
+ text.gsub(/<a.*>(.*)<\/a>/m, '\1')
+ end
+
+ private
+ # Returns a version of the text that's safe to use in a regular expression without triggering engine features.
+ def escape_regexp(text)
+ text.gsub(/([\\|?+*\/\)\(])/) { |m| "\\#{$1}" }
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb
new file mode 100644
index 0000000000..feda33d7c1
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/url_helper.rb
@@ -0,0 +1,78 @@
+module ActionView
+ module Helpers
+ # Provides a set of methods for making easy links and getting urls that depend on the controller and action. This means that
+ # you can use the same format for links in the views that you do in the controller. The different methods are even named
+ # synchronously, so link_to uses that same url as is generated by url_for, which again is the same url used for
+ # redirection in redirect_to.
+ module UrlHelper
+ # Returns the URL for the set of +options+ provided. See the valid options in link:classes/ActionController/Base.html#M000021
+ def url_for(options = {}, *parameters_for_method_reference)
+ if Hash === options then options = { :only_path => true }.merge(options) end
+ @controller.send(:url_for, options, *parameters_for_method_reference)
+ end
+
+ # Creates a link tag of the given +name+ using an URL created by the set of +options+. See the valid options in
+ # link:classes/ActionController/Base.html#M000021. It's also possible to pass a string instead of an options hash to
+ # get a link tag that just points without consideration. The html_options have a special feature for creating javascript
+ # confirm alerts where if you pass :confirm => 'Are you sure?', the link will be guarded with a JS popup asking that question.
+ # If the user accepts, the link is processed, otherwise not.
+ def link_to(name, options = {}, html_options = {}, *parameters_for_method_reference)
+ convert_confirm_option_to_javascript!(html_options) unless html_options.nil?
+ if options.is_a?(String)
+ content_tag "a", name, (html_options || {}).merge({ "href" => options })
+ else
+ content_tag("a", name, (html_options || {}).merge({ "href" => url_for(options, *parameters_for_method_reference) }))
+ end
+ end
+
+ # Creates a link tag of the given +name+ using an URL created by the set of +options+, unless the current
+ # controller, action, and id are the same as the link's, in which case only the name is returned (or the
+ # given block is yielded, if one exists). This is useful for creating link bars where you don't want to link
+ # to the page currently being viewed.
+ def link_to_unless_current(name, options = {}, html_options = {}, *parameters_for_method_reference)
+ assume_current_url_options!(options)
+
+ if destination_equal_to_current(options)
+ block_given? ?
+ yield(name, options, html_options, *parameters_for_method_reference) :
+ html_escape(name)
+ else
+ link_to name, options, html_options, *parameters_for_method_reference
+ end
+ end
+
+ # Creates a link tag for starting an email to the specified <tt>email_address</tt>, which is also used as the name of the
+ # link unless +name+ is specified. Additional HTML options, such as class or id, can be passed in the <tt>html_options</tt> hash.
+ def mail_to(email_address, name = nil, html_options = {})
+ content_tag "a", name || email_address, html_options.merge({ "href" => "mailto:#{email_address}" })
+ end
+
+ private
+ def destination_equal_to_current(options)
+ params_without_location = @params.reject { |key, value| %w( controller action id ).include?(key) }
+
+ options[:action] == @params['action'] &&
+ options[:id] == @params['id'] &&
+ options[:controller] == @params['controller'] &&
+ (options.has_key?(:params) ? params_without_location == options[:params] : true)
+ end
+
+ def assume_current_url_options!(options)
+ if options[:controller].nil?
+ options[:controller] = @params['controller']
+ if options[:action].nil?
+ options[:action] = @params['action']
+ if options[:id].nil? then options[:id] ||= @params['id'] end
+ end
+ end
+ end
+
+ def convert_confirm_option_to_javascript!(html_options)
+ if html_options.include?(:confirm)
+ html_options["onclick"] = "return confirm('#{html_options[:confirm]}');"
+ html_options.delete(:confirm)
+ end
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/partials.rb b/actionpack/lib/action_view/partials.rb
new file mode 100644
index 0000000000..96bde4c6d3
--- /dev/null
+++ b/actionpack/lib/action_view/partials.rb
@@ -0,0 +1,64 @@
+module ActionView
+ # There's also a convenience method for rendering sub templates within the current controller that depends on a single object
+ # (we call this kind of sub templates for partials). It relies on the fact that partials should follow the naming convention of being
+ # prefixed with an underscore -- as to separate them from regular templates that could be rendered on their own. In the template for
+ # Advertiser#buy, we could have:
+ #
+ # <% for ad in @advertisements %>
+ # <%= render_partial "ad", ad %>
+ # <% end %>
+ #
+ # This would render "advertiser/_ad.rhtml" and pass the local variable +ad+ to the template for display.
+ #
+ # == Rendering a collection of partials
+ #
+ # The example of partial use describes a familar pattern where a template needs to iterate over an array and render a sub
+ # template for each of the elements. This pattern has been implemented as a single method that accepts an array and renders
+ # a partial by the same name as the elements contained within. So the three-lined example in "Using partials" can be rewritten
+ # with a single line:
+ #
+ # <%= render_collection_of_partials "ad", @advertisements %>
+ #
+ # This will render "advertiser/_ad.rhtml" and pass the local variable +ad+ to the template for display. An iteration counter
+ # will automatically be made available to the template with a name of the form +partial_name_counter+. In the case of the
+ # example above, the template would be fed +ad_counter+.
+ #
+ # == Rendering shared partials
+ #
+ # Two controllers can share a set of partials and render them like this:
+ #
+ # <%= render_partial "advertisement/ad", ad %>
+ #
+ # This will render the partial "advertisement/_ad.rhtml" regardless of which controller this is being called from.
+ module Partials
+ def render_partial(partial_path, object = nil, local_assigns = {})
+ path, partial_name = partial_pieces(partial_path)
+ object ||= controller.instance_variable_get("@#{partial_name}")
+ render("#{path}/_#{partial_name}", { partial_name => object }.merge(local_assigns))
+ end
+
+ def render_collection_of_partials(partial_name, collection, partial_spacer_template = nil)
+ collection_of_partials = Array.new
+ collection.each_with_index do |element, counter|
+ collection_of_partials.push(render_partial(partial_name, element, "#{partial_name.split("/").last}_counter" => counter))
+ end
+
+ return nil if collection_of_partials.empty?
+ if partial_spacer_template
+ spacer_path, spacer_name = partial_pieces(partial_spacer_template)
+ collection_of_partials.join(render("#{spacer_path}/_#{spacer_name}"))
+ else
+ collection_of_partials
+ end
+ end
+
+ private
+ def partial_pieces(partial_path)
+ if partial_path.include?('/')
+ return File.dirname(partial_path), File.basename(partial_path)
+ else
+ return controller.send(:controller_name), partial_path
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/template_error.rb b/actionpack/lib/action_view/template_error.rb
new file mode 100644
index 0000000000..ab05b3303f
--- /dev/null
+++ b/actionpack/lib/action_view/template_error.rb
@@ -0,0 +1,84 @@
+module ActionView
+ # The TemplateError exception is raised when the compilation of the template fails. This exception then gathers a
+ # bunch of intimate details and uses it to report a very precise exception message.
+ class TemplateError < ActionViewError #:nodoc:
+ SOURCE_CODE_RADIUS = 3
+
+ attr_reader :original_exception
+
+ def initialize(base_path, file_name, assigns, source, original_exception)
+ @base_path, @file_name, @assigns, @source, @original_exception =
+ base_path, file_name, assigns, source, original_exception
+ end
+
+ def message
+ if original_exception.message.include?("(eval):")
+ original_exception.message.scan(/\(eval\):(?:[0-9]*):in `.*'(.*)/).first.first
+ else
+ original_exception.message
+ end
+ end
+
+ def sub_template_message
+ if @sub_templates
+ "Trace of template inclusion: " +
+ @sub_templates.collect { |template| strip_base_path(template) }.join(", ")
+ else
+ ""
+ end
+ end
+
+ def source_extract
+ 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
+
+ line_counter = start_on_line
+ extract = source_code[start_on_line..end_on_line].collect do |line|
+ line_counter += 1
+ "#{line_counter}: " + line
+ end
+
+ extract.join
+ end
+
+ def sub_template_of(file_name)
+ @sub_templates ||= []
+ @sub_templates << file_name
+ end
+
+ def line_number
+ begin
+ @original_exception.backtrace.join.scan(/\((?:erb)\):([0-9]*)/).first.first.to_i
+ rescue
+ begin
+ original_exception.message.scan(/\((?:eval)\):([0-9]*)/).first.first.to_i
+ rescue
+ 1
+ end
+ end
+ end
+
+ def file_name
+ strip_base_path(@file_name)
+ end
+
+ def to_s
+ "\n\n#{self.class} (#{message}) on line ##{line_number} of #{file_name}:\n" +
+ source_extract + "\n " +
+ clean_backtrace(original_exception).join("\n ") +
+ "\n\n"
+ end
+
+ private
+ def strip_base_path(file_name)
+ file_name.gsub(@base_path, "")
+ end
+
+ def clean_backtrace(exception)
+ base_dir = File.expand_path(File.dirname(__FILE__) + "/../../../../")
+ exception.backtrace.collect { |line| line.gsub(base_dir, "").gsub("/public/../config/environments/../../", "").gsub("/public/../", "") }
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/vendor/builder.rb b/actionpack/lib/action_view/vendor/builder.rb
new file mode 100644
index 0000000000..9719277669
--- /dev/null
+++ b/actionpack/lib/action_view/vendor/builder.rb
@@ -0,0 +1,13 @@
+#!/usr/bin/env ruby
+
+#--
+# Copyright 2004 by Jim Weirich (jim@weirichhouse.org).
+# All rights reserved.
+
+# Permission is granted for use, copying, modification, distribution,
+# and distribution of modified versions of this work as long as the
+# above copyright notice is included.
+#++
+
+require 'builder/xmlmarkup'
+require 'builder/xmlevents'
diff --git a/actionpack/lib/action_view/vendor/builder/blankslate.rb b/actionpack/lib/action_view/vendor/builder/blankslate.rb
new file mode 100644
index 0000000000..25307b0e56
--- /dev/null
+++ b/actionpack/lib/action_view/vendor/builder/blankslate.rb
@@ -0,0 +1,51 @@
+#!/usr/bin/env ruby
+#--
+# Copyright 2004 by Jim Weirich (jim@weirichhouse.org).
+# All rights reserved.
+
+# Permission is granted for use, copying, modification, distribution,
+# and distribution of modified versions of this work as long as the
+# above copyright notice is included.
+#++
+
+module Builder #:nodoc:
+
+ # BlankSlate provides an abstract base class with no predefined
+ # methods (except for <tt>\_\_send__</tt> and <tt>\_\_id__</tt>).
+ # BlankSlate is useful as a base class when writing classes that
+ # depend upon <tt>method_missing</tt> (e.g. dynamic proxies).
+ class BlankSlate #:nodoc:
+ class << self
+ def hide(name)
+ undef_method name unless name =~ /^(__|instance_eval)/
+ end
+ end
+
+ instance_methods.each { |m| hide(m) }
+ end
+end
+
+# Since Ruby is very dynamic, methods added to the ancestors of
+# BlankSlate <em>after BlankSlate is defined</em> will show up in the
+# list of available BlankSlate methods. We handle this by defining a hook in the Object and Kernel classes that will hide any defined
+module Kernel #:nodoc:
+ class << self
+ alias_method :blank_slate_method_added, :method_added
+ def method_added(name)
+ blank_slate_method_added(name)
+ return if self != Kernel
+ Builder::BlankSlate.hide(name)
+ end
+ end
+end
+
+class Object #:nodoc:
+ class << self
+ alias_method :blank_slate_method_added, :method_added
+ def method_added(name)
+ blank_slate_method_added(name)
+ return if self != Object
+ Builder::BlankSlate.hide(name)
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/vendor/builder/xmlbase.rb b/actionpack/lib/action_view/vendor/builder/xmlbase.rb
new file mode 100644
index 0000000000..d065d6fae1
--- /dev/null
+++ b/actionpack/lib/action_view/vendor/builder/xmlbase.rb
@@ -0,0 +1,143 @@
+#!/usr/bin/env ruby
+
+require 'builder/blankslate'
+
+module Builder #:nodoc:
+
+ # Generic error for builder
+ class IllegalBlockError < RuntimeError #:nodoc:
+ end
+
+ # XmlBase is a base class for building XML builders. See
+ # Builder::XmlMarkup and Builder::XmlEvents for examples.
+ class XmlBase < BlankSlate #:nodoc:
+
+ # Create an XML markup builder.
+ #
+ # out:: Object receiving the markup.1 +out+ must respond to
+ # <tt><<</tt>.
+ # indent:: Number of spaces used for indentation (0 implies no
+ # indentation and no line breaks).
+ # initial:: Level of initial indentation.
+ #
+ def initialize(indent=0, initial=0)
+ @indent = indent
+ @level = initial
+ end
+
+ # Create a tag named +sym+. Other than the first argument which
+ # is the tag name, the arguements are the same as the tags
+ # implemented via <tt>method_missing</tt>.
+ def tag!(sym, *args, &block)
+ self.__send__(sym, *args, &block)
+ end
+
+ # Create XML markup based on the name of the method. This method
+ # is never invoked directly, but is called for each markup method
+ # in the markup block.
+ def method_missing(sym, *args, &block)
+ text = nil
+ attrs = nil
+ sym = "#{sym}:#{args.shift}" if args.first.kind_of?(Symbol)
+ args.each do |arg|
+ case arg
+ when Hash
+ attrs ||= {}
+ attrs.merge!(arg)
+ else
+ text ||= ''
+ text << arg.to_s
+ end
+ end
+ if block
+ unless text.nil?
+ raise ArgumentError, "XmlMarkup cannot mix a text argument with a block"
+ end
+ _capture_outer_self(block) if @self.nil?
+ _indent
+ _start_tag(sym, attrs)
+ _newline
+ _nested_structures(block)
+ _indent
+ _end_tag(sym)
+ _newline
+ elsif text.nil?
+ _indent
+ _start_tag(sym, attrs, true)
+ _newline
+ else
+ _indent
+ _start_tag(sym, attrs)
+ text! text
+ _end_tag(sym)
+ _newline
+ end
+ @target
+ end
+
+ # Append text to the output target. Escape any markup. May be
+ # used within the markup brakets as:
+ #
+ # builder.p { br; text! "HI" } #=> <p><br/>HI</p>
+ def text!(text)
+ _text(_escape(text))
+ end
+
+ # Append text to the output target without escaping any markup.
+ # May be used within the markup brakets as:
+ #
+ # builder.p { |x| x << "<br/>HI" } #=> <p><br/>HI</p>
+ #
+ # This is useful when using non-builder enabled software that
+ # generates strings. Just insert the string directly into the
+ # builder without changing the inserted markup.
+ #
+ # It is also useful for stacking builder objects. Builders only
+ # use <tt><<</tt> to append to the target, so by supporting this
+ # method/operation builders can use oother builders as their
+ # targets.
+ def <<(text)
+ _text(text)
+ end
+
+ # For some reason, nil? is sent to the XmlMarkup object. If nil?
+ # is not defined and method_missing is invoked, some strange kind
+ # of recursion happens. Since nil? won't ever be an XML tag, it
+ # is pretty safe to define it here. (Note: this is an example of
+ # cargo cult programming,
+ # cf. http://fishbowl.pastiche.org/2004/10/13/cargo_cult_programming).
+ def nil?
+ false
+ end
+
+ private
+
+ def _escape(text)
+ text.
+ gsub(%r{&}, '&amp;').
+ gsub(%r{<}, '&lt;').
+ gsub(%r{>}, '&gt;')
+ end
+
+ def _capture_outer_self(block)
+ @self = eval("self", block)
+ end
+
+ def _newline
+ return if @indent == 0
+ text! "\n"
+ end
+
+ def _indent
+ return if @indent == 0 || @level == 0
+ text!(" " * (@level * @indent))
+ end
+
+ def _nested_structures(block)
+ @level += 1
+ block.call(self)
+ ensure
+ @level -= 1
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/vendor/builder/xmlevents.rb b/actionpack/lib/action_view/vendor/builder/xmlevents.rb
new file mode 100644
index 0000000000..15dc7b6421
--- /dev/null
+++ b/actionpack/lib/action_view/vendor/builder/xmlevents.rb
@@ -0,0 +1,63 @@
+#!/usr/bin/env ruby
+
+#--
+# Copyright 2004 by Jim Weirich (jim@weirichhouse.org).
+# All rights reserved.
+
+# Permission is granted for use, copying, modification, distribution,
+# and distribution of modified versions of this work as long as the
+# above copyright notice is included.
+#++
+
+require 'builder/xmlmarkup'
+
+module Builder
+
+ # Create a series of SAX-like XML events (e.g. start_tag, end_tag)
+ # from the markup code. XmlEvent objects are used in a way similar
+ # to XmlMarkup objects, except that a series of events are generated
+ # and passed to a handler rather than generating character-based
+ # markup.
+ #
+ # Usage:
+ # xe = Builder::XmlEvents.new(hander)
+ # xe.title("HI") # Sends start_tag/end_tag/text messages to the handler.
+ #
+ # Indentation may also be selected by providing value for the
+ # indentation size and initial indentation level.
+ #
+ # xe = Builder::XmlEvents.new(handler, indent_size, initial_indent_level)
+ #
+ # == XML Event Handler
+ #
+ # The handler object must expect the following events.
+ #
+ # [<tt>start_tag(tag, attrs)</tt>]
+ # Announces that a new tag has been found. +tag+ is the name of
+ # the tag and +attrs+ is a hash of attributes for the tag.
+ #
+ # [<tt>end_tag(tag)</tt>]
+ # Announces that an end tag for +tag+ has been found.
+ #
+ # [<tt>text(text)</tt>]
+ # Announces that a string of characters (+text+) has been found.
+ # A series of characters may be broken up into more than one
+ # +text+ call, so the client cannot assume that a single
+ # callback contains all the text data.
+ #
+ class XmlEvents < XmlMarkup #:nodoc:
+ def text!(text)
+ @target.text(text)
+ end
+
+ def _start_tag(sym, attrs, end_too=false)
+ @target.start_tag(sym, attrs)
+ _end_tag(sym) if end_too
+ end
+
+ def _end_tag(sym)
+ @target.end_tag(sym)
+ end
+ end
+
+end
diff --git a/actionpack/lib/action_view/vendor/builder/xmlmarkup.rb b/actionpack/lib/action_view/vendor/builder/xmlmarkup.rb
new file mode 100644
index 0000000000..716ff52535
--- /dev/null
+++ b/actionpack/lib/action_view/vendor/builder/xmlmarkup.rb
@@ -0,0 +1,288 @@
+#!/usr/bin/env ruby
+#--
+# Copyright 2004 by Jim Weirich (jim@weirichhouse.org).
+# All rights reserved.
+
+# Permission is granted for use, copying, modification, distribution,
+# and distribution of modified versions of this work as long as the
+# above copyright notice is included.
+#++
+
+# Provide a flexible and easy to use Builder for creating XML markup.
+# See XmlBuilder for usage details.
+
+require 'builder/xmlbase'
+
+module Builder
+
+ # Create XML markup easily. All (well, almost all) methods sent to
+ # an XmlMarkup object will be translated to the equivalent XML
+ # markup. Any method with a block will be treated as an XML markup
+ # tag with nested markup in the block.
+ #
+ # Examples will demonstrate this easier than words. In the
+ # following, +xm+ is an +XmlMarkup+ object.
+ #
+ # xm.em("emphasized") # => <em>emphasized</em>
+ # xm.em { xmm.b("emp & bold") } # => <em><b>emph &amp; bold</b></em>
+ # xm.a("A Link", "href"=>"http://onestepback.org")
+ # # => <a href="http://onestepback.org">A Link</a>
+ # xm.div { br } # => <div><br/></div>
+ # xm.target("name"=>"compile", "option"=>"fast")
+ # # => <target option="fast" name="compile"\>
+ # # NOTE: order of attributes is not specified.
+ #
+ # xm.instruct! # <?xml version="1.0" encoding="UTF-8"?>
+ # xm.html { # <html>
+ # xm.head { # <head>
+ # xm.title("History") # <title>History</title>
+ # } # </head>
+ # xm.body { # <body>
+ # xm.comment! "HI" # <!-- HI -->
+ # xm.h1("Header") # <h1>Header</h1>
+ # xm.p("paragraph") # <p>paragraph</p>
+ # } # </body>
+ # } # </html>
+ #
+ # == Notes:
+ #
+ # * The order that attributes are inserted in markup tags is
+ # undefined.
+ #
+ # * Sometimes you wish to insert text without enclosing tags. Use
+ # the <tt>text!</tt> method to accomplish this.
+ #
+ # Example:
+ #
+ # xm.div { # <div>
+ # xm.text! "line"; xm.br # line<br/>
+ # xm.text! "another line"; xmbr # another line<br/>
+ # } # </div>
+ #
+ # * The special XML characters <, >, and & are converted to &lt;,
+ # &gt; and &amp; automatically. Use the <tt><<</tt> operation to
+ # insert text without modification.
+ #
+ # * Sometimes tags use special characters not allowed in ruby
+ # identifiers. Use the <tt>tag!</tt> method to handle these
+ # cases.
+ #
+ # Example:
+ #
+ # xml.tag!("SOAP:Envelope") { ... }
+ #
+ # will produce ...
+ #
+ # <SOAP:Envelope> ... </SOAP:Envelope>"
+ #
+ # <tt>tag!</tt> will also take text and attribute arguments (after
+ # the tag name) like normal markup methods. (But see the next
+ # bullet item for a better way to handle XML namespaces).
+ #
+ # * Direct support for XML namespaces is now available. If the
+ # first argument to a tag call is a symbol, it will be joined to
+ # the tag to produce a namespace:tag combination. It is easier to
+ # show this than describe it.
+ #
+ # xml.SOAP :Envelope do ... end
+ #
+ # Just put a space before the colon in a namespace to produce the
+ # right form for builder (e.g. "<tt>SOAP:Envelope</tt>" =>
+ # "<tt>xml.SOAP :Envelope</tt>")
+ #
+ # * XmlMarkup builds the markup in any object (called a _target_)
+ # that accepts the <tt><<</tt> method. If no target is given,
+ # then XmlMarkup defaults to a string target.
+ #
+ # Examples:
+ #
+ # xm = Builder::XmlMarkup.new
+ # result = xm.title("yada")
+ # # result is a string containing the markup.
+ #
+ # buffer = ""
+ # xm = Builder::XmlMarkup.new(buffer)
+ # # The markup is appended to buffer (using <<)
+ #
+ # xm = Builder::XmlMarkup.new(STDOUT)
+ # # The markup is written to STDOUT (using <<)
+ #
+ # xm = Builder::XmlMarkup.new
+ # x2 = Builder::XmlMarkup.new(:target=>xm)
+ # # Markup written to +x2+ will be send to +xm+.
+ #
+ # * Indentation is enabled by providing the number of spaces to
+ # indent for each level as a second argument to XmlBuilder.new.
+ # Initial indentation may be specified using a third parameter.
+ #
+ # Example:
+ #
+ # xm = Builder.new(:ident=>2)
+ # # xm will produce nicely formatted and indented XML.
+ #
+ # xm = Builder.new(:indent=>2, :margin=>4)
+ # # xm will produce nicely formatted and indented XML with 2
+ # # spaces per indent and an over all indentation level of 4.
+ #
+ # builder = Builder::XmlMarkup.new(:target=>$stdout, :indent=>2)
+ # builder.name { |b| b.first("Jim"); b.last("Weirich) }
+ # # prints:
+ # # <name>
+ # # <first>Jim</first>
+ # # <last>Weirich</last>
+ # # </name>
+ #
+ # * The instance_eval implementation which forces self to refer to
+ # the message receiver as self is now obsolete. We now use normal
+ # block calls to execute the markup block. This means that all
+ # markup methods must now be explicitly send to the xml builder.
+ # For instance, instead of
+ #
+ # xml.div { strong("text") }
+ #
+ # you need to write:
+ #
+ # xml.div { xml.strong("text") }
+ #
+ # Although more verbose, the subtle change in semantics within the
+ # block was found to be prone to error. To make this change a
+ # little less cumbersome, the markup block now gets the markup
+ # object sent as an argument, allowing you to use a shorter alias
+ # within the block.
+ #
+ # For example:
+ #
+ # xml_builder = Builder::XmlMarkup.new
+ # xml_builder.div { |xml|
+ # xml.stong("text")
+ # }
+ #
+ class XmlMarkup < XmlBase
+
+ # Create an XML markup builder. Parameters are specified by an
+ # option hash.
+ #
+ # :target=><em>target_object</em>::
+ # Object receiving the markup. +out+ must respond to the
+ # <tt><<</tt> operator. The default is a plain string target.
+ # :indent=><em>indentation</em>::
+ # Number of spaces used for indentation. The default is no
+ # indentation and no line breaks.
+ # :margin=><em>initial_indentation_level</em>::
+ # Amount of initial indentation (specified in levels, not
+ # spaces).
+ #
+ def initialize(options={})
+ indent = options[:indent] || 0
+ margin = options[:margin] || 0
+ super(indent, margin)
+ @target = options[:target] || ""
+ end
+
+ # Return the target of the builder.
+ def target!
+ @target
+ end
+
+ def comment!(comment_text)
+ _ensure_no_block block_given?
+ _special("<!-- ", " -->", comment_text, nil)
+ end
+
+ # Insert an XML declaration into the XML markup.
+ #
+ # For example:
+ #
+ # xml.declare! :ELEMENT, :blah, "yada"
+ # # => <!ELEMENT blah "yada">
+ def declare!(inst, *args, &block)
+ _indent
+ @target << "<!#{inst}"
+ args.each do |arg|
+ case arg
+ when String
+ @target << %{ "#{arg}"}
+ when Symbol
+ @target << " #{arg}"
+ end
+ end
+ if block_given?
+ @target << " ["
+ _newline
+ _nested_structures(block)
+ @target << "]"
+ end
+ @target << ">"
+ _newline
+ end
+
+ # Insert a processing instruction into the XML markup. E.g.
+ #
+ # For example:
+ #
+ # xml.instruct!
+ # #=> <?xml encoding="UTF-8" version="1.0"?>
+ # xml.instruct! :aaa, :bbb=>"ccc"
+ # #=> <?aaa bbb="ccc"?>
+ #
+ def instruct!(directive_tag=:xml, attrs={})
+ _ensure_no_block block_given?
+ if directive_tag == :xml
+ a = { :version=>"1.0", :encoding=>"UTF-8" }
+ attrs = a.merge attrs
+ end
+ _special("<?#{directive_tag}", "?>", nil, attrs)
+ end
+
+ private
+
+ # NOTE: All private methods of a builder object are prefixed when
+ # a "_" character to avoid possible conflict with XML tag names.
+
+ # Insert text directly in to the builder's target.
+ def _text(text)
+ @target << text
+ end
+
+ # Insert special instruction.
+ def _special(open, close, data=nil, attrs=nil)
+ _indent
+ @target << open
+ @target << data if data
+ _insert_attributes(attrs) if attrs
+ @target << close
+ _newline
+ end
+
+ # Start an XML tag. If <tt>end_too</tt> is true, then the start
+ # tag is also the end tag (e.g. <br/>
+ def _start_tag(sym, attrs, end_too=false)
+ @target << "<#{sym}"
+ _insert_attributes(attrs)
+ @target << "/" if end_too
+ @target << ">"
+ end
+
+ # Insert an ending tag.
+ def _end_tag(sym)
+ @target << "</#{sym}>"
+ end
+
+ # Insert the attributes (given in the hash).
+ def _insert_attributes(attrs)
+ return if attrs.nil?
+ attrs.each do |k, v|
+ @target << %{ #{k}="#{v}"}
+ end
+ end
+
+ def _ensure_no_block(got_block)
+ if got_block
+ fail IllegalBlockError,
+ "Blocks are not allowed on XML instructions"
+ end
+ end
+
+ end
+
+end