aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--actionmailer/README.rdoc2
-rw-r--r--actionmailer/lib/action_mailer/mail_helper.rb9
-rw-r--r--actionmailer/test/mail_helper_test.rb44
-rw-r--r--actionpack/CHANGELOG.md5
-rw-r--r--actionpack/README.rdoc2
-rw-r--r--actionpack/lib/abstract_controller/base.rb4
-rw-r--r--actionpack/lib/action_controller/caching/actions.rb6
-rw-r--r--actionpack/lib/action_controller/metal/conditional_get.rb11
-rw-r--r--actionpack/lib/action_controller/metal/responder.rb2
-rw-r--r--actionpack/lib/action_dispatch/http/cache.rb14
-rw-r--r--actionpack/lib/action_dispatch/http/filter_parameters.rb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/static.rb13
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb8
-rw-r--r--actionpack/lib/action_dispatch/testing/test_process.rb3
-rw-r--r--actionpack/lib/action_view/helpers/form_helper.rb10
-rw-r--r--actionpack/lib/action_view/helpers/form_options_helper.rb25
-rw-r--r--actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb4
-rw-r--r--actionpack/lib/action_view/helpers/tags/collection_helpers.rb11
-rw-r--r--actionpack/lib/action_view/helpers/tags/collection_radio_buttons.rb4
-rw-r--r--actionpack/lib/action_view/helpers/tags/grouped_collection_select.rb7
-rw-r--r--actionpack/lib/action_view/locale/en.yml9
-rw-r--r--actionpack/lib/action_view/template.rb1
-rw-r--r--actionpack/lib/action_view/template/handlers.rb1
-rw-r--r--actionpack/lib/sprockets/helpers/rails_helper.rb6
-rw-r--r--actionpack/test/controller/caching_test.rb12
-rw-r--r--actionpack/test/controller/integration_test.rb51
-rw-r--r--actionpack/test/controller/render_test.rb27
-rw-r--r--actionpack/test/controller/routing_test.rb26
-rw-r--r--actionpack/test/controller/test_case_test.rb5
-rw-r--r--actionpack/test/dispatch/callbacks_test.rb11
-rw-r--r--actionpack/test/dispatch/routing_test.rb2
-rw-r--r--actionpack/test/dispatch/static_test.rb90
-rw-r--r--actionpack/test/fixtures/with_format.json.erb1
-rw-r--r--actionpack/test/template/form_collections_helper_test.rb26
-rw-r--r--actionpack/test/template/form_options_helper_test.rb50
-rw-r--r--actionpack/test/template/render_test.rb13
-rw-r--r--actionpack/test/template/template_test.rb2
-rw-r--r--activemodel/CHANGELOG.md2
-rw-r--r--activemodel/lib/active_model/errors.rb17
-rw-r--r--activemodel/lib/active_model/mass_assignment_security.rb6
-rw-r--r--activemodel/lib/active_model/validations/length.rb2
-rw-r--r--activemodel/test/cases/errors_test.rb10
-rw-r--r--activemodel/test/cases/mass_assignment_security_test.rb7
-rw-r--r--activerecord/CHANGELOG.md2
-rw-r--r--activerecord/lib/active_record/attribute_methods/before_type_cast.rb6
-rw-r--r--activerecord/lib/active_record/attribute_methods/dirty.rb6
-rw-r--r--activerecord/lib/active_record/attribute_methods/primary_key.rb11
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb60
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_adapter.rb23
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql_adapter.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb62
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb1
-rw-r--r--activerecord/lib/active_record/core.rb2
-rw-r--r--activerecord/lib/active_record/railties/databases.rake10
-rw-r--r--activerecord/test/cases/adapters/postgresql/schema_test.rb10
-rw-r--r--activerecord/test/cases/attribute_methods_test.rb8
-rw-r--r--activerecord/test/cases/connection_management_test.rb21
-rw-r--r--activerecord/test/cases/dirty_test.rb14
-rw-r--r--activesupport/lib/active_support/cache/mem_cache_store.rb1
-rw-r--r--activesupport/lib/active_support/callbacks.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/object/blank.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/string.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/time/calculations.rb2
-rw-r--r--activesupport/lib/active_support/gzip.rb1
-rw-r--r--activesupport/lib/active_support/ruby/shim.rb1
-rw-r--r--railties/CHANGELOG.md12
-rw-r--r--railties/guides/assets/stylesheets/fixes.css2
-rw-r--r--railties/guides/assets/stylesheets/main.css1
-rw-r--r--railties/guides/source/active_record_validations_callbacks.textile2
-rw-r--r--railties/guides/source/association_basics.textile105
-rw-r--r--railties/guides/source/configuring.textile11
-rw-r--r--railties/guides/source/engines.textile206
-rw-r--r--railties/guides/source/layouts_and_rendering.textile2
-rw-r--r--railties/guides/source/plugins.textile2
-rw-r--r--railties/lib/rails/application/configuration.rb3
-rw-r--r--railties/lib/rails/commands/console.rb75
-rw-r--r--railties/lib/rails/engine.rb4
-rw-r--r--railties/test/application/rake/migrations_test.rb50
-rw-r--r--railties/test/commands/console_test.rb87
81 files changed, 1140 insertions, 238 deletions
diff --git a/actionmailer/README.rdoc b/actionmailer/README.rdoc
index 4c2516db59..755717cfba 100644
--- a/actionmailer/README.rdoc
+++ b/actionmailer/README.rdoc
@@ -82,7 +82,7 @@ Note that every value you set with this method will get over written if you use
Example:
- class Authenticationmailer < ActionMailer::Base
+ class AuthenticationMailer < ActionMailer::Base
default :from => "awesome@application.com", :subject => Proc.new { "E-mail was generated at #{Time.now}" }
.....
end
diff --git a/actionmailer/lib/action_mailer/mail_helper.rb b/actionmailer/lib/action_mailer/mail_helper.rb
index 6f22adc479..2036883b22 100644
--- a/actionmailer/lib/action_mailer/mail_helper.rb
+++ b/actionmailer/lib/action_mailer/mail_helper.rb
@@ -1,11 +1,10 @@
module ActionMailer
module MailHelper
- # Uses Text::Format to take the text and format it, indented two spaces for
- # each line, and wrapped at 72 columns.
+ # Take the text and format it, indented two spaces for each line, and wrapped at 72 columns.
def block_format(text)
- formatted = text.split(/\n\r\n/).collect { |paragraph|
+ formatted = text.split(/\n\r?\n/).collect { |paragraph|
format_paragraph(paragraph)
- }.join("\n")
+ }.join("\n\n")
# Make list points stand on their own line
formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
@@ -41,7 +40,7 @@ module ActionMailer
sentences = [[]]
text.split.each do |word|
- if (sentences.last + [word]).join(' ').length > len
+ if sentences.first.present? && (sentences.last + [word]).join(' ').length > len
sentences << [word]
else
sentences.last << word
diff --git a/actionmailer/test/mail_helper_test.rb b/actionmailer/test/mail_helper_test.rb
index 17e9c82045..d8a73e6c46 100644
--- a/actionmailer/test/mail_helper_test.rb
+++ b/actionmailer/test/mail_helper_test.rb
@@ -22,6 +22,14 @@ class HelperMailer < ActionMailer::Base
end
end
+ def use_format_paragraph_with_long_first_word
+ @text = "Antidisestablishmentarianism is very long."
+
+ mail_with_defaults do |format|
+ format.html { render(:inline => "<%= format_paragraph @text, 10, 1 %>") }
+ end
+ end
+
def use_mailer
mail_with_defaults do |format|
format.html { render(:inline => "<%= mailer.message.subject %>") }
@@ -34,6 +42,23 @@ class HelperMailer < ActionMailer::Base
end
end
+ def use_block_format
+ @text = <<-TEXT
+This is the
+first paragraph.
+
+The second
+ paragraph.
+
+* item1 * item2
+ * item3
+ TEXT
+
+ mail_with_defaults do |format|
+ format.html { render(:inline => "<%= block_format @text %>") }
+ end
+ end
+
protected
def mail_with_defaults(&block)
@@ -63,5 +88,24 @@ class MailerHelperTest < ActionMailer::TestCase
mail = HelperMailer.use_format_paragraph
assert_match " But soft! What\r\n light through\r\n yonder window\r\n breaks?", mail.body.encoded
end
+
+ def test_use_format_paragraph_with_long_first_word
+ mail = HelperMailer.use_format_paragraph_with_long_first_word
+ assert_equal " Antidisestablishmentarianism\r\n is very\r\n long.", mail.body.encoded
+ end
+
+ def test_use_block_format
+ mail = HelperMailer.use_block_format
+ expected = <<-TEXT
+ This is the first paragraph.
+
+ The second paragraph.
+
+ * item1
+ * item2
+ * item3
+ TEXT
+ assert_equal expected.gsub("\n", "\r\n"), mail.body.encoded
+ end
end
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index 459f5b90e4..cf662500a4 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,5 +1,10 @@
## Rails 4.0.0 (unreleased) ##
+* Integration tests support the `OPTIONS` method. *Jeremy Kemper*
+
+* `expires_in` accepts a `must_revalidate` flag. If true, "must-revalidate"
+ is added to the Cache-Control header. *fxn*
+
* Add `date_field` and `date_field_tag` helpers which render an `input[type="date"]` tag *Olek Janiszewski*
* Adds `image_url`, `javascript_url`, `stylesheet_url`, `audio_url`, `video_url`, and `font_url`
diff --git a/actionpack/README.rdoc b/actionpack/README.rdoc
index 076a93bbcd..1fdc57e14d 100644
--- a/actionpack/README.rdoc
+++ b/actionpack/README.rdoc
@@ -218,7 +218,7 @@ A short rundown of some of the major features:
def show
# the output of the method will be cached as
- # ActionController::Base.page_cache_directory + "/weblog/show/n.html"
+ # ActionController::Base.page_cache_directory + "/weblog/show.html"
# and the web server will pick it up without even hitting Rails
end
diff --git a/actionpack/lib/abstract_controller/base.rb b/actionpack/lib/abstract_controller/base.rb
index fd6a46fbec..3d915cf513 100644
--- a/actionpack/lib/abstract_controller/base.rb
+++ b/actionpack/lib/abstract_controller/base.rb
@@ -42,8 +42,8 @@ module AbstractController
controller.public_instance_methods(true)
end
- # The list of hidden actions to an empty array. Defaults to an
- # empty array. This can be modified by other modules or subclasses
+ # The list of hidden actions. Defaults to an empty array.
+ # This can be modified by other modules or subclasses
# to specify particular actions as hidden.
#
# ==== Returns
diff --git a/actionpack/lib/action_controller/caching/actions.rb b/actionpack/lib/action_controller/caching/actions.rb
index bd3b0b5df3..ba96735e56 100644
--- a/actionpack/lib/action_controller/caching/actions.rb
+++ b/actionpack/lib/action_controller/caching/actions.rb
@@ -103,8 +103,10 @@ module ActionController #:nodoc:
end
def _save_fragment(name, options)
- content = response_body
- content = content.join if content.is_a?(Array)
+ content = ""
+ response_body.each do |parts|
+ content << parts
+ end
if caching_allowed?
write_fragment(name, content, options)
diff --git a/actionpack/lib/action_controller/metal/conditional_get.rb b/actionpack/lib/action_controller/metal/conditional_get.rb
index 1645400693..2a8e4c575e 100644
--- a/actionpack/lib/action_controller/metal/conditional_get.rb
+++ b/actionpack/lib/action_controller/metal/conditional_get.rb
@@ -110,16 +110,23 @@ module ActionController
#
# Examples:
# expires_in 20.minutes
- # expires_in 3.hours, :public => true
+ # expires_in 3.hours, :public => true, :must_revalidate => true
# expires_in 3.hours, 'max-stale' => 5.hours, :public => true
#
# This method will overwrite an existing Cache-Control header.
# See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html for more possibilities.
+ #
+ # The method will also ensure a HTTP Date header for client compatibility.
def expires_in(seconds, options = {}) #:doc:
- response.cache_control.merge!(:max_age => seconds, :public => options.delete(:public))
+ response.cache_control.merge!(
+ :max_age => seconds,
+ :public => options.delete(:public),
+ :must_revalidate => options.delete(:must_revalidate)
+ )
options.delete(:private)
response.cache_control[:extras] = options.map {|k,v| "#{k}=#{v}"}
+ response.date = Time.now unless response.date?
end
# Sets a HTTP 1.1 Cache-Control header of <tt>no-cache</tt> so no caching should occur by the browser or
diff --git a/actionpack/lib/action_controller/metal/responder.rb b/actionpack/lib/action_controller/metal/responder.rb
index 4ad64bff20..daa1ddd65f 100644
--- a/actionpack/lib/action_controller/metal/responder.rb
+++ b/actionpack/lib/action_controller/metal/responder.rb
@@ -267,7 +267,7 @@ module ActionController #:nodoc:
end
def resource_errors
- respond_to?("#{format}_resource_errors") ? send("#{format}_resource_errors") : resource.errors
+ respond_to?("#{format}_resource_errors", true) ? send("#{format}_resource_errors") : resource.errors
end
def json_resource_errors
diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb
index bea62b94d2..5ee4c044ea 100644
--- a/actionpack/lib/action_dispatch/http/cache.rb
+++ b/actionpack/lib/action_dispatch/http/cache.rb
@@ -60,6 +60,20 @@ module ActionDispatch
headers[LAST_MODIFIED] = utc_time.httpdate
end
+ def date
+ if date_header = headers['Date']
+ Time.httpdate(date_header)
+ end
+ end
+
+ def date?
+ headers.include?('Date')
+ end
+
+ def date=(utc_time)
+ headers['Date'] = utc_time.httpdate
+ end
+
def etag=(etag)
key = ActiveSupport::Cache.expand_cache_key(etag)
@etag = self[ETAG] = %("#{Digest::MD5.hexdigest(key)}")
diff --git a/actionpack/lib/action_dispatch/http/filter_parameters.rb b/actionpack/lib/action_dispatch/http/filter_parameters.rb
index 02a15ad599..132b0c82bc 100644
--- a/actionpack/lib/action_dispatch/http/filter_parameters.rb
+++ b/actionpack/lib/action_dispatch/http/filter_parameters.rb
@@ -50,7 +50,7 @@ module ActionDispatch
end
def env_filter
- parameter_filter_for(Array(@env["action_dispatch.parameter_filter"]) << /RAW_POST_DATA/)
+ parameter_filter_for(Array(@env["action_dispatch.parameter_filter"]) + [/RAW_POST_DATA/, "rack.request.form_vars"])
end
def parameter_filter_for(filters)
diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb
index 404943d720..63b7422287 100644
--- a/actionpack/lib/action_dispatch/middleware/static.rb
+++ b/actionpack/lib/action_dispatch/middleware/static.rb
@@ -1,4 +1,5 @@
require 'rack/utils'
+require 'active_support/core_ext/uri'
module ActionDispatch
class FileHandler
@@ -11,14 +12,14 @@ module ActionDispatch
def match?(path)
path = path.dup
- full_path = path.empty? ? @root : File.join(@root, ::Rack::Utils.unescape(path))
+ full_path = path.empty? ? @root : File.join(@root, escape_glob_chars(unescape_path(path)))
paths = "#{full_path}#{ext}"
matches = Dir[paths]
match = matches.detect { |m| File.file?(m) }
if match
match.sub!(@compiled_root, '')
- match
+ ::Rack::Utils.escape(match)
end
end
@@ -32,6 +33,14 @@ module ActionDispatch
"{,#{ext},/index#{ext}}"
end
end
+
+ def unescape_path(path)
+ URI.parser.unescape(path)
+ end
+
+ def escape_glob_chars(path)
+ path.gsub(/[*?{}\[\]]/, "\\\\\\&")
+ end
end
class Static
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index 08b7ff49c2..0287e7728b 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -56,6 +56,12 @@ module ActionDispatch
process :head, path, parameters, headers
end
+ # Performs a OPTIONS request with the given parameters. See +#get+ for
+ # more details.
+ def options(path, parameters = nil, headers = nil)
+ process :options, path, parameters, headers
+ end
+
# Performs an XMLHttpRequest request with the given parameters, mirroring
# a request from the Prototype library.
#
@@ -312,7 +318,7 @@ module ActionDispatch
@integration_session = Integration::Session.new(app)
end
- %w(get post put head delete cookies assigns
+ %w(get post put head delete options cookies assigns
xml_http_request xhr get_via_redirect post_via_redirect).each do |method|
define_method(method) do |*args|
reset! unless integration_session
diff --git a/actionpack/lib/action_dispatch/testing/test_process.rb b/actionpack/lib/action_dispatch/testing/test_process.rb
index b08ff41950..3a6d081721 100644
--- a/actionpack/lib/action_dispatch/testing/test_process.rb
+++ b/actionpack/lib/action_dispatch/testing/test_process.rb
@@ -5,7 +5,8 @@ require 'active_support/core_ext/hash/indifferent_access'
module ActionDispatch
module TestProcess
def assigns(key = nil)
- assigns = @controller.view_assigns.with_indifferent_access
+ assigns = {}.with_indifferent_access
+ @controller.view_assigns.each {|k, v| assigns.regular_writer(k, v)}
key.nil? ? assigns : assigns[key]
end
diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
index 44e24fecd1..cae345a1d6 100644
--- a/actionpack/lib/action_view/helpers/form_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -1102,14 +1102,14 @@ module ActionView
# <% end %>
#
# In the example above, if @post is a new record, it will use "Create Post" as
- # submit button label, otherwise, it uses "Update Post".
+ # button label, otherwise, it uses "Update Post".
#
- # Those labels can be customized using I18n, under the helpers.submit key and accept
- # the %{model} as translation interpolation:
+ # Those labels can be customized using I18n, under the helpers.submit key
+ # (the same as submit helper) and accept the %{model} as translation interpolation:
#
# en:
# helpers:
- # button:
+ # submit:
# create: "Create a %{model}"
# update: "Confirm changes to %{model}"
#
@@ -1117,7 +1117,7 @@ module ActionView
#
# en:
# helpers:
- # button:
+ # submit:
# post:
# create: "Add %{model}"
#
diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb
index bc03a1cf83..abb548c276 100644
--- a/actionpack/lib/action_view/helpers/form_options_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_options_helper.rb
@@ -330,9 +330,12 @@ module ActionView
container.map do |element|
html_attributes = option_html_attributes(element)
text, value = option_text_and_value(element).map { |item| item.to_s }
- selected_attribute = ' selected="selected"' if option_value_selected?(value, selected)
- disabled_attribute = ' disabled="disabled"' if disabled && option_value_selected?(value, disabled)
- %(<option value="#{ERB::Util.html_escape(value)}"#{selected_attribute}#{disabled_attribute}#{html_attributes}>#{ERB::Util.html_escape(text)}</option>)
+
+ html_attributes[:selected] = 'selected' if option_value_selected?(value, selected)
+ html_attributes[:disabled] = 'disabled' if disabled && option_value_selected?(value, disabled)
+ html_attributes[:value] = value
+
+ content_tag(:option, text, html_attributes)
end.join("\n").html_safe
end
@@ -472,16 +475,16 @@ module ActionView
# <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to
# wrap the output in an appropriate <tt><select></tt> tag.
def grouped_options_for_select(grouped_options, selected_key = nil, prompt = nil)
- body = ''
- body << content_tag(:option, prompt, { :value => "" }, true) if prompt
+ body = "".html_safe
+ body.safe_concat content_tag(:option, prompt, :value => "") if prompt
grouped_options = grouped_options.sort if grouped_options.is_a?(Hash)
- grouped_options.each do |group|
- body << content_tag(:optgroup, options_for_select(group[1], selected_key), :label => group[0])
+ grouped_options.each do |label, container|
+ body.safe_concat content_tag(:optgroup, options_for_select(container, selected_key), :label => label)
end
- body.html_safe
+ body
end
# Returns a string of option tags for pretty much any time zone in the
@@ -649,11 +652,9 @@ module ActionView
private
def option_html_attributes(element)
- return "" unless Array === element
+ return {} unless Array === element
- element.select { |e| Hash === e }.reduce({}, :merge).map do |k, v|
- " #{k}=\"#{ERB::Util.html_escape(v.to_s)}\""
- end.join
+ Hash[element.select { |e| Hash === e }.reduce({}, :merge).map { |k, v| [k, ERB::Util.html_escape(v.to_s)] }]
end
def option_text_and_value(option)
diff --git a/actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb b/actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb
index 5f1e9ec026..e23f5113fb 100644
--- a/actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb
+++ b/actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb
@@ -14,9 +14,9 @@ module ActionView
end
def render
- rendered_collection = render_collection do |value, text, default_html_options|
+ rendered_collection = render_collection do |item, value, text, default_html_options|
default_html_options[:multiple] = true
- builder = instantiate_builder(CheckBoxBuilder, value, text, default_html_options)
+ builder = instantiate_builder(CheckBoxBuilder, item, value, text, default_html_options)
if block_given?
yield builder
diff --git a/actionpack/lib/action_view/helpers/tags/collection_helpers.rb b/actionpack/lib/action_view/helpers/tags/collection_helpers.rb
index 1e2e77dde1..6f950e552a 100644
--- a/actionpack/lib/action_view/helpers/tags/collection_helpers.rb
+++ b/actionpack/lib/action_view/helpers/tags/collection_helpers.rb
@@ -3,13 +3,14 @@ module ActionView
module Tags
module CollectionHelpers
class Builder
- attr_reader :text, :value
+ attr_reader :object, :text, :value
- def initialize(template_object, object_name, method_name,
+ def initialize(template_object, object_name, method_name, object,
sanitized_attribute_name, text, value, input_html_options)
@template_object = template_object
@object_name = object_name
@method_name = method_name
+ @object = object
@sanitized_attribute_name = sanitized_attribute_name
@text = text
@value = value
@@ -32,8 +33,8 @@ module ActionView
private
- def instantiate_builder(builder_class, value, text, html_options)
- builder_class.new(@template_object, @object_name, @method_name,
+ def instantiate_builder(builder_class, item, value, text, html_options)
+ builder_class.new(@template_object, @object_name, @method_name, item,
sanitize_attribute_name(value), text, value, html_options)
end
@@ -71,7 +72,7 @@ module ActionView
text = value_for_collection(item, @text_method)
default_html_options = default_html_options_for_collection(item, value)
- yield value, text, default_html_options
+ yield item, value, text, default_html_options
end.join.html_safe
end
end
diff --git a/actionpack/lib/action_view/helpers/tags/collection_radio_buttons.rb b/actionpack/lib/action_view/helpers/tags/collection_radio_buttons.rb
index 8e7aeeed63..ba2035f074 100644
--- a/actionpack/lib/action_view/helpers/tags/collection_radio_buttons.rb
+++ b/actionpack/lib/action_view/helpers/tags/collection_radio_buttons.rb
@@ -14,8 +14,8 @@ module ActionView
end
def render
- render_collection do |value, text, default_html_options|
- builder = instantiate_builder(RadioButtonBuilder, value, text, default_html_options)
+ render_collection do |item, value, text, default_html_options|
+ builder = instantiate_builder(RadioButtonBuilder, item, value, text, default_html_options)
if block_given?
yield builder
diff --git a/actionpack/lib/action_view/helpers/tags/grouped_collection_select.rb b/actionpack/lib/action_view/helpers/tags/grouped_collection_select.rb
index 507466a57a..507ba8835f 100644
--- a/actionpack/lib/action_view/helpers/tags/grouped_collection_select.rb
+++ b/actionpack/lib/action_view/helpers/tags/grouped_collection_select.rb
@@ -14,8 +14,13 @@ module ActionView
end
def render
+ option_tags_options = {
+ :selected => @options.fetch(:selected) { value(@object) },
+ :disabled => @options[:disabled]
+ }
+
select_content_tag(
- option_groups_from_collection_for_select(@collection, @group_method, @group_label_method, @option_key_method, @option_value_method, value(@object)), @options, @html_options
+ option_groups_from_collection_for_select(@collection, @group_method, @group_label_method, @option_key_method, @option_value_method, option_tags_options), @options, @html_options
)
end
end
diff --git a/actionpack/lib/action_view/locale/en.yml b/actionpack/lib/action_view/locale/en.yml
index 7cca7d969a..8e9db634fb 100644
--- a/actionpack/lib/action_view/locale/en.yml
+++ b/actionpack/lib/action_view/locale/en.yml
@@ -147,15 +147,8 @@
# Default value for :prompt => true in FormOptionsHelper
prompt: "Please select"
- # Default translation keys for submit FormHelper
+ # Default translation keys for submit and button FormHelper
submit:
create: 'Create %{model}'
update: 'Update %{model}'
submit: 'Save %{model}'
-
- # Default translation keys for button FormHelper
- button:
- create: 'Create %{model}'
- update: 'Update %{model}'
- submit: 'Save %{model}'
-
diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb
index edb3d427d5..644debd49c 100644
--- a/actionpack/lib/action_view/template.rb
+++ b/actionpack/lib/action_view/template.rb
@@ -163,6 +163,7 @@ module ActionView
pieces = @virtual_path.split("/")
name = pieces.pop
partial = !!name.sub!(/^_/, "")
+ lookup.formats = @formats
lookup.disable_cache do
lookup.find_template(name, [ pieces.join('/') ], partial, @locals)
end
diff --git a/actionpack/lib/action_view/template/handlers.rb b/actionpack/lib/action_view/template/handlers.rb
index 67978ada7e..4e22bec6cc 100644
--- a/actionpack/lib/action_view/template/handlers.rb
+++ b/actionpack/lib/action_view/template/handlers.rb
@@ -23,6 +23,7 @@ module ActionView #:nodoc:
# and should return the rendered template as a String.
def register_template_handler(extension, handler)
@@template_handlers[extension.to_sym] = handler
+ @@template_extensions = nil
end
def template_handler_extensions
diff --git a/actionpack/lib/sprockets/helpers/rails_helper.rb b/actionpack/lib/sprockets/helpers/rails_helper.rb
index 976ae5a76d..5a46a01027 100644
--- a/actionpack/lib/sprockets/helpers/rails_helper.rb
+++ b/actionpack/lib/sprockets/helpers/rails_helper.rb
@@ -19,9 +19,9 @@ module Sprockets
def javascript_include_tag(*sources)
options = sources.extract_options!
- debug = options.key?(:debug) ? options.delete(:debug) : debug_assets?
- body = options.key?(:body) ? options.delete(:body) : false
- digest = options.key?(:digest) ? options.delete(:digest) : digest_assets?
+ debug = options.delete(:debug) { debug_assets? }
+ body = options.delete(:body) { false }
+ digest = options.delete(:digest) { digest_assets? }
sources.collect do |source|
if debug && asset = asset_paths.asset_for(source, 'js')
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index bb4fb7bf07..10f73c3da3 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -237,6 +237,7 @@ class ActionCachingTestController < CachingController
caches_action :with_format_and_http_param, :cache_path => Proc.new { |c| { :key => 'value' } }
caches_action :layout_false, :layout => false
caches_action :record_not_found, :four_oh_four, :simple_runtime_error
+ caches_action :streaming
layout 'talk_from_action'
@@ -296,6 +297,10 @@ class ActionCachingTestController < CachingController
expire_action url_for(:controller => 'action_caching_test', :action => 'index')
render :nothing => true
end
+
+ def streaming
+ render :text => "streaming", :stream => true
+ end
end
class MockTime < Time
@@ -647,6 +652,13 @@ class ActionCacheTest < ActionController::TestCase
assert_response 500
end
+ def test_action_caching_plus_streaming
+ get :streaming
+ assert_response :success
+ assert_match(/streaming/, @response.body)
+ assert fragment_exist?('hostname.com/action_caching_test/streaming')
+ end
+
private
def content_to_cache
assigns(:cache_this)
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index a328372cff..64c4682015 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -105,6 +105,12 @@ class SessionTest < ActiveSupport::TestCase
@session.head(path,params,headers)
end
+ def test_options
+ path = "/index"; params = "blah"; headers = {:location => 'blah'}
+ @session.expects(:process).with(:options,path,params,headers)
+ @session.options(path,params,headers)
+ end
+
def test_xml_http_request_get
path = "/index"; params = "blah"; headers = {:location => 'blah'}
headers_after_xhr = headers.merge(
@@ -155,6 +161,16 @@ class SessionTest < ActiveSupport::TestCase
@session.xml_http_request(:head,path,params,headers)
end
+ def test_xml_http_request_options
+ path = "/index"; params = "blah"; headers = {:location => 'blah'}
+ headers_after_xhr = headers.merge(
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
+ )
+ @session.expects(:process).with(:options,path,params,headers_after_xhr)
+ @session.xml_http_request(:options,path,params,headers)
+ end
+
def test_xml_http_request_override_accept
path = "/index"; params = "blah"; headers = {:location => 'blah', "HTTP_ACCEPT" => "application/xml"}
headers_after_xhr = headers.merge(
@@ -212,7 +228,7 @@ class IntegrationTestUsesCorrectClass < ActionDispatch::IntegrationTest
@integration_session.stubs(:generic_url_rewriter)
@integration_session.stubs(:process)
- %w( get post head put delete ).each do |verb|
+ %w( get post head put delete options ).each do |verb|
assert_nothing_raised("'#{verb}' should use integration test methods") { __send__(verb, '/') }
end
end
@@ -535,3 +551,36 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest
assert_equal old_env, env
end
end
+
+class EnvironmentFilterIntegrationTest < ActionDispatch::IntegrationTest
+ class TestController < ActionController::Base
+ def post
+ render :text => "Created", :status => 201
+ end
+ end
+
+ def self.call(env)
+ env["action_dispatch.parameter_filter"] = [:password]
+ routes.call(env)
+ end
+
+ def self.routes
+ @routes ||= ActionDispatch::Routing::RouteSet.new
+ end
+
+ routes.draw do
+ match '/post', :to => 'environment_filter_integration_test/test#post', :via => :post
+ end
+
+ def app
+ self.class
+ end
+
+ test "filters rack request form vars" do
+ post "/post", :username => 'cjolly', :password => 'secret'
+
+ assert_equal 'cjolly', request.filtered_parameters['username']
+ assert_equal '[FILTERED]', request.filtered_parameters['password']
+ assert_equal '[FILTERED]', request.filtered_env['rack.request.form_vars']
+ end
+end
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index fef9fbb175..e040878b26 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -91,6 +91,16 @@ class TestController < ActionController::Base
render :action => 'hello_world'
end
+ def conditional_hello_with_expires_in_with_must_revalidate
+ expires_in 1.minute, :must_revalidate => true
+ render :action => 'hello_world'
+ end
+
+ def conditional_hello_with_expires_in_with_public_and_must_revalidate
+ expires_in 1.minute, :public => true, :must_revalidate => true
+ render :action => 'hello_world'
+ end
+
def conditional_hello_with_expires_in_with_public_with_more_keys
expires_in 1.minute, :public => true, 'max-stale' => 5.hours
render :action => 'hello_world'
@@ -1399,6 +1409,16 @@ class ExpiresInRenderTest < ActionController::TestCase
assert_equal "max-age=60, public", @response.headers["Cache-Control"]
end
+ def test_expires_in_header_with_must_revalidate
+ get :conditional_hello_with_expires_in_with_must_revalidate
+ assert_equal "max-age=60, private, must-revalidate", @response.headers["Cache-Control"]
+ end
+
+ def test_expires_in_header_with_public_and_must_revalidate
+ get :conditional_hello_with_expires_in_with_public_and_must_revalidate
+ assert_equal "max-age=60, public, must-revalidate", @response.headers["Cache-Control"]
+ end
+
def test_expires_in_header_with_additional_headers
get :conditional_hello_with_expires_in_with_public_with_more_keys
assert_equal "max-age=60, public, max-stale=18000", @response.headers["Cache-Control"]
@@ -1413,6 +1433,13 @@ class ExpiresInRenderTest < ActionController::TestCase
get :conditional_hello_with_expires_now
assert_equal "no-cache", @response.headers["Cache-Control"]
end
+
+ def test_date_header_when_expires_in
+ time = Time.mktime(2011,10,30)
+ Time.stubs(:now).returns(time)
+ get :conditional_hello_with_expires_in
+ assert_equal Time.now.httpdate, @response.headers["Date"]
+ end
end
class LastModifiedRenderTest < ActionController::TestCase
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index d403494261..ee9374cc91 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -145,6 +145,32 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
assert_equal 'Not Found', get(URI('http://example.org/journey/omg-faithfully'))
end
+ def test_star_paths_are_greedy
+ rs.draw do
+ match "/(*filters)", :to => lambda { |env|
+ x = env["action_dispatch.request.path_parameters"][:filters]
+ [200, {}, [x]]
+ }, :format => false
+ end
+
+ u = URI('http://example.org/ne_27.065938,-80.6092/sw_25.489856,-82.542794')
+ assert_equal u.path.sub(/^\//, ''), get(u)
+ end
+
+ def test_star_paths_are_greedy_but_not_too_much
+ rs.draw do
+ match "/(*filters).:format", :to => lambda { |env|
+ x = JSON.dump env["action_dispatch.request.path_parameters"]
+ [200, {}, [x]]
+ }
+ end
+
+ expected = { "filters" => "ne_27.065938,-80.6092/sw_25.489856,-82",
+ "format" => "542794" }
+ u = URI('http://example.org/ne_27.065938,-80.6092/sw_25.489856,-82.542794')
+ assert_equal expected, JSON.parse(get(u))
+ end
+
def test_regexp_precidence
@rs.draw do
match '/whois/:domain', :constraints => {
diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb
index c957df88b3..ecba9fed22 100644
--- a/actionpack/test/controller/test_case_test.rb
+++ b/actionpack/test/controller/test_case_test.rb
@@ -119,6 +119,7 @@ XML
def test_assigns
@foo = "foo"
+ @foo_hash = {:foo => :bar}
render :nothing => true
end
@@ -292,6 +293,10 @@ XML
assert_equal "foo", assigns("foo")
assert_equal "foo", assigns[:foo]
assert_equal "foo", assigns["foo"]
+
+ # but the assigned variable should not have its own keys stringified
+ expected_hash = { :foo => :bar }
+ assert_equal expected_hash, assigns(:foo_hash)
end
def test_view_assigns
diff --git a/actionpack/test/dispatch/callbacks_test.rb b/actionpack/test/dispatch/callbacks_test.rb
index eed2eca2ab..f767b07e75 100644
--- a/actionpack/test/dispatch/callbacks_test.rb
+++ b/actionpack/test/dispatch/callbacks_test.rb
@@ -27,6 +27,12 @@ class DispatcherTest < ActiveSupport::TestCase
dispatch
assert_equal 4, Foo.a
assert_equal 4, Foo.b
+
+ dispatch do |env|
+ raise "error"
+ end rescue nil
+ assert_equal 6, Foo.a
+ assert_equal 6, Foo.b
end
def test_to_prepare_and_cleanup_delegation
@@ -44,8 +50,9 @@ class DispatcherTest < ActiveSupport::TestCase
private
def dispatch(&block)
- @dispatcher ||= ActionDispatch::Callbacks.new(block || DummyApp.new)
- @dispatcher.call({'rack.input' => StringIO.new('')})
+ ActionDispatch::Callbacks.new(block || DummyApp.new).call(
+ {'rack.input' => StringIO.new('')}
+ )
end
end
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index c3c1c12e82..563c6efe0d 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -2087,7 +2087,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
def test_named_routes_collision_is_avoided_unless_explicitly_given_as
assert_equal "/c/1", routes_collision_path(1)
- assert_equal "/fc", routes_forced_collision_path
+ assert_equal "/fc/1", routes_forced_collision_path(1)
end
def test_redirect_argument_error
diff --git a/actionpack/test/dispatch/static_test.rb b/actionpack/test/dispatch/static_test.rb
index b7a53353a9..092ca3e20a 100644
--- a/actionpack/test/dispatch/static_test.rb
+++ b/actionpack/test/dispatch/static_test.rb
@@ -1,5 +1,6 @@
# encoding: utf-8
require 'abstract_unit'
+require 'rbconfig'
module StaticTests
def test_serves_dynamic_content
@@ -35,6 +36,87 @@ module StaticTests
assert_html "means hello in Japanese\n", get("/foo/#{Rack::Utils.escape("こんにちは.html")}")
end
+
+ def test_serves_static_file_with_exclamation_mark_in_filename
+ with_static_file "/foo/foo!bar.html" do |file|
+ assert_html file, get("/foo/foo%21bar.html")
+ assert_html file, get("/foo/foo!bar.html")
+ end
+ end
+
+ def test_serves_static_file_with_dollar_sign_in_filename
+ with_static_file "/foo/foo$bar.html" do |file|
+ assert_html file, get("/foo/foo%24bar.html")
+ assert_html file, get("/foo/foo$bar.html")
+ end
+ end
+
+ def test_serves_static_file_with_ampersand_in_filename
+ with_static_file "/foo/foo&bar.html" do |file|
+ assert_html file, get("/foo/foo%26bar.html")
+ assert_html file, get("/foo/foo&bar.html")
+ end
+ end
+
+ def test_serves_static_file_with_apostrophe_in_filename
+ with_static_file "/foo/foo'bar.html" do |file|
+ assert_html file, get("/foo/foo%27bar.html")
+ assert_html file, get("/foo/foo'bar.html")
+ end
+ end
+
+ def test_serves_static_file_with_parentheses_in_filename
+ with_static_file "/foo/foo(bar).html" do |file|
+ assert_html file, get("/foo/foo%28bar%29.html")
+ assert_html file, get("/foo/foo(bar).html")
+ end
+ end
+
+ def test_serves_static_file_with_plus_sign_in_filename
+ with_static_file "/foo/foo+bar.html" do |file|
+ assert_html file, get("/foo/foo%2Bbar.html")
+ assert_html file, get("/foo/foo+bar.html")
+ end
+ end
+
+ def test_serves_static_file_with_comma_in_filename
+ with_static_file "/foo/foo,bar.html" do |file|
+ assert_html file, get("/foo/foo%2Cbar.html")
+ assert_html file, get("/foo/foo,bar.html")
+ end
+ end
+
+ def test_serves_static_file_with_semi_colon_in_filename
+ with_static_file "/foo/foo;bar.html" do |file|
+ assert_html file, get("/foo/foo%3Bbar.html")
+ assert_html file, get("/foo/foo;bar.html")
+ end
+ end
+
+ def test_serves_static_file_with_at_symbol_in_filename
+ with_static_file "/foo/foo@bar.html" do |file|
+ assert_html file, get("/foo/foo%40bar.html")
+ assert_html file, get("/foo/foo@bar.html")
+ end
+ end
+
+ # Windows doesn't allow \ / : * ? " < > | in filenames
+ unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
+ def test_serves_static_file_with_colon
+ with_static_file "/foo/foo:bar.html" do |file|
+ assert_html file, get("/foo/foo%3Abar.html")
+ assert_html file, get("/foo/foo:bar.html")
+ end
+ end
+
+ def test_serves_static_file_with_asterisk
+ with_static_file "/foo/foo*bar.html" do |file|
+ assert_html file, get("/foo/foo%2Abar.html")
+ assert_html file, get("/foo/foo*bar.html")
+ end
+ end
+ end
+
private
def assert_html(body, response)
@@ -45,6 +127,14 @@ module StaticTests
def get(path)
Rack::MockRequest.new(@app).request("GET", path)
end
+
+ def with_static_file(file)
+ path = "#{FIXTURE_LOAD_PATH}/public" + file
+ File.open(path, "wb+") { |f| f.write(file) }
+ yield file
+ ensure
+ File.delete(path)
+ end
end
class StaticTest < ActiveSupport::TestCase
diff --git a/actionpack/test/fixtures/with_format.json.erb b/actionpack/test/fixtures/with_format.json.erb
new file mode 100644
index 0000000000..a7f480ab1d
--- /dev/null
+++ b/actionpack/test/fixtures/with_format.json.erb
@@ -0,0 +1 @@
+<%= render :partial => 'missing', :formats => [:json] %>
diff --git a/actionpack/test/template/form_collections_helper_test.rb b/actionpack/test/template/form_collections_helper_test.rb
index a4aea8ca56..4d878635ef 100644
--- a/actionpack/test/template/form_collections_helper_test.rb
+++ b/actionpack/test/template/form_collections_helper_test.rb
@@ -123,6 +123,19 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
end
+ test 'collection radio with block helpers allows access to the current object item in the collection to access extra properties' do
+ with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b|
+ b.label(:class => b.object) { b.radio_button + b.text }
+ end
+
+ assert_select 'label.true[for=user_active_true]', 'true' do
+ assert_select 'input#user_active_true[type=radio]'
+ end
+ assert_select 'label.false[for=user_active_false]', 'false' do
+ assert_select 'input#user_active_false[type=radio]'
+ end
+ end
+
test 'collection radio buttons with fields for' do
collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')]
@output_buffer = fields_for(:post) do |p|
@@ -298,4 +311,17 @@ class FormCollectionsHelperTest < ActionView::TestCase
assert_select 'input#user_active_false[type=checkbox]'
end
end
+
+ test 'collection check boxes with block helpers allows access to the current object item in the collection to access extra properties' do
+ with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b|
+ b.label(:class => b.object) { b.check_box + b.text }
+ end
+
+ assert_select 'label.true[for=user_active_true]', 'true' do
+ assert_select 'input#user_active_true[type=checkbox]'
+ end
+ assert_select 'label.false[for=user_active_false]', 'false' do
+ assert_select 'input#user_active_false[type=checkbox]'
+ end
+ end
end
diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb
index a32525c485..6b8d62df62 100644
--- a/actionpack/test/template/form_options_helper_test.rb
+++ b/actionpack/test/template/form_options_helper_test.rb
@@ -182,16 +182,16 @@ class FormOptionsHelperTest < ActionView::TestCase
def test_hash_options_for_select
assert_dom_equal(
- "<option value=\"&lt;Kroner&gt;\">&lt;DKR&gt;</option>\n<option value=\"Dollar\">$</option>",
- options_for_select("$" => "Dollar", "<DKR>" => "<Kroner>").split("\n").sort.join("\n")
+ "<option value=\"Dollar\">$</option>\n<option value=\"&lt;Kroner&gt;\">&lt;DKR&gt;</option>",
+ options_for_select("$" => "Dollar", "<DKR>" => "<Kroner>").split("\n").join("\n")
)
assert_dom_equal(
- "<option value=\"&lt;Kroner&gt;\">&lt;DKR&gt;</option>\n<option value=\"Dollar\" selected=\"selected\">$</option>",
- options_for_select({ "$" => "Dollar", "<DKR>" => "<Kroner>" }, "Dollar").split("\n").sort.join("\n")
+ "<option value=\"Dollar\" selected=\"selected\">$</option>\n<option value=\"&lt;Kroner&gt;\">&lt;DKR&gt;</option>",
+ options_for_select({ "$" => "Dollar", "<DKR>" => "<Kroner>" }, "Dollar").split("\n").join("\n")
)
assert_dom_equal(
- "<option value=\"&lt;Kroner&gt;\" selected=\"selected\">&lt;DKR&gt;</option>\n<option value=\"Dollar\" selected=\"selected\">$</option>",
- options_for_select({ "$" => "Dollar", "<DKR>" => "<Kroner>" }, [ "Dollar", "<Kroner>" ]).split("\n").sort.join("\n")
+ "<option value=\"Dollar\" selected=\"selected\">$</option>\n<option value=\"&lt;Kroner&gt;\" selected=\"selected\">&lt;DKR&gt;</option>",
+ options_for_select({ "$" => "Dollar", "<DKR>" => "<Kroner>" }, [ "Dollar", "<Kroner>" ]).split("\n").join("\n")
)
end
@@ -1056,36 +1056,36 @@ class FormOptionsHelperTest < ActionView::TestCase
end
def test_option_html_attributes_from_without_hash
- assert_dom_equal(
- "",
+ assert_equal(
+ {},
option_html_attributes([ 'foo', 'bar' ])
)
end
def test_option_html_attributes_with_single_element_hash
- assert_dom_equal(
- " class=\"fancy\"",
+ assert_equal(
+ {:class => 'fancy'},
option_html_attributes([ 'foo', 'bar', { :class => 'fancy' } ])
)
end
def test_option_html_attributes_with_multiple_element_hash
- assert_dom_equal(
- " class=\"fancy\" onclick=\"alert('Hello World');\"",
+ assert_equal(
+ {:class => 'fancy', 'onclick' => "alert('Hello World');"},
option_html_attributes([ 'foo', 'bar', { :class => 'fancy', 'onclick' => "alert('Hello World');" } ])
)
end
def test_option_html_attributes_with_multiple_hashes
- assert_dom_equal(
- " class=\"fancy\" onclick=\"alert('Hello World');\"",
+ assert_equal(
+ {:class => 'fancy', 'onclick' => "alert('Hello World');"},
option_html_attributes([ 'foo', 'bar', { :class => 'fancy' }, { 'onclick' => "alert('Hello World');" } ])
)
end
def test_option_html_attributes_with_special_characters
- assert_dom_equal(
- " onclick=\"alert(&quot;&lt;code&gt;&quot;)\"",
+ assert_equal(
+ {:onclick => "alert(&quot;&lt;code&gt;&quot;)"},
option_html_attributes([ 'foo', 'bar', { :onclick => %(alert("<code>")) } ])
)
end
@@ -1100,6 +1100,24 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
+ def test_grouped_collection_select_with_selected
+ @post = Post.new
+
+ assert_dom_equal(
+ %Q{<select id="post_origin" name="post[origin]"><optgroup label="&lt;Africa&gt;"><option value="&lt;sa&gt;">&lt;South Africa&gt;</option>\n<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk" selected="selected">Denmark</option>\n<option value="ie">Ireland</option></optgroup></select>},
+ grouped_collection_select("post", "origin", dummy_continents, :countries, :continent_name, :country_id, :country_name, :selected => 'dk')
+ )
+ end
+
+ def test_grouped_collection_select_with_disabled_value
+ @post = Post.new
+
+ assert_dom_equal(
+ %Q{<select id="post_origin" name="post[origin]"><optgroup label="&lt;Africa&gt;"><option value="&lt;sa&gt;">&lt;South Africa&gt;</option>\n<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option disabled="disabled" value="dk">Denmark</option>\n<option value="ie">Ireland</option></optgroup></select>},
+ grouped_collection_select("post", "origin", dummy_continents, :countries, :continent_name, :country_id, :country_name, :disabled => 'dk')
+ )
+ end
+
def test_grouped_collection_select_under_fields_for
@post = Post.new
@post.origin = 'dk'
diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb
index 5d3dc73ed2..e4ce756bf8 100644
--- a/actionpack/test/template/render_test.rb
+++ b/actionpack/test/template/render_test.rb
@@ -51,6 +51,13 @@ module RenderTestCases
assert_match "<error>No Comment</error>", @view.render(:template => "comments/empty", :formats => [:xml])
end
+ def test_render_template_with_a_missing_partial_of_another_format
+ assert_raise ActionView::Template::Error, "Missing partial /missing with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder]}" do
+ @view.lookup_context.freeze_formats([:html])
+ @view.render(:template => "with_format", :formats => [:json])
+ end
+ end
+
def test_render_file_with_locale
assert_equal "<h1>Kein Kommentar</h1>", @view.render(:file => "comments/empty", :locale => [:de])
assert_equal "<h1>Kein Kommentar</h1>", @view.render(:file => "comments/empty", :locale => :de)
@@ -299,6 +306,12 @@ module RenderTestCases
ActionView::Template.register_template_handler :foo, CustomHandler
assert_equal 'source: "Hello, <%= name %>!"', @view.render(:inline => "Hello, <%= name %>!", :locals => { :name => "Josh" }, :type => :foo)
end
+
+ def test_render_knows_about_types_registered_when_extensions_are_checked_earlier_in_initialization
+ ActionView::Template::Handlers.extensions
+ ActionView::Template.register_template_handler :foo, CustomHandler
+ assert ActionView::Template::Handlers.extensions.include?(:foo)
+ end
def test_render_ignores_templates_with_malformed_template_handlers
ActiveSupport::Deprecation.silence do
diff --git a/actionpack/test/template/template_test.rb b/actionpack/test/template/template_test.rb
index 3084527f70..63f1d3a6c0 100644
--- a/actionpack/test/template/template_test.rb
+++ b/actionpack/test/template/template_test.rb
@@ -11,6 +11,8 @@ class TestERBTemplate < ActiveSupport::TestCase
def find_template(*args)
end
+
+ attr_writer :formats
end
class Context
diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md
index 258c3681f6..e4779c90d8 100644
--- a/activemodel/CHANGELOG.md
+++ b/activemodel/CHANGELOG.md
@@ -1,3 +1,5 @@
+* `AM::Errors#to_json`: support `:full_messages` parameter *Bogdan Gusiev*
+
* Trim down Active Model API by removing `valid?` and `errors.full_messages` *José Valim*
## Rails 3.2.0 (January 20, 2012) ##
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index e548aa975d..042f9cd7e2 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -206,12 +206,23 @@ module ActiveModel
end
# Returns an Hash that can be used as the JSON representation for this object.
+ # Options:
+ # * <tt>:full_messages</tt> - determines if json object should contain
+ # full messages or not. Default: <tt>false</tt>.
def as_json(options=nil)
- to_hash
+ to_hash(options && options[:full_messages])
end
- def to_hash
- messages.dup
+ def to_hash(full_messages = false)
+ if full_messages
+ messages = {}
+ self.messages.each do |attribute, array|
+ messages[attribute] = array.map{|message| full_message(attribute, message) }
+ end
+ messages
+ else
+ self.messages.dup
+ end
end
# Adds +message+ to the error messages on +attribute+. More than one error can be added to the same
diff --git a/activemodel/lib/active_model/mass_assignment_security.rb b/activemodel/lib/active_model/mass_assignment_security.rb
index 13495d6786..95de039676 100644
--- a/activemodel/lib/active_model/mass_assignment_security.rb
+++ b/activemodel/lib/active_model/mass_assignment_security.rb
@@ -226,12 +226,12 @@ module ActiveModel
protected
- def sanitize_for_mass_assignment(attributes, role = :default)
+ def sanitize_for_mass_assignment(attributes, role = nil)
_mass_assignment_sanitizer.sanitize(attributes, mass_assignment_authorizer(role))
end
- def mass_assignment_authorizer(role = :default)
- self.class.active_authorizer[role]
+ def mass_assignment_authorizer(role)
+ self.class.active_authorizer[role || :default]
end
end
end
diff --git a/activemodel/lib/active_model/validations/length.rb b/activemodel/lib/active_model/validations/length.rb
index 0bbd81a984..f1beddf6d4 100644
--- a/activemodel/lib/active_model/validations/length.rb
+++ b/activemodel/lib/active_model/validations/length.rb
@@ -1,5 +1,3 @@
-require "active_support/core_ext/string/encoding"
-
module ActiveModel
# == Active Model Length Validator
diff --git a/activemodel/test/cases/errors_test.rb b/activemodel/test/cases/errors_test.rb
index 7a610e0c2c..3bc0d58351 100644
--- a/activemodel/test/cases/errors_test.rb
+++ b/activemodel/test/cases/errors_test.rb
@@ -184,6 +184,16 @@ class ErrorsTest < ActiveModel::TestCase
assert_equal ["is invalid"], hash[:email]
end
+ test 'should return a JSON hash representation of the errors with full messages' do
+ person = Person.new
+ person.errors.add(:name, "can not be blank")
+ person.errors.add(:name, "can not be nil")
+ person.errors.add(:email, "is invalid")
+ hash = person.errors.as_json(:full_messages => true)
+ assert_equal ["name can not be blank", "name can not be nil"], hash[:name]
+ assert_equal ["email is invalid"], hash[:email]
+ end
+
test "generate_message should work without i18n_scope" do
person = Person.new
assert !Person.respond_to?(:i18n_scope)
diff --git a/activemodel/test/cases/mass_assignment_security_test.rb b/activemodel/test/cases/mass_assignment_security_test.rb
index be07e59a2f..a197dbe748 100644
--- a/activemodel/test/cases/mass_assignment_security_test.rb
+++ b/activemodel/test/cases/mass_assignment_security_test.rb
@@ -19,6 +19,13 @@ class MassAssignmentSecurityTest < ActiveModel::TestCase
assert_equal expected, sanitized
end
+ def test_attribute_protection_when_role_is_nil
+ user = User.new
+ expected = { "name" => "John Smith", "email" => "john@smith.com" }
+ sanitized = user.sanitize_for_mass_assignment(expected.merge("admin" => true), nil)
+ assert_equal expected, sanitized
+ end
+
def test_only_moderator_role_attribute_accessible
user = SpecialUser.new
expected = { "name" => "John Smith", "email" => "john@smith.com" }
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index 3de5af22c5..f69f803513 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -130,7 +130,7 @@
* PostgreSQL hstore types are automatically deserialized from the database.
-## Rails 3.2.1 (unreleased) ##
+## Rails 3.2.1 (January 26, 2012) ##
* The threshold for auto EXPLAIN is ignored if there's no logger. *fxn*
diff --git a/activerecord/lib/active_record/attribute_methods/before_type_cast.rb b/activerecord/lib/active_record/attribute_methods/before_type_cast.rb
index bde11d0494..d4f529acbf 100644
--- a/activerecord/lib/active_record/attribute_methods/before_type_cast.rb
+++ b/activerecord/lib/active_record/attribute_methods/before_type_cast.rb
@@ -20,11 +20,7 @@ module ActiveRecord
# Handle *_before_type_cast for method_missing.
def attribute_before_type_cast(attribute_name)
- if attribute_name == 'id'
- read_attribute_before_type_cast(self.class.primary_key)
- else
- read_attribute_before_type_cast(attribute_name)
- end
+ read_attribute_before_type_cast(attribute_name)
end
end
end
diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb
index 40e4a97e73..433d508357 100644
--- a/activerecord/lib/active_record/attribute_methods/dirty.rb
+++ b/activerecord/lib/active_record/attribute_methods/dirty.rb
@@ -55,12 +55,12 @@ module ActiveRecord
# The attribute already has an unsaved change.
if attribute_changed?(attr)
old = @changed_attributes[attr]
- @changed_attributes.delete(attr) unless field_changed?(attr, old, value)
+ @changed_attributes.delete(attr) unless _field_changed?(attr, old, value)
else
old = clone_attribute_value(:read_attribute, attr)
# Save Time objects as TimeWithZone if time_zone_aware_attributes == true
old = old.in_time_zone if clone_with_time_zone_conversion_attribute?(attr, old)
- @changed_attributes[attr] = old if field_changed?(attr, old, value)
+ @changed_attributes[attr] = old if _field_changed?(attr, old, value)
end
# Carry on.
@@ -77,7 +77,7 @@ module ActiveRecord
end
end
- def field_changed?(attr, old, value)
+ def _field_changed?(attr, old, value)
if column = column_for_attribute(attr)
if column.number? && column.null && (old.nil? || old == 0) && value.blank?
# For nullable numeric columns, NULL gets stored in database for blank (i.e. '') values.
diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb
index 2e1a2dc3ef..8e0b3e1402 100644
--- a/activerecord/lib/active_record/attribute_methods/primary_key.rb
+++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb
@@ -1,3 +1,5 @@
+require 'set'
+
module ActiveRecord
module AttributeMethods
module PrimaryKey
@@ -24,6 +26,11 @@ module ActiveRecord
query_attribute(self.class.primary_key)
end
+ # Returns the primary key value before type cast
+ def id_before_type_cast
+ read_attribute_before_type_cast(self.class.primary_key)
+ end
+
protected
def attribute_method?(attr_name)
@@ -45,8 +52,10 @@ module ActiveRecord
end
end
+ ID_ATTRIBUTE_METHODS = %w(id id= id? id_before_type_cast).to_set
+
def dangerous_attribute_method?(method_name)
- super && !['id', 'id=', 'id?'].include?(method_name)
+ super && !ID_ATTRIBUTE_METHODS.include?(method_name)
end
# Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
index d69f02d504..06b9bc5765 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -328,16 +328,18 @@ module ActiveRecord
# ActiveRecord::Base.connection_handler. Active Record models use this to
# determine that connection pool that they should use.
class ConnectionHandler
- attr_reader :connection_pools
-
- def initialize(pools = {})
+ def initialize(pools = Hash.new { |h,k| h[k] = {} })
@connection_pools = pools
- @class_to_pool = {}
+ @class_to_pool = Hash.new { |h,k| h[k] = {} }
+ end
+
+ def connection_pools
+ @connection_pools[Process.pid]
end
def establish_connection(name, spec)
- @connection_pools[spec] ||= ConnectionAdapters::ConnectionPool.new(spec)
- @class_to_pool[name] = @connection_pools[spec]
+ set_pool_for_spec spec, ConnectionAdapters::ConnectionPool.new(spec)
+ set_class_to_pool name, connection_pools[spec]
end
# Returns true if there are any active connections among the connection
@@ -350,21 +352,21 @@ module ActiveRecord
# and also returns connections to the pool cached by threads that are no
# longer alive.
def clear_active_connections!
- @connection_pools.each_value {|pool| pool.release_connection }
+ connection_pools.each_value {|pool| pool.release_connection }
end
# Clears the cache which maps classes.
def clear_reloadable_connections!
- @connection_pools.each_value {|pool| pool.clear_reloadable_connections! }
+ connection_pools.each_value {|pool| pool.clear_reloadable_connections! }
end
def clear_all_connections!
- @connection_pools.each_value {|pool| pool.disconnect! }
+ connection_pools.each_value {|pool| pool.disconnect! }
end
# Verify active connections.
def verify_active_connections! #:nodoc:
- @connection_pools.each_value {|pool| pool.verify_active_connections! }
+ connection_pools.each_value {|pool| pool.verify_active_connections! }
end
# Locate the connection of the nearest super class. This can be an
@@ -388,21 +390,53 @@ module ActiveRecord
# can be used as an argument for establish_connection, for easily
# re-establishing the connection.
def remove_connection(klass)
- pool = @class_to_pool.delete(klass.name)
+ pool = class_to_pool.delete(klass.name)
return nil unless pool
- @connection_pools.delete pool.spec
+ connection_pools.delete pool.spec
pool.automatic_reconnect = false
pool.disconnect!
pool.spec.config
end
def retrieve_connection_pool(klass)
- pool = @class_to_pool[klass.name]
+ pool = get_pool_for_class klass.name
return pool if pool
return nil if ActiveRecord::Model == klass
retrieve_connection_pool klass.active_record_super
end
+
+ private
+
+ def class_to_pool
+ @class_to_pool[Process.pid]
+ end
+
+ def set_pool_for_spec(spec, pool)
+ @connection_pools[Process.pid][spec] = pool
+ end
+
+ def set_class_to_pool(name, pool)
+ @class_to_pool[Process.pid][name] = pool
+ pool
+ end
+
+ def get_pool_for_class(klass)
+ @class_to_pool[Process.pid].fetch(klass) {
+ c_to_p = @class_to_pool.values.find { |class_to_pool|
+ class_to_pool[klass]
+ }
+
+ if c_to_p
+ pool = c_to_p[klass]
+ pool = ConnectionAdapters::ConnectionPool.new pool.spec
+ set_pool_for_spec pool.spec, pool
+ set_class_to_pool klass, pool
+ else
+ set_class_to_pool klass, nil
+ end
+ }
+ end
end
class ConnectionManagement
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
index ea6071ea46..6bac05191d 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -163,7 +163,7 @@ module ActiveRecord
yield td if block_given?
if options[:force] && table_exists?(table_name)
- drop_table(table_name)
+ drop_table(table_name, options)
end
create_sql = "CREATE#{' TEMPORARY' if options[:temporary]} TABLE "
@@ -294,7 +294,7 @@ module ActiveRecord
end
# Drops a table from the database.
- def drop_table(table_name)
+ def drop_table(table_name, options = {})
execute "DROP TABLE #{quote_table_name(table_name)}"
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
index dd421b2054..c6af682d28 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -13,21 +13,24 @@ module ActiveRecord
autoload :Column
autoload :ConnectionSpecification
- autoload_under 'abstract' do
- autoload :IndexDefinition, 'active_record/connection_adapters/abstract/schema_definitions'
- autoload :ColumnDefinition, 'active_record/connection_adapters/abstract/schema_definitions'
- autoload :TableDefinition, 'active_record/connection_adapters/abstract/schema_definitions'
- autoload :Table, 'active_record/connection_adapters/abstract/schema_definitions'
+ autoload_at 'active_record/connection_adapters/abstract/schema_definitions' do
+ autoload :IndexDefinition
+ autoload :ColumnDefinition
+ autoload :TableDefinition
+ autoload :Table
+ end
+
+ autoload_at 'active_record/connection_adapters/abstract/connection_pool' do
+ autoload :ConnectionHandler
+ autoload :ConnectionManagement
+ end
+ autoload_under 'abstract' do
autoload :SchemaStatements
autoload :DatabaseStatements
autoload :DatabaseLimits
autoload :Quoting
-
autoload :ConnectionPool
- autoload :ConnectionHandler, 'active_record/connection_adapters/abstract/connection_pool'
- autoload :ConnectionManagement, 'active_record/connection_adapters/abstract/connection_pool'
-
autoload :QueryCache
end
@@ -163,7 +166,7 @@ module ActiveRecord
# Returns a bind substitution value given a +column+ and list of current
# +binds+
def substitute_at(column, index)
- Arel.sql '?'
+ Arel::Nodes::BindParam.new '?'
end
# REFERENTIAL INTEGRITY ====================================
diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
index 321d500da2..5ab9c24999 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
@@ -66,7 +66,7 @@ module ActiveRecord
end
def substitute_at(column, index)
- Arel.sql "\0"
+ Arel::Nodes::BindParam.new "\0"
end
# CONNECTION MANAGEMENT ====================================
diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
index 5905242747..724dbff1f0 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -119,7 +119,7 @@ module ActiveRecord
private
def cache
- @cache[$$]
+ @cache[Process.pid]
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index fd5cbd3f9a..3925a9634e 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -359,7 +359,7 @@ module ActiveRecord
private
def cache
- @cache[$$]
+ @cache[Process.pid]
end
def dealloc(key)
@@ -721,7 +721,7 @@ module ActiveRecord
end
def substitute_at(column, index)
- Arel.sql("$#{index + 1}")
+ Arel::Nodes::BindParam.new "$#{index + 1}"
end
class Result < ActiveRecord::Result
@@ -1032,26 +1032,46 @@ module ActiveRecord
def pk_and_sequence_for(table) #:nodoc:
# First try looking for a sequence with a dependency on the
# given table's primary key.
- result = exec_query(<<-end_sql, 'SCHEMA').rows.first
- SELECT attr.attname, ns.nspname, seq.relname
- FROM pg_class seq
- INNER JOIN pg_depend dep ON seq.oid = dep.objid
- INNER JOIN pg_attribute attr ON attr.attrelid = dep.refobjid AND attr.attnum = dep.refobjsubid
- INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = cons.conkey[1]
- INNER JOIN pg_namespace ns ON seq.relnamespace = ns.oid
- WHERE seq.relkind = 'S'
- AND cons.contype = 'p'
- AND dep.refobjid = '#{quote_table_name(table)}'::regclass
+ result = query(<<-end_sql, 'PK and serial sequence')[0]
+ SELECT attr.attname, seq.relname
+ FROM pg_class seq,
+ pg_attribute attr,
+ pg_depend dep,
+ pg_namespace name,
+ pg_constraint cons
+ WHERE seq.oid = dep.objid
+ AND seq.relkind = 'S'
+ AND attr.attrelid = dep.refobjid
+ AND attr.attnum = dep.refobjsubid
+ AND attr.attrelid = cons.conrelid
+ AND attr.attnum = cons.conkey[1]
+ AND cons.contype = 'p'
+ AND dep.refobjid = '#{quote_table_name(table)}'::regclass
end_sql
- # [primary_key, sequence]
- if result.second == 'public' then
- sequence = result.last
- else
- sequence = result.second+'.'+result.last
+ if result.nil? or result.empty?
+ # If that fails, try parsing the primary key's default value.
+ # Support the 7.x and 8.0 nextval('foo'::text) as well as
+ # the 8.1+ nextval('foo'::regclass).
+ result = query(<<-end_sql, 'PK and custom sequence')[0]
+ SELECT attr.attname,
+ CASE
+ WHEN split_part(def.adsrc, '''', 2) ~ '.' THEN
+ substr(split_part(def.adsrc, '''', 2),
+ strpos(split_part(def.adsrc, '''', 2), '.')+1)
+ ELSE split_part(def.adsrc, '''', 2)
+ END
+ FROM pg_class t
+ JOIN pg_attribute attr ON (t.oid = attrelid)
+ JOIN pg_attrdef def ON (adrelid = attrelid AND adnum = attnum)
+ JOIN pg_constraint cons ON (conrelid = adrelid AND adnum = conkey[1])
+ WHERE t.oid = '#{quote_table_name(table)}'::regclass
+ AND cons.contype = 'p'
+ AND def.adsrc ~* 'nextval'
+ end_sql
end
- [result.first, sequence]
+ [result.first, result.last]
rescue
nil
end
@@ -1238,7 +1258,11 @@ module ActiveRecord
# prepared statements whose return value may have changed is
# FEATURE_NOT_SUPPORTED. Check here for more details:
# http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/cache/plancache.c#l573
- code = e.result.result_error_field(PGresult::PG_DIAG_SQLSTATE)
+ begin
+ code = e.result.result_error_field(PGresult::PG_DIAG_SQLSTATE)
+ rescue
+ raise e
+ end
if FEATURE_NOT_SUPPORTED == code
@statements.delete sql_key(sql)
retry
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
index 55eca48efe..b73f7ae876 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
@@ -1,6 +1,5 @@
require 'active_record/connection_adapters/abstract_adapter'
require 'active_record/connection_adapters/statement_pool'
-require 'active_support/core_ext/string/encoding'
module ActiveRecord
module ConnectionAdapters #:nodoc:
diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
index c4a4c0ad9a..3f90d25962 100644
--- a/activerecord/lib/active_record/core.rb
+++ b/activerecord/lib/active_record/core.rb
@@ -223,7 +223,7 @@ module ActiveRecord
@changed_attributes = {}
self.class.column_defaults.each do |attr, orig_value|
- @changed_attributes[attr] = orig_value if field_changed?(attr, orig_value, @attributes[attr])
+ @changed_attributes[attr] = orig_value if _field_changed?(attr, orig_value, @attributes[attr])
end
@aggregation_cache = {}
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index 821410f42c..14bb0a724e 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -162,6 +162,9 @@ db_namespace = namespace :db do
else
raise "unknown schema format #{ActiveRecord::Base.schema_format}"
end
+ # Allow this task to be called as many times as required. An example is the
+ # migrate:redo task, which calls other two internally that depend on this one.
+ db_namespace['_dump'].reenable
end
namespace :migrate do
@@ -204,11 +207,12 @@ db_namespace = namespace :db do
next # means "return" for rake task
end
db_list = ActiveRecord::Base.connection.select_values("SELECT version FROM #{ActiveRecord::Migrator.schema_migrations_table_name}")
+ db_list.map! { |version| "%.3d" % version }
file_list = []
ActiveRecord::Migrator.migrations_paths.each do |path|
Dir.foreach(path) do |file|
- # only files matching "20091231235959_some_name.rb" pattern
- if match_data = /^(\d{14})_(.+)\.rb$/.match(file)
+ # match "20091231235959_some_name.rb" and "001_some_name.rb" pattern
+ if match_data = /^(\d{3,})_(.+)\.rb$/.match(file)
status = db_list.delete(match_data[1]) ? 'up' : 'down'
file_list << [status, match_data[1], match_data[2].humanize]
end
@@ -612,7 +616,7 @@ def firebird_db_string(config)
end
def set_psql_env(config)
- ENV['PGHOST'] = config['host'] if config['host']
+ ENV['PGHOST'] = config['host'] if config['host']
ENV['PGPORT'] = config['port'].to_s if config['port']
ENV['PGPASSWORD'] = config['password'].to_s if config['password']
ENV['PGUSER'] = config['username'].to_s if config['username']
diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb
index 18670b4177..18c81d2b09 100644
--- a/activerecord/test/cases/adapters/postgresql/schema_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb
@@ -24,6 +24,8 @@ class SchemaTest < ActiveRecord::TestCase
'moment timestamp without time zone default now()'
]
PK_TABLE_NAME = 'table_with_pk'
+ UNMATCHED_SEQUENCE_NAME = 'unmatched_primary_key_default_value_seq'
+ UNMATCHED_PK_TABLE_NAME = 'table_with_unmatched_sequence_for_pk'
class Thing1 < ActiveRecord::Base
self.table_name = "test_schema.things"
@@ -60,6 +62,8 @@ class SchemaTest < ActiveRecord::TestCase
@connection.execute "CREATE INDEX #{INDEX_D_NAME} ON #{SCHEMA_NAME}.#{TABLE_NAME} USING btree (#{INDEX_D_COLUMN} DESC);"
@connection.execute "CREATE INDEX #{INDEX_D_NAME} ON #{SCHEMA2_NAME}.#{TABLE_NAME} USING btree (#{INDEX_D_COLUMN} DESC);"
@connection.execute "CREATE TABLE #{SCHEMA_NAME}.#{PK_TABLE_NAME} (id serial primary key)"
+ @connection.execute "CREATE SEQUENCE #{SCHEMA_NAME}.#{UNMATCHED_SEQUENCE_NAME}"
+ @connection.execute "CREATE TABLE #{SCHEMA_NAME}.#{UNMATCHED_PK_TABLE_NAME} (id integer NOT NULL DEFAULT nextval('#{SCHEMA_NAME}.#{UNMATCHED_SEQUENCE_NAME}'::regclass), CONSTRAINT unmatched_pkey PRIMARY KEY (id))"
end
def teardown
@@ -241,12 +245,12 @@ class SchemaTest < ActiveRecord::TestCase
def test_pk_and_sequence_for_with_schema_specified
[
%("#{SCHEMA_NAME}"."#{PK_TABLE_NAME}"),
- %(#{SCHEMA_NAME}."#{PK_TABLE_NAME}"),
- %(#{SCHEMA_NAME}.#{PK_TABLE_NAME})
+ %("#{SCHEMA_NAME}"."#{UNMATCHED_PK_TABLE_NAME}")
].each do |given|
pk, seq = @connection.pk_and_sequence_for(given)
assert_equal 'id', pk, "primary key should be found when table referenced as #{given}"
- assert_equal "#{SCHEMA_NAME}.#{PK_TABLE_NAME}_id_seq", seq, "sequence name should be found when table referenced as #{given}"
+ assert_equal "#{PK_TABLE_NAME}_id_seq", seq, "sequence name should be found when table referenced as #{given}" if given == %("#{SCHEMA_NAME}"."#{PK_TABLE_NAME}")
+ assert_equal "#{UNMATCHED_SEQUENCE_NAME}", seq, "sequence name should be found when table referenced as #{given}" if given == %("#{SCHEMA_NAME}"."#{UNMATCHED_PK_TABLE_NAME}")
end
end
diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb
index 3ac2a76b96..4078b7eb0b 100644
--- a/activerecord/test/cases/attribute_methods_test.rb
+++ b/activerecord/test/cases/attribute_methods_test.rb
@@ -121,6 +121,14 @@ class AttributeMethodsTest < ActiveRecord::TestCase
assert keyboard.respond_to?('id')
end
+ def test_id_before_type_cast_with_custom_primary_key
+ keyboard = Keyboard.create
+ keyboard.key_number = '10'
+ assert_equal '10', keyboard.id_before_type_cast
+ assert_equal nil, keyboard.read_attribute_before_type_cast('id')
+ assert_equal '10', keyboard.read_attribute_before_type_cast('key_number')
+ end
+
# Syck calls respond_to? before actually calling initialize
def test_respond_to_with_allocated_object
topic = Topic.allocate
diff --git a/activerecord/test/cases/connection_management_test.rb b/activerecord/test/cases/connection_management_test.rb
index 496cd78136..fe1b40d884 100644
--- a/activerecord/test/cases/connection_management_test.rb
+++ b/activerecord/test/cases/connection_management_test.rb
@@ -26,6 +26,27 @@ module ActiveRecord
assert ActiveRecord::Base.connection_handler.active_connections?
end
+ def test_connection_pool_per_pid
+ return skip('must support fork') unless Process.respond_to?(:fork)
+
+ object_id = ActiveRecord::Base.connection.object_id
+
+ rd, wr = IO.pipe
+
+ pid = fork {
+ rd.close
+ wr.write Marshal.dump ActiveRecord::Base.connection.object_id
+ wr.close
+ exit!
+ }
+
+ wr.close
+
+ Process.waitpid pid
+ assert_not_equal object_id, Marshal.load(rd.read)
+ rd.close
+ end
+
def test_app_delegation
manager = ConnectionManagement.new(@app)
diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb
index b1ce846218..54e0b40b4f 100644
--- a/activerecord/test/cases/dirty_test.rb
+++ b/activerecord/test/cases/dirty_test.rb
@@ -497,6 +497,20 @@ class DirtyTest < ActiveRecord::TestCase
assert !pirate.previous_changes.key?('created_on')
end
+ if ActiveRecord::Base.connection.supports_migrations?
+ class Testings < ActiveRecord::Base; end
+ def test_field_named_field
+ ActiveRecord::Base.connection.create_table :testings do |t|
+ t.string :field
+ end
+ assert_nothing_raised do
+ Testings.new.attributes
+ end
+ ensure
+ ActiveRecord::Base.connection.drop_table :testings rescue nil
+ end
+ end
+
private
def with_partial_updates(klass, on = true)
old = klass.partial_updates?
diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb
index e38a8387b4..2e1ccb72d8 100644
--- a/activesupport/lib/active_support/cache/mem_cache_store.rb
+++ b/activesupport/lib/active_support/cache/mem_cache_store.rb
@@ -6,7 +6,6 @@ rescue LoadError => e
end
require 'digest/md5'
-require 'active_support/core_ext/string/encoding'
module ActiveSupport
module Cache
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index 1834027e7b..6de49409e5 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -356,7 +356,7 @@ module ActiveSupport
#
def __run_callbacks(kind, object, &blk) #:nodoc:
name = __callback_runner_name(kind)
- unless object.respond_to?(name)
+ unless object.respond_to?(name, true)
str = object.send("_#{kind}_callbacks").compile
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
def #{name}() #{str} end
diff --git a/activesupport/lib/active_support/core_ext/object/blank.rb b/activesupport/lib/active_support/core_ext/object/blank.rb
index 7271671908..d67711f3b8 100644
--- a/activesupport/lib/active_support/core_ext/object/blank.rb
+++ b/activesupport/lib/active_support/core_ext/object/blank.rb
@@ -1,5 +1,4 @@
# encoding: utf-8
-require 'active_support/core_ext/string/encoding'
class Object
# An object is blank if it's false, empty, or a whitespace string.
diff --git a/activesupport/lib/active_support/core_ext/string.rb b/activesupport/lib/active_support/core_ext/string.rb
index 72522d395c..ab49af55bf 100644
--- a/activesupport/lib/active_support/core_ext/string.rb
+++ b/activesupport/lib/active_support/core_ext/string.rb
@@ -9,6 +9,5 @@ require 'active_support/core_ext/string/behavior'
require 'active_support/core_ext/string/interpolation'
require 'active_support/core_ext/string/output_safety'
require 'active_support/core_ext/string/exclude'
-require 'active_support/core_ext/string/encoding'
require 'active_support/core_ext/string/strip'
require 'active_support/core_ext/string/inquiry'
diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb
index 4f300329f5..dd2a21fe2a 100644
--- a/activesupport/lib/active_support/core_ext/time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -67,7 +67,7 @@ class Time
end
# Returns a new Time where one or more of the elements have been changed according to the +options+ parameter. The time options
- # (hour, minute, sec, usec) reset cascadingly, so if only the hour is passed, then minute, sec, and usec is set to 0. If the hour and
+ # (hour, min, sec, usec) reset cascadingly, so if only the hour is passed, then minute, sec, and usec is set to 0. If the hour and
# minute is passed, then sec and usec is set to 0.
def change(options)
::Time.send(
diff --git a/activesupport/lib/active_support/gzip.rb b/activesupport/lib/active_support/gzip.rb
index f7036315d6..420b965c87 100644
--- a/activesupport/lib/active_support/gzip.rb
+++ b/activesupport/lib/active_support/gzip.rb
@@ -1,6 +1,5 @@
require 'zlib'
require 'stringio'
-require 'active_support/core_ext/string/encoding'
module ActiveSupport
# A convenient wrapper for the zlib standard library that allows compression/decompression of strings with gzip.
diff --git a/activesupport/lib/active_support/ruby/shim.rb b/activesupport/lib/active_support/ruby/shim.rb
index 41fd866481..13e96b3596 100644
--- a/activesupport/lib/active_support/ruby/shim.rb
+++ b/activesupport/lib/active_support/ruby/shim.rb
@@ -12,5 +12,4 @@ require 'active_support/core_ext/date_time/conversions'
require 'active_support/core_ext/enumerable'
require 'active_support/core_ext/string/conversions'
require 'active_support/core_ext/string/interpolation'
-require 'active_support/core_ext/string/encoding'
require 'active_support/core_ext/time/conversions'
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
index c25d4a889e..a5f32d1a2c 100644
--- a/railties/CHANGELOG.md
+++ b/railties/CHANGELOG.md
@@ -1,5 +1,17 @@
## Rails 4.0.0 (unreleased) ##
+* Allow to set class that will be used to run as a console, other than IRB, with `Rails.application.config.console=`. It's best to add it to `console` block. *Piotr Sarnacki*
+
+ Example:
+
+ # it can be added to config/application.rb
+ console do
+ # this block is called only when running console,
+ # so we can safely require pry here
+ require "pry"
+ config.console = Pry
+ end
+
* Add convenience `hide!` method to Rails generators to hide current generator
namespace from showing when running `rails generate`. *Carlos Antonio da Silva*
diff --git a/railties/guides/assets/stylesheets/fixes.css b/railties/guides/assets/stylesheets/fixes.css
index 54efa5b9b7..bf86b29efa 100644
--- a/railties/guides/assets/stylesheets/fixes.css
+++ b/railties/guides/assets/stylesheets/fixes.css
@@ -12,5 +12,5 @@
.syntaxhighlighter table thead,
.syntaxhighlighter table caption,
.syntaxhighlighter textarea {
- line-height: 1.2em !important;
+ line-height: 1.25em !important;
}
diff --git a/railties/guides/assets/stylesheets/main.css b/railties/guides/assets/stylesheets/main.css
index 4a775f632c..90723cc8e1 100644
--- a/railties/guides/assets/stylesheets/main.css
+++ b/railties/guides/assets/stylesheets/main.css
@@ -81,6 +81,7 @@ body {
font-size: 87.5%;
line-height: 1.5em;
background: #222;
+ min-width: 69em;
color: #999;
}
diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile
index 15d24f9ac1..72ac8d2db9 100644
--- a/railties/guides/source/active_record_validations_callbacks.textile
+++ b/railties/guides/source/active_record_validations_callbacks.textile
@@ -675,7 +675,7 @@ The following is a list of the most commonly used methods. Please refer to the +
h4(#working_with_validation_errors-errors). +errors+
-Returns an instance of the class +ActiveModel::Errors+ (which behaves like an ordered hash) containing all errors. Each key is the attribute name and the value is an array of strings with all errors.
+Returns an instance of the class +ActiveModel::Errors+ containing all errors. Each key is the attribute name and the value is an array of strings with all errors.
<ruby>
class Person < ActiveRecord::Base
diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile
index a55ed38d1b..ba92aedbd0 100644
--- a/railties/guides/source/association_basics.textile
+++ b/railties/guides/source/association_basics.textile
@@ -358,6 +358,7 @@ Here are a few things you should know to make efficient use of Active Record ass
* Avoiding name collisions
* Updating the schema
* Controlling association scope
+* Bi-directional associations
h4. Controlling Caching
@@ -501,6 +502,59 @@ module MyApplication
end
</ruby>
+h4. Bi-directional Associations
+
+It's normal for associations to work in two directions, requiring declaration on two different models:
+
+<ruby>
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+</ruby>
+
+By default, Active Record doesn't know about the connection between these associations. This can lead to two copies of an object getting out of sync:
+
+<ruby>
+c = Customer.first
+o = c.orders.first
+c.first_name == o.customer.first_name # => true
+c.first_name = 'Manny'
+c.first_name == o.customer.first_name # => false
+</ruby>
+
+This happens because c and o.customer are two different in-memory representations of the same data, and neither one is automatically refreshed from changes to the other. Active Record provides the +:inverse_of+ option so that you can inform it of these relations:
+
+<ruby>
+class Customer < ActiveRecord::Base
+ has_many :orders, :inverse_of => :customer
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer, :inverse_of => :orders
+end
+</ruby>
+
+With these changes, Active Record will only load one copy of the customer object, preventing inconsistencies and making your application more efficient:
+
+<ruby>
+c = Customer.first
+o = c.orders.first
+c.first_name == o.customer.first_name # => true
+c.first_name = 'Manny'
+c.first_name == o.customer.first_name # => true
+</ruby>
+
+There are a few limitations to +inverse_of+ support:
+
+* They do not work with <tt>:through</tt> associations.
+* They do not work with <tt>:polymorphic</tt> associations.
+* They do not work with <tt>:as</tt> associations.
+* For +belongs_to+ associations, +has_many+ inverse associations are ignored.
+
h3. Detailed Association Reference
The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association.
@@ -594,6 +648,7 @@ The +belongs_to+ association supports these options:
* +:dependent+
* +:foreign_key+
* +:include+
+* +:inverse_of+
* +:polymorphic+
* +:readonly+
* +:select+
@@ -720,6 +775,20 @@ end
NOTE: There's no need to use +:include+ for immediate associations - that is, if you have +Order belongs_to :customer+, then the customer is eager-loaded automatically when it's needed.
+h6(#belongs_to-inverse_of). +:inverse_of+
+
+The +:inverse_of+ option specifies the name of the +has_many+ or +has_one+ association that is the inverse of this association. Does not work in combination with the +:polymorphic+ options.
+
+<ruby>
+class Customer < ActiveRecord::Base
+ has_many :orders, :inverse_of => :customer
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer, :inverse_of => :orders
+end
+</ruby>
+
h6(#belongs_to-polymorphic). +:polymorphic+
Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.
@@ -859,6 +928,7 @@ The +has_one+ association supports these options:
* +:dependent+
* +:foreign_key+
* +:include+
+* +:inverse_of+
* +:order+
* +:primary_key+
* +:readonly+
@@ -899,6 +969,9 @@ end
h6(#has_one-dependent). +:dependent+
If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the association object to +NULL+.
+If you set the +:dependent+ option to +:restrict+, then the deletion of the object is restricted if a dependent associated object exist and a +DeleteRestrictionError+ exception is raised.
+
+NOTE: The default behavior for +:dependent => :restrict+ is to raise a +DeleteRestrictionError+ when associated objects exist. Since Rails 4.0 this behavior is being deprecated in favor of adding an error to the base model. To silence the warning in Rails 4.0, you should fix your code to not expect this Exception and add +config.active_record.dependent_restrict_raises = false+ to your application config.
h6(#has_one-foreign_key). +:foreign_key+
@@ -948,6 +1021,20 @@ class Representative < ActiveRecord::Base
end
</ruby>
+h6(#has_one-inverse_of). +:inverse_of+
+
+The +:inverse_of+ option specifies the name of the +belongs_to+ association that is the inverse of this association. Does not work in combination with the +:through+ or +:as+ options.
+
+<ruby>
+class Supplier < ActiveRecord::Base
+ has_one :account, :inverse_of => :supplier
+end
+
+class Account < ActiveRecord::Base
+ belongs_to :supplier, :inverse_of => :account
+end
+</ruby>
+
h6(#has_one-order). +:order+
The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
@@ -1177,6 +1264,7 @@ The +has_many+ association supports these options:
* +:foreign_key+
* +:group+
* +:include+
+* +:inverse_of+
* +:limit+
* +:offset+
* +:order+
@@ -1247,6 +1335,9 @@ NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL
h6(#has_many-dependent). +:dependent+
If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+.
+If you set the +:dependent+ option to +:restrict+, then the deletion of the object is restricted if a dependent associated object exist and a +DeleteRestrictionError+ exception is raised.
+
+NOTE: The default behavior for +:dependent => :restrict+ is to raise a +DeleteRestrictionError+ when associated objects exist. Since Rails 4.0 this behavior is being deprecated in favor of adding an error to the base model. To silence the warning in Rails 4.0, you should fix your code to not expect this Exception and add +config.active_record.dependent_restrict_raises = false+ to your application config.
NOTE: This option is ignored when you use the +:through+ option on the association.
@@ -1316,6 +1407,20 @@ class LineItem < ActiveRecord::Base
end
</ruby>
+h6(#has_many-inverse_of). +:inverse_of+
+
+The +:inverse_of+ option specifies the name of the +belongs_to+ association that is the inverse of this association. Does not work in combination with the +:through+ or +:as+ options.
+
+<ruby>
+class Customer < ActiveRecord::Base
+ has_many :orders, :inverse_of => :customer
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer, :inverse_of => :orders
+end
+</ruby>
+
h6(#has_many-limit). +:limit+
The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile
index 95f93101ab..451235d41d 100644
--- a/railties/guides/source/configuring.textile
+++ b/railties/guides/source/configuring.textile
@@ -122,6 +122,17 @@ WARNING: Threadsafe operation is incompatible with the normal workings of develo
* +config.whiny_nils+ enables or disables warnings when a certain set of methods are invoked on +nil+ and it does not respond to them. Defaults to true in development and test environments.
+* +config.console+ allows you to set class that will be used as console you run +rails console+. It's best to run it in +console+ block:
+
+<ruby>
+console do
+ # this block is called only when running console,
+ # so we can safely require pry here
+ require "pry"
+ config.console = Pry
+end
+</ruby>
+
h4. Configuring Assets
Rails 3.1, by default, is set up to use the +sprockets+ gem to manage assets within an application. This gem concatenates and compresses assets in order to make serving them much less painful.
diff --git a/railties/guides/source/engines.textile b/railties/guides/source/engines.textile
index 694b36bea1..e6058e7581 100644
--- a/railties/guides/source/engines.textile
+++ b/railties/guides/source/engines.textile
@@ -12,33 +12,43 @@ endprologue.
h3. What are engines?
-Engines can be considered miniature applications that provide functionality to their host applications. A Rails application is actually just a "supercharged" engine, with the +Rails::Application+ class inheriting from +Rails::Engine+. Therefore, engines and applications share common functionality but are at the same time two separate beasts. Engines and applications also share a common structure, as you'll see throughout this guide.
+Engines can be considered miniature applications that provide functionality to their host applications. A Rails application is actually just a "supercharged" engine, with the +Rails::Application+ class inheriting a lot of its behaviour from +Rails::Engine+.
-Engines are also closely related to plugins where the two share a common +lib+ directory structure and are both generated using the +rails plugin new+ generator.
+Therefore, engines and applications can be thought of almost the same thing, just with very minor differences, as you'll see throughout this guide. Engines and applications also share a common structure.
-The engine that will be generated for this guide will be called "blorgh". The engine will provide blogging functionality to its host applications, allowing for new posts and comments to be created. For now, you will be working solely within the engine itself and in later sections you'll see how to hook it into an application.
+Engines are also closely related to plugins where the two share a common +lib+ directory structure and are both generated using the +rails plugin new+ generator. The difference being that an engine is considered a "full plugin" by Rails -- as indicated by the +--full+ option that's passed to the generator command -- but this guide will refer to them simply as "engines" throughout. An engine *can* be a plugin, and a plugin *can* be an engine.
+
+The engine that will be created in this guide will be called "blorgh". The engine will provide blogging functionality to its host applications, allowing for new posts and comments to be created. At the beginning of this guide, you will be working solely within the engine itself, but in later sections you'll see how to hook it into an application.
Engines can also be isolated from their host applications. This means that an application is able to have a path provided by a routing helper such as +posts_path+ and use an engine also that provides a path also called +posts_path+, and the two would not clash. Along with this, controllers, models and table names are also namespaced. You'll see how to do this later in this guide.
-To see demonstrations of other engines, check out "Devise":https://github.com/plataformatec/devise, an engine that provides authentication for its parent applications, or "Forem":https://github.com/radar/forem, an engine that provides forum functionality.
+It's important to keep in mind at all times that the application should *always* take precedence over its engines. An application is the object that has final say in what goes on in the universe (with the universe being the application's environment) where the engine should only be enhancing it, rather than changing it drastically.
+
+To see demonstrations of other engines, check out "Devise":https://github.com/plataformatec/devise, an engine that provides authentication for its parent applications, or "Forem":https://github.com/radar/forem, an engine that provides forum functionality. There's also "Spree":https://github.com/spree/spree which provides an e-commerce platform, and "RefineryCMS":https://github.com/resolve/refinerycms, a CMS engine.
Finally, engines would not have be possible without the work of James Adam, Piotr Sarnacki, the Rails Core Team, and a number of other people. If you ever meet them, don't forget to say thanks!
h3. Generating an engine
-To generate an engine with Rails 3.1, you will need to run the plugin generator and pass it the +--mountable+ option. To generate the beginnings of the "blorgh" engine you will need to run this command in a terminal:
+To generate an engine with Rails 3.1, you will need to run the plugin generator and pass it the +--full+ and +--mountable+ options. To generate the beginnings of the "blorgh" engine you will need to run this command in a terminal:
<shell>
-$ rails plugin new blorgh --mountable
+$ rails plugin new blorgh --full --mountable
</shell>
-The +--mountable+ option tells the plugin generator that you want to create an engine (which is a mountable plugin, hence the option name), creating the basic directory structure of an engine by providing things such as the foundations of an +app+ folder, as well a +config/routes.rb+ file. This generator also provides a file at +lib/blorgh/engine.rb+ which is identical in function to an application's +config/application.rb+ file.
+The +--full+ option tells the plugin generator that you want to create an engine (which is a mountable plugin, hence the option name), creating the basic directory structure of an engine by providing things such as the foundations of an +app+ folder, as well a +config/routes.rb+ file. This generator also provides a file at +lib/blorgh/engine.rb+ which is identical in function to an application's +config/application.rb+ file.
+
+The +--mountable+ option tells the generator to mount the engine inside the dummy testing application located at +test/dummy+ inside the engine. It does this by placing this line in to the dummy application's +config/routes.rb+ file, located at +test/dummy/config/routes.rb+ inside the engine:
+
+<ruby>
+mount Blorgh::Engine, :at => "blorgh"
+</ruby>
h4. Inside an engine
h5. Critical files
-At the root of the engine's directory, lives a +blorgh.gemspec+ file. When you include the engine into the application later on, you will do so with this line in a Rails application's +Gemfile+:
+At the root of this brand new engine's directory, lives a +blorgh.gemspec+ file. When you include the engine into the application later on, you will do so with this line in a Rails application's +Gemfile+:
<ruby>
gem 'blorgh', :path => "vendor/engines/blorgh"
@@ -53,6 +63,8 @@ module Blorgh
end
</ruby>
+TIP: Some engines choose to use this file to put global configuration options for their engine. It's a relatively good idea, and so if you're wanting offer configuration options, the file where your engine's +module+ is defined is perfect for that. Place the methods inside the module and you'll be good to go.
+
Within +lib/blorgh/engine.rb+ is the base class for the engine:
<ruby>
@@ -63,23 +75,39 @@ module Blorgh
end
</ruby>
-By inheriting from the +Rails::Engine+ class, this engine gains all the functionality it needs, such as being able to serve requests to its controllers.
+By inheriting from the +Rails::Engine+ class, this gem notifies Rails that there's an engine at the specified path, and will correctly mount the engine inside the application, performing tasks such as adding the +app+ directory of the engine to the load path for models, mailers, controllers and views.
+
+The +isolate_namespace+ method here deserves special notice. This call is responsible for isolating the controllers, models, routes and other things into their own namespace, away from similar components inside hte application. Without this, there is a possibility that the engine's components could "leak" into the application, causing unwanted disruption, or that important engine components could be overriden by similarly named things within the application.
+
+NOTE: It is *highly* recommended that the +isolate_namespace+ line be left within the +Engine+ class definition. Without it, classes generated in an engine *may* conflict with an application.
+
+What this isolation of the namespace means is that a model generated by a call to +rails g model+ such as +rails g model post+ wouldn't be called +Post+, but instead be namespaced and called +Blorgh::Post+. In addition to this, the table for the model is namespaced, becoming +blorgh_posts+, rather than simply +posts+. Similar to the model namespacing, a controller called +PostsController+ would be +Blorgh::Postscontroller+ and the views for that controller would not be at +app/views/posts+, but rather +app/views/blorgh/posts+. Mailers would be namespaced as well.
-The +isolate_namespace+ method here deserves special notice. This call is responsible for isolating the controllers, models, routes and other things into their own namespace. Without this, there is a possibility that the engine's components could "leak" into the application, causing unwanted disruption. It is recommended that this line be left within this file.
+Finally, routes will also be isolated within the engine. This is one of the most important parts about namespacing, and is discussed later in the "Routes":#routes section of this guide.
h5. +app+ directory
-Inside the +app+ directory there lives the standard +assets+, +controllers+, +helpers+, +mailers+, +models+ and +views+ directories that you should be familiar with from an application. The +helpers+, +mailers+ and +models+ directories are empty and so aren't described in this section. We'll look more into models in a future section.
+Inside the +app+ directory there is the standard +assets+, +controllers+, +helpers+, +mailers+, +models+ and +views+ directories that you should be familiar with from an application. The +helpers+, +mailers+ and +models+ directories are empty and so aren't described in this section. We'll look more into models in a future section, when we're writing the engine.
Within the +app/assets+ directory, there is the +images+, +javascripts+ and +stylesheets+ directories which, again, you should be familiar with due to their similarities of an application. One difference here however is that each directory contains a sub-directory with the engine name. Because this engine is going to be namespaced, its assets should be too.
Within the +app/controllers+ directory there is a +blorgh+ directory and inside that a file called +application_controller.rb+. This file will provide any common functionality for the controllers of the engine. The +blorgh+ directory is where the other controllers for the engine will go. By placing them within this namespaced directory, you prevent them from possibly clashing with identically-named controllers within other engines or even within the application.
+NOTE: The +ApplicationController+ class is called as such inside an engine -- rather than +EngineController+ -- mainly due to that if you consider that an engine is really just a mini-application, it makes sense. You should also be able to convert an application to an engine with relatively little pain, and this is just one of the ways to make that process easier, albeit however so slightly.
+
Lastly, the +app/views+ directory contains a +layouts+ folder which contains file at +blorgh/application.html.erb+ which allows you to specify a layout for the engine. If this engine is to be used as a stand-alone engine, then you would add any customization to its layout in this file, rather than the applications +app/views/layouts/application.html.erb+ file.
+If you don't want to force a layout on to users of the engine, then you can delete this file and reference a different layout in the controllers of your engine.
+
h5. +script+ directory
-This directory contains one file, +script/rails+, which allows you to use the +rails+ sub-commands and generators just like you would within an application. This means that you will very easily be able to generate new controllers and models for this engine.
+This directory contains one file, +script/rails+, which enables you to use the +rails+ sub-commands and generators just like you would within an application. This means that you will very easily be able to generate new controllers and models for this engine by running commands like this:
+
+<shell>
+rails g model
+</shell>
+
+Keeping in mind, of course, that anything generated with these commands inside an engine that has +isolate_namespace+ inside the Engine class will be namespaced.
h5. +test+ directory
@@ -92,9 +120,9 @@ Rails.application.routes.draw do
end
</ruby>
-This line mounts the engine at the path of +/blorgh+, which will make it accessible through the application only at that path. We will look more into mounting an engine after some features have been developed.
+This line mounts the engine at the path of +/blorgh+, which will make it accessible through the application only at that path.
-Also in the test directory is the +test/integration+ directory, where integration tests for the engine should be placed.
+Also in the test directory is the +test/integration+ directory, where integration tests for the engine should be placed. Other directories can be created in the +test+ directory also. For example, you may wish to create a +test/unit+ directory for your unit tests.
h3. Providing engine functionality
@@ -142,11 +170,11 @@ invoke css
create app/assets/stylesheets/scaffold.css
</shell>
-The first thing that the scaffold generator does is invoke the +active_record+ generator, which generates a migration and a model for the resource. Note here, however, that the migration is called +create_blorgh_posts+ rather than the usual +create_posts+. This is due to the +isolate_namespace+ method called in the +Blorgh::Engine+ class's definition. The model here is also namespaced, being placed at +app/models/blorgh/post.rb+ rather than +app/models/post.rb+.
+The first thing that the scaffold generator does is invoke the +active_record+ generator, which generates a migration and a model for the resource. Note here, however, that the migration is called +create_blorgh_posts+ rather than the usual +create_posts+. This is due to the +isolate_namespace+ method called in the +Blorgh::Engine+ class's definition. The model here is also namespaced, being placed at +app/models/blorgh/post.rb+ rather than +app/models/post.rb+ due to the +isolate_namespace+ call within the +Engine+ class.
Next, the +test_unit+ generator is invoked for this model, generating a unit test at +test/unit/blorgh/post_test.rb+ (rather than +test/unit/post_test.rb+) and a fixture at +test/fixtures/blorgh/posts.yml+ (rather than +test/fixtures/posts.yml+).
-After that, a line for the resource is inserted into the +config/routes.rb+ file for the engine. This line is simply +resources :posts+, turning the +config/routes.rb+ file into this:
+After that, a line for the resource is inserted into the +config/routes.rb+ file for the engine. This line is simply +resources :posts+, turning the +config/routes.rb+ file for the engine into this:
<ruby>
Blorgh::Engine.routes.draw do
@@ -155,11 +183,11 @@ Blorgh::Engine.routes.draw do
end
</ruby>
-Note here that the routes are drawn upon the +Blorgh::Engine+ object rather than the +YourApp::Application+ class. This is so that the engine routes are confined to the engine itself and can be mounted at a specific point as shown in the "test directory":#test-directory section.
+Note here that the routes are drawn upon the +Blorgh::Engine+ object rather than the +YourApp::Application+ class. This is so that the engine routes are confined to the engine itself and can be mounted at a specific point as shown in the "test directory":#test-directory section. This is also what causes the engine's routes to be isolated from those routes that are within the application. This is discussed further in the "Routes":#routes section of this guide.
Next, the +scaffold_controller+ generator is invoked, generating a controlled called +Blorgh::PostsController+ (at +app/controllers/blorgh/posts_controller.rb+) and its related views at +app/views/blorgh/posts+. This generator also generates a functional test for the controller (+test/functional/blorgh/posts_controller_test.rb+) and a helper (+app/helpers/blorgh/posts_controller.rb+).
-Everything this generator has generated is neatly namespaced. The controller's class is defined within the +Blorgh+ module:
+Everything this generator has created is neatly namespaced. The controller's class is defined within the +Blorgh+ module:
<ruby>
module Blorgh
@@ -171,7 +199,7 @@ end
NOTE: The +ApplicationController+ class being inherited from here is the +Blorgh::ApplicationController+, not an application's +ApplicationController+.
-The helper is also namespaced:
+The helper inside +app/helpers/blorgh/posts_helper.rb+ is also namespaced:
<ruby>
module Blorgh
@@ -210,7 +238,7 @@ One final thing is that the +posts+ resource for this engine should be the root
root :to => "posts#index"
</ruby>
-Now people will only need to go to the root of the engine to see all the posts, rather than visiting +/posts+.
+Now people will only need to go to the root of the engine to see all the posts, rather than visiting +/posts+. This means that instead of +http://localhost:3000/blorgh/posts+, you only need to go to +http://localhost:3000/blorgh+ now.
h4. Generating a comments resource
@@ -258,7 +286,7 @@ module Blorgh
end
</ruby>
-Because the +has_many+ is defined inside a class that is inside the +Blorgh+ module, Rails will know that you want to use the +Blorgh::Comment+ model for these objects.
+NOTE: Because the +has_many+ is defined inside a class that is inside the +Blorgh+ module, Rails will know that you want to use the +Blorgh::Comment+ model for these objects, so there's no need to specify that using the +:class_name+ option here.
Next, there needs to be a form so that comments can be created on a post. To add this, put this line underneath the call to +render @post.comments+ in +app/views/blorgh/posts/show.html.erb+:
@@ -279,7 +307,7 @@ Next, the partial that this line will render needs to exist. Create a new direct
<% end %>
</erb>
-This form, when submitted, is going to attempt to post to a route of +posts/:post_id/comments+ within the engine. This route doesn't exist at the moment, but can be created by changing the +resources :posts+ line inside +config/routes.rb+ into these lines:
+When this form is submitted, it is going to attempt to perform a +POST+ request to a route of +/posts/:post_id/comments+ within the engine. This route doesn't exist at the moment, but can be created by changing the +resources :posts+ line inside +config/routes.rb+ into these lines:
<ruby>
resources :posts do
@@ -287,7 +315,9 @@ resources :posts do
end
</ruby>
-The route now will exist, but the controller that this route goes to does not. To create it, run this command:
+This creates a nested route for the comments, which is what the form requires.
+
+The route now exists, but the controller that this route goes to does not. To create it, run this command:
<shell>
$ rails g controller comments
@@ -378,10 +408,10 @@ As described earlier, by placing the gem in the +Gemfile+ it will be loaded when
To make the engine's functionality accessible from within an application, it needs to be mounted in that application's +config/routes.rb+ file:
<ruby>
-mount Blorgh::Engine, :at => "blog"
+mount Blorgh::Engine, :at => "/blog"
</ruby>
-This line will mount the engine at +blog+ in the application. Making it accessible at +http://localhost:3000/blog+ when the application runs with +rails s+.
+This line will mount the engine at +/blog+ in the application. Making it accessible at +http://localhost:3000/blog+ when the application runs with +rails server+.
NOTE: Other engines, such as Devise, handle this a little differently by making you specify custom helpers such as +devise_for+ in the routes. These helpers do exactly the same thing, mounting pieces of the engines's functionality at a pre-defined path which may be customizable.
@@ -393,6 +423,12 @@ The engine contains migrations for the +blorgh_posts+ and +blorgh_comments+ tabl
$ rake blorgh:install:migrations
</shell>
+If you have multiple engines that need migrations copied over, use +railties:install:migrations+ instead:
+
+<shell>
+$ rake railties:install:migrations
+</shell>
+
This command, when run for the first time will copy over all the migrations from the engine. When run the next time, it will only copy over migrations that haven't been copied over already. The first run for this command will output something such as this:
<shell>
@@ -410,7 +446,7 @@ When an engine is created, it may want to use specific classes from an applicati
Usually, an application would have a +User+ class that would provide the objects that would represent the posts' and comments' authors, but there could be a case where the application calls this class something different, such as +Person+. It's because of this reason that the engine should not hardcode the associations to be exactly for a +User+ class, but should allow for some flexibility around what the class is called.
-To keep it simple in this case, the application will have a class called +User+ which will represent the users of the application. It can be generated using this command:
+To keep it simple in this case, the application will have a class called +User+ which will represent the users of the application. It can be generated using this command inside the application:
<shell>
rails g model user name:string
@@ -418,7 +454,7 @@ rails g model user name:string
The +rake db:migrate+ command needs to be run here to ensure that our application has the +users+ table for future use.
-Also to keep it simple, the posts form will have a new text field called +author_name_+ where users can elect to put their name. The engine will then take this name and create a new +User+ object from it or find one that already has that name, and then associate the post with it.
+Also, to keep it simple, the posts form will have a new text field called +author_name+ where users can elect to put their name. The engine will then take this name and create a new +User+ object from it or find one that already has that name, and then associate the post with it.
First, the +author_name+ text field needs to be added to the +app/views/blorgh/posts/_form.html.erb+ partial inside the engine. This can be added above the +title+ field with this code:
@@ -486,8 +522,6 @@ Finally, the author's name should be displayed on the post's page. Add this code
</p>
</erb>
-WARNING: For posts created previously, this will break the +show+ page for them. We recommend deleting these posts and starting again, or manually assigning an author using +rails c+.
-
By outputting +@post.author+ using the +<%=+ tag the +to_s+ method will be called on the object. By default, this will look quite ugly:
<text>
@@ -532,7 +566,23 @@ The +set_author+ method also located in this class should also use this class:
self.author = Blorgh.user_class.constantize.find_or_create_by_name(author_name)
</ruby>
-To set this configuration setting within the application, an initializer should be used. By using an initializer, the configuration will be set up before the application starts and makes references to the classes of the engine which may depend on this configuration setting existing.
+To save having to call +constantize+ on the +user_class+ result all the time, you could instead just override the +user_class+ getter method inside the +Blorgh+ module in the +lib/blorgh.rb+ file to always call +constantize+ on the saved value before returning the result:
+
+<ruby>
+ def self.user_class
+ @@user_class.constantize
+ end
+</ruby>
+
+This would then turn the above code for +self.author=+ into this:
+
+<ruby>
+self.author = Blorgh.user_class.find_or_create_by_name(author_name)
+</ruby>
+
+Resulting in something a little shorter, and more implicit in its behaviour. The +user_class+ method should always return a +Class+ object.
+
+To set this configuration setting within the application, an initializer should be used. By using an initializer, the configuration will be set up before the application starts and calls the engine's models which may depend on this configuration setting existing.
Create a new initializer at +config/initializers/blorgh.rb+ inside the application where the +blorgh+ engine is installed and put this content in it:
@@ -544,23 +594,45 @@ WARNING: It's very important here to use the +String+ version of the class, rath
Go ahead and try to create a new post. You will see that it works exactly in the same way as before, except this time the engine is using the configuration setting in +config/initializers/blorgh.rb+ to learn what the class is.
-There are now no strict dependencies on what the class is, only what the class's API must be. The engine simply requires this class to define a +find_or_create_by_name+ method which returns an object of that class to be associated with a post when it's created.
+There are now no strict dependencies on what the class is, only what the class's API must be. The engine simply requires this class to define a +find_or_create_by_name+ method which returns an object of that class to be associated with a post when it's created. This object, of course, should have some sort of identifier by which it can be referenced.
h5. General engine configuration
Within an engine, there may come a time where you wish to use things such as initializers, internationalization or other configuration options. The great news is that these things are entirely possible because a Rails engine shares much the same functionality as a Rails application. In fact, a Rails application's functionality is actually a superset of what is provided by engines!
-If you wish to use initializers (code that should run before the engine is loaded), the best place for them is the +config/initializers+ folder. This directory's functionality is explained in the "Initializers section":http://guides.rubyonrails.org/configuring.html#initializers of the Configuring guide.
+If you wish to use an initializer -- code that should run before the engine is loaded -- the place for it is the +config/initializers+ folder. This directory's functionality is explained in the "Initializers section":http://guides.rubyonrails.org/configuring.html#initializers of the Configuring guide, and works precisely the same way as the +config/initializers+ directory inside an application. Same goes for if you want to use a standard initializer.
For locales, simply place the locale files in the +config/locales+ directory, just like you would in an application.
-h3. Extending engine functionality
+h3. Testing an engine
+
+When an engine is generated there is a smaller dummy application created inside it at +test/dummy+. This application is used as a mounting point for the engine to make testing the engine extremely simple. You may extend this application by generating controllers, models or views from within the directory, and then use those to test your engine.
+
+The +test+ directory should be treated like a typical Rails testing environment, allowing for unit, functional and integration tests.
+
+h4. Functional tests
+
+A matter worth taking into consideration when writing functional tests is that the tests are going to be running on an application -- the +test/dummy+ application -- rather than your engine. This is due to the setup of the testing environment; an engine needs an application as a host for testing its main functionality, especially controllers. This means that if you were to make a typical +GET+ to a controller in a controller's functional test like this:
+
+<ruby>
+get :index
+</ruby>
+
+It may not function correctly. This is because the application doesn't know how to route these requests to the engine unless you explicitly tell it *how*. To do this, you must pass the +:use_route+ option (as a parameter) on these requests also:
+
+<ruby>
+get :index, :use_route => :blorgh
+</ruby>
+
+This tells the application that you still want to perform a +GET+ request to the +index+ action of this controller, just that you want to use the engine's route to get there, rather than the application.
+
+h3. Improving engine functionality
This section looks at overriding or adding functionality to the views, controllers and models provided by an engine.
h4. Overriding views
-When Rails looks for a view to render, it will first look in the +app/views+ directory of the application. If it cannot find the view there, then it will check in the +app/views+ directories of all engines which have this directory.
+When Rails looks for a view to render, it will first look in the +app/views+ directory of the application. If it cannot find the view there, then it will check in the +app/views+ directories of all engines which have this directory.
In the +blorgh+ engine, there is a currently a file at +app/views/blorgh/posts/index.html.erb+. When the engine is asked to render the view for +Blorgh::PostsController+'s +index+ action, it will first see if it can find it at +app/views/blorgh/posts/index.html.erb+ within the application and then if it cannot it will look inside the engine.
@@ -583,36 +655,78 @@ Rather than looking like the default scaffold, the page will now look like this:
!images/engines_post_override.png(Engine scaffold overriden)!
-h4. Controllers
+h4. Routes
-TODO: Explain how to extend a controller.
-IDEA: I like Devise's +devise :controllers => { "sessions" => "sessions" }+ idea. Perhaps we could incorporate that into the guide?
+Routes inside an engine are, by default, isolated from the application. This is done by the +isolate_namespace+ call inside the +Engine+ class. This essentially means that the application and its engines can have identically named routes, and that they will not clash.
-h4. Models
+Routes inside an engine are drawn on the +Engine+ class within +config/routes.rb+, like this:
-TODO: Explain how to extend models provided by an engine.
+<ruby>
+ Blorgh::Engine.routes.draw do
+ resources :posts
+ end
+</ruby>
-h4. Routes
+By having isolated routes such as this, if you wish to link to an area of an engine from within an application, you will need to use the engine's routing proxy method. Calls to normal routing methods such as +posts_path+ may end up going to undesired locations if both the application and the engine both have such a helper defined.
-Within the application, you may wish to link to some area within the engine. Due to the fact that the engine's routes are isolated (by the +isolate_namespace+ call within the +lib/blorgh/engine.rb+ file), you will need to prefix these routes with the engine name. This means rather than having something such as:
+For instance, the following example would go to the application's +posts_path+ if that template was rendered from the application, or the engine's +posts_path+ if it was rendered from the engine:
<erb>
<%= link_to "Blog posts", posts_path %>
</erb>
-It needs to be written as:
+To make this route always use the engine's +posts_path+ routing helper method, we must call the method on the routing proxy method that shares the same name as the engine.
<erb>
<%= link_to "Blog posts", blorgh.posts_path %>
</erb>
-This allows for the engine _and_ the application to both have a +posts_path+ routing helper and to not interfere with each other. You may also reference another engine's routes from inside an engine using this same syntax.
-
If you wish to reference the application inside the engine in a similar way, use the +main_app+ helper:
<erb>
<%= link_to "Home", main_app.root_path %>
</erb>
-TODO: Mention how to use assets within an engine?
-TODO: Mention how to depend on external gems, like RedCarpet.
+If you were to use this inside an engine, it would *always* go to the application's root. If you were to leave off the +main_app+ "routing proxy" method call, it could potentially go to the engine's or application's root, depending on where it was called from.
+
+If a template is rendered from within an engine and it's attempting to use one of the application's routing helper methods, it may result in an undefined method call. If you encounter such an issue, ensure that you're not attempting to call the application's routing methods without the +main_app+ prefix from within the engine.
+
+h4. Assets
+
+Assets within an engine work in an identical way to a full application. Because the engine class inherits from +Rails::Engine+, the application will know to look up in the engine's +app/assets+ directory for potential assets.
+
+Much like all the other components of an engine, the assets should also be namespaced. This means if you have an asset called +style.css+, it should be placed at +app/assets/stylesheets/[engine name]/style.css+, rather than +app/assets/stylesheets/style.css+. If this asset wasn't namespaced, then there is a possibility that the host application could have an asset named identically, in which case the application's asset would take precedence and the engine's one would be all but ignored.
+
+Imagine that you did have an asset located at +app/assets/stylesheets/blorgh/style.css+ To include this asset inside an application, just use +stylesheet_link_tag+ and reference the asset as if it were inside the engine:
+
+<erb>
+<%= stylesheet_link_tag "blorgh/style.css" %>
+</erb>
+
+You can also specify these assets as dependencies of other assets using the Asset Pipeline require statements in processed files:
+
+<css>
+/*
+ *= require blorgh/style
+*/
+</css>
+
+For more information, read the "Asset Pipeline guide":http://guides.rubyonrails.org/asset_pipeline.html
+
+h4. Other gem dependencies
+
+Gem dependencies inside an engine should be specified inside the +.gemspec+ file that's at the root of the engine. The reason for this is because the engine may be installed as a gem. If dependencies were to be specified inside the +Gemfile+, these would not be recognised by a traditional gem install and so they would not be installed, causing the engine to malfunction.
+
+To specify a dependency that should be installed with the engine during a traditional +gem install+, specify it inside the +Gem::Specification+ block inside the +.gemspec+ file in the engine:
+
+<ruby>
+s.add_dependency "moo"
+</ruby>
+
+To specify a dependency that should only be installed as a development dependency of the application, specify it like this:
+
+<ruby>
+s.add_development_dependency "moo"
+</ruby>
+
+Both kinds of dependencies will be installed when +bundle install+ is run inside the application. The development dependencies for the gem will only be used when the tests for the engine are running.
diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile
index 6ac9645917..be352cfe3d 100644
--- a/railties/guides/source/layouts_and_rendering.textile
+++ b/railties/guides/source/layouts_and_rendering.textile
@@ -1188,7 +1188,7 @@ You can also specify a second partial to be rendered between instances of the ma
h5. Spacer Templates
<erb>
-<%= render @products, :spacer_template => "product_ruler" %>
+<%= render :partial => @products, :spacer_template => "product_ruler" %>
</erb>
Rails will render the +_product_ruler+ partial (with no data passed in to it) between each pair of +_product+ partials.
diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile
index ccff2a1eed..07fd95c825 100644
--- a/railties/guides/source/plugins.textile
+++ b/railties/guides/source/plugins.textile
@@ -30,7 +30,7 @@ Before you continue, take a moment to decide if your new plugin will be potentia
* If your plugin is specific to your application, your new plugin will be a _vendored plugin_.
* If you think your plugin may be used across applications, build it as a _gemified plugin_.
-h4. Or generate a gemified plugin.
+h4. Generate a gemified plugin.
Writing your Rails plugin as a gem, rather than as a vendored plugin,
lets you share your plugin across different rails applications using
diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb
index 1ad08220ee..825ea985fc 100644
--- a/railties/lib/rails/application/configuration.rb
+++ b/railties/lib/rails/application/configuration.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/string/encoding'
require 'active_support/core_ext/kernel/reporting'
require 'active_support/file_update_checker'
require 'rails/engine/configuration'
@@ -7,7 +6,7 @@ module Rails
class Application
class Configuration < ::Rails::Engine::Configuration
attr_accessor :allow_concurrency, :asset_host, :asset_path, :assets,
- :cache_classes, :cache_store, :consider_all_requests_local,
+ :cache_classes, :cache_store, :consider_all_requests_local, :console,
:dependency_loading, :exceptions_app, :file_watcher, :filter_parameters,
:force_ssl, :helpers_paths, :logger, :log_tags, :preload_frameworks,
:railties_order, :relative_url_root, :secret_token,
diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb
index 3acac2a6f0..86376ac7e6 100644
--- a/railties/lib/rails/commands/console.rb
+++ b/railties/lib/rails/commands/console.rb
@@ -4,47 +4,68 @@ require 'irb/completion'
module Rails
class Console
- def self.start(app)
- new(app).start
- end
+ attr_reader :options, :app, :console, :arguments
- def initialize(app)
- @app = app
+ def self.start(*args)
+ new(*args).start
end
- def start
- options = {}
-
- OptionParser.new do |opt|
- opt.banner = "Usage: console [environment] [options]"
- opt.on('-s', '--sandbox', 'Rollback database modifications on exit.') { |v| options[:sandbox] = v }
- opt.on("--debugger", 'Enable ruby-debugging for the console.') { |v| options[:debugger] = v }
- opt.on('--irb', "DEPRECATED: Invoke `/your/choice/of/ruby script/rails console` instead") { |v| abort '--irb option is no longer supported. Invoke `/your/choice/of/ruby script/rails console` instead' }
- opt.parse!(ARGV)
- end
+ def initialize(app, arguments = ARGV)
+ @app = app
+ @arguments = arguments
+ app.load_console
+ @console = app.config.console || IRB
+ end
- @app.sandbox = options[:sandbox]
- @app.load_console
+ def options
+ @options ||= begin
+ options = {}
- if options[:debugger]
- begin
- require 'ruby-debug'
- puts "=> Debugger enabled"
- rescue Exception
- puts "You need to install ruby-debug19 to run the console in debugging mode. With gems, use 'gem install ruby-debug19'"
- exit
+ OptionParser.new do |opt|
+ opt.banner = "Usage: console [environment] [options]"
+ opt.on('-s', '--sandbox', 'Rollback database modifications on exit.') { |v| options[:sandbox] = v }
+ opt.on("--debugger", 'Enable ruby-debugging for the console.') { |v| options[:debugger] = v }
+ opt.parse!(arguments)
end
+
+ options
end
+ end
+
+ def sandbox?
+ options[:sandbox]
+ end
- if options[:sandbox]
+ def debugger?
+ options[:debugger]
+ end
+
+ def start
+ app.sandbox = sandbox?
+
+ require_debugger if debugger?
+
+ if sandbox?
puts "Loading #{Rails.env} environment in sandbox (Rails #{Rails.version})"
puts "Any modifications you make will be rolled back on exit"
else
puts "Loading #{Rails.env} environment (Rails #{Rails.version})"
end
- IRB::ExtendCommandBundle.send :include, Rails::ConsoleMethods
- IRB.start
+ if defined?(console::ExtendCommandBundle)
+ console::ExtendCommandBundle.send :include, Rails::ConsoleMethods
+ end
+ console.start
+ end
+
+ def require_debugger
+ begin
+ require 'ruby-debug'
+ puts "=> Debugger enabled"
+ rescue Exception
+ puts "You need to install ruby-debug19 to run the console in debugging mode. With gems, use 'gem install ruby-debug19'"
+ exit
+ end
end
end
end
diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb
index 77a68eb7f1..af2bde5a6e 100644
--- a/railties/lib/rails/engine.rb
+++ b/railties/lib/rails/engine.rb
@@ -300,7 +300,7 @@ module Rails
# helper MyEngine::SharedEngineHelper
# end
#
- # If you want to include all of the engine's helpers, you can use #helpers method on an engine's
+ # If you want to include all of the engine's helpers, you can use #helper method on an engine's
# instance:
#
# class ApplicationController < ActionController::Base
@@ -326,7 +326,7 @@ module Rails
# migration in the application and rerun copying migrations.
#
# If your engine has migrations, you may also want to prepare data for the database in
- # the <tt>seeds.rb</tt> file. You can load that data using the <tt>load_seed</tt> method, e.g.
+ # the <tt>db/seeds.rb</tt> file. You can load that data using the <tt>load_seed</tt> method, e.g.
#
# MyEngine::Engine.load_seed
#
diff --git a/railties/test/application/rake/migrations_test.rb b/railties/test/application/rake/migrations_test.rb
index 301e516192..c94334f189 100644
--- a/railties/test/application/rake/migrations_test.rb
+++ b/railties/test/application/rake/migrations_test.rb
@@ -67,7 +67,7 @@ module ApplicationTests
`rails generate migration add_email_to_users email:string`
end
- Dir.chdir(app_path) { `rake db:migrate`}
+ Dir.chdir(app_path) { `rake db:migrate` }
output = Dir.chdir(app_path) { `rake db:migrate:status` }
assert_match(/up\s+\d{14}\s+Create users/, output)
@@ -80,6 +80,27 @@ module ApplicationTests
assert_match(/down\s+\d{14}\s+Add email to users/, output)
end
+ test 'migration status without timestamps' do
+ add_to_config('config.active_record.timestamped_migrations = false')
+
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string`
+ `rails generate migration add_email_to_users email:string`
+ end
+
+ Dir.chdir(app_path) { `rake db:migrate` }
+ output = Dir.chdir(app_path) { `rake db:migrate:status` }
+
+ assert_match(/up\s+\d{3,}\s+Create users/, output)
+ assert_match(/up\s+\d{3,}\s+Add email to users/, output)
+
+ Dir.chdir(app_path) { `rake db:rollback STEP=1` }
+ output = Dir.chdir(app_path) { `rake db:migrate:status` }
+
+ assert_match(/up\s+\d{3,}\s+Create users/, output)
+ assert_match(/down\s+\d{3,}\s+Add email to users/, output)
+ end
+
test 'test migration status after rollback and redo' do
Dir.chdir(app_path) do
`rails generate model user username:string password:string`
@@ -104,6 +125,33 @@ module ApplicationTests
assert_match(/up\s+\d{14}\s+Create users/, output)
assert_match(/up\s+\d{14}\s+Add email to users/, output)
end
+
+ test 'migration status after rollback and redo without timestamps' do
+ add_to_config('config.active_record.timestamped_migrations = false')
+
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string`
+ `rails generate migration add_email_to_users email:string`
+ end
+
+ Dir.chdir(app_path) { `rake db:migrate` }
+ output = Dir.chdir(app_path) { `rake db:migrate:status` }
+
+ assert_match(/up\s+\d{3,}\s+Create users/, output)
+ assert_match(/up\s+\d{3,}\s+Add email to users/, output)
+
+ Dir.chdir(app_path) { `rake db:rollback STEP=2` }
+ output = Dir.chdir(app_path) { `rake db:migrate:status` }
+
+ assert_match(/down\s+\d{3,}\s+Create users/, output)
+ assert_match(/down\s+\d{3,}\s+Add email to users/, output)
+
+ Dir.chdir(app_path) { `rake db:migrate:redo` }
+ output = Dir.chdir(app_path) { `rake db:migrate:status` }
+
+ assert_match(/up\s+\d{3,}\s+Create users/, output)
+ assert_match(/up\s+\d{3,}\s+Add email to users/, output)
+ end
end
end
end
diff --git a/railties/test/commands/console_test.rb b/railties/test/commands/console_test.rb
new file mode 100644
index 0000000000..01847ae58c
--- /dev/null
+++ b/railties/test/commands/console_test.rb
@@ -0,0 +1,87 @@
+require 'abstract_unit'
+require 'rails/commands/console'
+
+class Rails::ConsoleTest < ActiveSupport::TestCase
+ class FakeConsole
+ end
+
+ def setup
+ end
+
+ def test_sandbox_option
+ console = Rails::Console.new(app, ["--sandbox"])
+ assert console.sandbox?
+ end
+
+ def test_short_version_of_sandbox_option
+ console = Rails::Console.new(app, ["-s"])
+ assert console.sandbox?
+ end
+
+ def test_debugger_option
+ console = Rails::Console.new(app, ["--debugger"])
+ assert console.debugger?
+ end
+
+ def test_no_options
+ console = Rails::Console.new(app, [])
+ assert !console.debugger?
+ assert !console.sandbox?
+ end
+
+ def test_start
+ app.expects(:sandbox=).with(nil)
+ FakeConsole.expects(:start)
+
+ start
+
+ assert_match /Loading \w+ environment \(Rails/, output
+ end
+
+ def test_start_with_debugger
+ app.expects(:sandbox=).with(nil)
+ rails_console.expects(:require_debugger).returns(nil)
+ FakeConsole.expects(:start)
+
+ start ["--debugger"]
+ end
+
+ def test_start_with_sandbox
+ app.expects(:sandbox=).with(true)
+ FakeConsole.expects(:start)
+
+ start ["--sandbox"]
+
+ assert_match /Loading \w+ environment in sandbox \(Rails/, output
+ end
+
+ def test_console_defaults_to_IRB
+ config = mock("config", :console => nil)
+ app = mock("app", :config => config)
+ app.expects(:load_console).returns(nil)
+
+ assert_equal IRB, Rails::Console.new(app).console
+ end
+
+ private
+
+ attr_reader :output
+
+ def rails_console
+ @rails_console ||= Rails::Console.new(app)
+ end
+
+ def start(argv = [])
+ rails_console.stubs(:arguments => argv)
+ @output = output = capture(:stdout) { rails_console.start }
+ end
+
+ def app
+ @app ||= begin
+ config = mock("config", :console => FakeConsole)
+ app = mock("app", :config => config)
+ app.expects(:load_console)
+ app
+ end
+ end
+end