Browse files

Merge branch 'master' of git://github.com/rails/rails

  • Loading branch information...
2 parents 735027e + d6953cb commit a16fd961310d4df5bd20df5fe64b2f764d8aa471 @mikel mikel committed Jun 7, 2010
Showing with 899 additions and 501 deletions.
  1. +1 −1 Gemfile
  2. +1 −1 actionpack/actionpack.gemspec
  3. +8 −0 actionpack/lib/action_controller/metal/url_for.rb
  4. +7 −5 actionpack/lib/action_controller/test_case.rb
  5. +1 −0 actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb
  6. +19 −7 actionpack/lib/action_dispatch/http/request.rb
  7. +1 −1 actionpack/lib/action_dispatch/middleware/flash.rb
  8. +4 −4 actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
  9. +1 −1 actionpack/lib/action_dispatch/middleware/show_exceptions.rb
  10. +5 −13 actionpack/lib/action_dispatch/middleware/stack.rb
  11. +1 −1 actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb
  12. +11 −4 actionpack/lib/action_dispatch/routing/mapper.rb
  13. +21 −11 actionpack/lib/action_dispatch/routing/route_set.rb
  14. +0 −2 actionpack/lib/action_dispatch/testing/assertions/selector.rb
  15. +2 −1 actionpack/lib/action_view/base.rb
  16. +1 −1 actionpack/lib/action_view/helpers/tag_helper.rb
  17. +22 −16 actionpack/lib/action_view/helpers/text_helper.rb
  18. +52 −22 actionpack/lib/action_view/lookup_context.rb
  19. +3 −12 actionpack/lib/action_view/render/layouts.rb
  20. +1 −1 actionpack/lib/action_view/template/handlers.rb
  21. +3 −0 actionpack/test/controller/new_base/render_rjs_test.rb
  22. +12 −0 actionpack/test/dispatch/routing_test.rb
  23. +2 −14 actionpack/test/template/lookup_context_test.rb
  24. +2 −0 actionpack/test/template/tag_helper_test.rb
  25. +96 −6 actionpack/test/template/text_helper_test.rb
  26. +1 −1 activemodel/activemodel.gemspec
  27. +1 −0 activemodel/lib/active_model/observing.rb
  28. +1 −0 activerecord/lib/active_record/associations.rb
  29. +2 −1 activerecord/lib/active_record/associations/association_collection.rb
  30. +5 −9 activerecord/lib/active_record/autosave_association.rb
  31. +1 −1 activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
  32. +8 −49 activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
  33. +7 −7 activerecord/test/cases/associations/eager_load_nested_include_test.rb
  34. +4 −4 activerecord/test/cases/autosave_association_test.rb
  35. +14 −1 activerecord/test/cases/named_scope_test.rb
  36. +2 −2 activerecord/test/cases/nested_attributes_test.rb
  37. +1 −0 activerecord/test/models/comment.rb
  38. +1 −1 activesupport/CHANGELOG
  39. +6 −3 activesupport/lib/active_support/callbacks.rb
  40. +18 −4 activesupport/lib/active_support/core_ext/array/random_access.rb
  41. +1 −0 activesupport/lib/active_support/core_ext/load_error.rb
  42. +11 −0 activesupport/lib/active_support/core_ext/string/conversions.rb
  43. +0 −11 activesupport/lib/active_support/core_ext/string/inflections.rb
  44. +6 −2 activesupport/lib/active_support/core_ext/uri.rb
  45. +32 −0 activesupport/lib/active_support/dependencies.rb
  46. +4 −4 activesupport/lib/active_support/message_verifier.rb
  47. +23 −7 activesupport/test/core_ext/array_ext_test.rb
  48. +10 −0 activesupport/test/core_ext/date_ext_test.rb
  49. +21 −0 activesupport/test/dependencies_test.rb
  50. +118 −123 railties/README
  51. +1 −0 railties/guides/source/3_0_release_notes.textile
  52. +122 −5 railties/guides/source/active_support_core_extensions.textile
  53. +7 −3 railties/guides/source/activerecord_validations_callbacks.textile
  54. +1 −1 railties/guides/source/routing.textile
  55. +4 −0 railties/lib/rails/configuration.rb
  56. +166 −129 railties/lib/rails/generators/rails/app/templates/README
  57. +10 −3 railties/lib/rails/log_subscriber.rb
  58. +4 −3 railties/lib/rails/rack/logger.rb
  59. +2 −2 railties/test/application/initializers/frameworks_test.rb
  60. +6 −0 railties/test/application/middleware_test.rb
  61. +1 −1 railties/test/isolation/abstract_unit.rb
View
2 Gemfile
@@ -29,7 +29,7 @@ gem "text-format", "~> 1.0.0"
# AR
if mri || RUBY_ENGINE == "rbx"
- gem "sqlite3-ruby", "= 1.3.0.beta.2", :require => 'sqlite3'
+ gem "sqlite3-ruby", "~> 1.3.0", :require => 'sqlite3'
group :db do
gem "pg", ">= 0.9.0"
View
2 actionpack/actionpack.gemspec
@@ -22,7 +22,7 @@ Gem::Specification.new do |s|
s.add_dependency('activesupport', version)
s.add_dependency('activemodel', version)
s.add_dependency('builder', '~> 2.1.2')
- s.add_dependency('i18n', '~> 0.4.0')
+ s.add_dependency('i18n', '~> 0.4.1')
s.add_dependency('rack', '~> 1.1.0')
s.add_dependency('rack-test', '~> 0.5.4')
s.add_dependency('rack-mount', '~> 0.6.3')
View
8 actionpack/lib/action_controller/metal/url_for.rb
@@ -16,5 +16,13 @@ def _router
raise "In order to use #url_for, you must include the helpers of a particular " \
"router. For instance, `include Rails.application.routes.url_helpers"
end
+
+ module ClassMethods
+ def action_methods
+ @action_methods ||= begin
+ super - _router.named_routes.helper_names
+ end
+ end
+ end
end
end
View
12 actionpack/lib/action_controller/test_case.rb
@@ -139,14 +139,16 @@ def assign_parameters(routes, controller_path, action, parameters = {})
end
end
- params = self.request_parameters.dup
+ # Clear the combined params hash in case it was already referenced.
+ @env.delete("action_dispatch.request.parameters")
+ params = self.request_parameters.dup
%w(controller action only_path).each do |k|
params.delete(k)
params.delete(k.to_sym)
end
-
data = params.to_query
+
@env['CONTENT_LENGTH'] = data.length.to_s
@env['rack.input'] = StringIO.new(data)
end
@@ -155,6 +157,8 @@ def recycle!
@formats = nil
@env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ }
@env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ }
+ @method = @request_method = nil
+ @fullpath = @ip = @remote_ip = nil
@env['action_dispatch.request.query_parameters'] = {}
end
end
@@ -167,9 +171,7 @@ def recycle!
@block = nil
@length = 0
@body = []
- @charset = nil
- @content_type = nil
-
+ @charset = @content_type = nil
@request = @template = nil
end
end
View
1 actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb
@@ -23,6 +23,7 @@ class Tokenizer #:nodoc:
# Create a new Tokenizer for the given text.
def initialize(text)
+ text.encode! if text.encoding_aware?
@scanner = StringScanner.new(text)
@position = 0
@line = 0
View
26 actionpack/lib/action_dispatch/http/request.rb
@@ -52,9 +52,11 @@ def key?(key)
# the application should use), this \method returns the overridden
# value, not the original.
def request_method
- method = env["REQUEST_METHOD"]
- HTTP_METHOD_LOOKUP[method] || raise(ActionController::UnknownHttpMethod, "#{method}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}")
- method
+ @request_method ||= begin
+ method = env["REQUEST_METHOD"]
+ HTTP_METHOD_LOOKUP[method] || raise(ActionController::UnknownHttpMethod, "#{method}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}")
+ method
+ end
end
# Returns a symbol form of the #request_method
@@ -66,9 +68,11 @@ def request_method_symbol
# even if it was overridden by middleware. See #request_method for
# more information.
def method
- method = env["rack.methodoverride.original_method"] || env['REQUEST_METHOD']
- HTTP_METHOD_LOOKUP[method] || raise(ActionController::UnknownHttpMethod, "#{method}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}")
- method
+ @method ||= begin
+ method = env["rack.methodoverride.original_method"] || env['REQUEST_METHOD']
+ HTTP_METHOD_LOOKUP[method] || raise(ActionController::UnknownHttpMethod, "#{method}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}")
+ method
+ end
end
# Returns a symbol form of the #method
@@ -113,6 +117,10 @@ def headers
Http::Headers.new(@env)
end
+ def fullpath
+ @fullpath ||= super
+ end
+
def forgery_whitelisted?
get? || xhr? || content_mime_type.nil? || !content_mime_type.verify_request?
end
@@ -134,6 +142,10 @@ def xml_http_request?
end
alias :xhr? :xml_http_request?
+ def ip
+ @ip ||= super
+ end
+
# Which IP addresses are "trusted proxies" that can be stripped from
# the right-hand-side of X-Forwarded-For
TRUSTED_PROXIES = /^127\.0\.0\.1$|^(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\./i
@@ -145,7 +157,7 @@ def xml_http_request?
# delimited list in the case of multiple chained proxies; the last
# address which is not trusted is the originating IP.
def remote_ip
- (@env["action_dispatch.remote_ip"] || ip).to_s
+ @remote_ip ||= (@env["action_dispatch.remote_ip"] || ip).to_s
end
# Returns the lowercase name of the HTTP server software.
View
2 actionpack/lib/action_dispatch/middleware/flash.rb
@@ -176,7 +176,7 @@ def call(env)
@app.call(env)
ensure
- if (session = env['rack.session']) && (flash = session['flash']) && flash.empty?
+ if (session = env['rack.session']) && session.key?('flash') && session['flash'].empty?
session.delete('flash')
end
end
View
8 actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
@@ -51,11 +51,11 @@ def inspect
super
end
- private
- def loaded?
- @loaded
- end
+ def loaded?
+ @loaded
+ end
+ private
def load!
stale_session_check! do
id, session = @by.send(:load_session, @env)
View
2 actionpack/lib/action_dispatch/middleware/show_exceptions.rb
@@ -72,7 +72,7 @@ def render_exception(env, exception)
rescue_action_in_public(exception)
end
rescue Exception => failsafe_error
- $stderr.puts "Error during failsafe response: #{failsafe_error}"
+ $stderr.puts "Error during failsafe response: #{failsafe_error}\n #{failsafe_error.backtrace * "\n "}"
FAILSAFE_RESPONSE
end
View
18 actionpack/lib/action_dispatch/middleware/stack.rb
@@ -5,13 +5,13 @@ class MiddlewareStack < Array
class Middleware
attr_reader :args, :block
- def initialize(klass, *args, &block)
- @klass, @args, @block = klass, args, block
+ def initialize(klass_or_name, *args, &block)
+ @ref = ActiveSupport::Dependencies::Reference.new(klass_or_name)
+ @args, @block = args, block
end
def klass
- return @klass if @klass.respond_to?(:new)
- @klass = ActiveSupport::Inflector.constantize(@klass.to_s)
+ @ref.get
end
def ==(middleware)
@@ -21,11 +21,7 @@ def ==(middleware)
when Class
klass == middleware
else
- if lazy_compare?(@klass) && lazy_compare?(middleware)
- normalize(@klass) == normalize(middleware)
- else
- klass.name == normalize(middleware.to_s)
- end
+ normalize(@ref.name) == normalize(middleware)
end
end
@@ -39,10 +35,6 @@ def build(app)
private
- def lazy_compare?(object)
- object.is_a?(String) || object.is_a?(Symbol)
- end
-
def normalize(object)
object.to_s.strip.sub(/^::/, '')
end
View
2 actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb
@@ -13,7 +13,7 @@
request_dump = clean_params.empty? ? 'None' : clean_params.inspect.gsub(',', ",\n")
def debug_hash(hash)
- hash.sort_by { |k, v| k.to_s }.map { |k, v| "#{k}: #{v.inspect}" }.join("\n")
+ hash.sort_by { |k, v| k.to_s }.map { |k, v| "#{k}: #{v.inspect rescue $!.message}" }.join("\n")
end
%>
View
15 actionpack/lib/action_dispatch/routing/mapper.rb
@@ -622,12 +622,19 @@ def collection
end
def member
- unless @scope[:scope_level] == :resources
- raise ArgumentError, "can't use member outside resources scope"
+ unless [:resources, :resource].include?(@scope[:scope_level])
+ raise ArgumentError, "You can't use member action outside resources and resource scope."
end
- with_scope_level(:member) do
- scope(':id', :name_prefix => parent_resource.member_name, :as => "") do
+ case @scope[:scope_level]
+ when :resources
+ with_scope_level(:member) do
+ scope(':id', :name_prefix => parent_resource.member_name, :as => "") do
+ yield
+ end
+ end
+ when :resource
+ with_scope_level(:member) do
yield
end
end
View
32 actionpack/lib/action_dispatch/routing/route_set.rb
@@ -12,6 +12,7 @@ class Dispatcher #:nodoc:
def initialize(options={})
@defaults = options[:defaults]
@glob_param = options.delete(:glob)
+ @controllers = {}
end
def call(env)
@@ -29,19 +30,18 @@ def call(env)
def prepare_params!(params)
merge_default_action!(params)
split_glob_param!(params) if @glob_param
-
- params.each do |key, value|
- if value.is_a?(String)
- value = value.dup.force_encoding(Encoding::BINARY) if value.respond_to?(:force_encoding)
- params[key] = URI.unescape(value)
- end
- end
end
def controller(params, raise_error=true)
- if params && params.has_key?(:controller)
- controller = "#{params[:controller].camelize}Controller"
- ActiveSupport::Inflector.constantize(controller)
+ if params && params.key?(:controller)
+ controller_param = params[:controller]
+ unless controller = @controllers[controller_param]
+ controller_name = "#{controller_param.camelize}Controller"
+ controller = @controllers[controller_param] =
+ ActiveSupport::Dependencies.ref(controller_name)
+ end
+
+ controller.get
end
rescue NameError => e
raise ActionController::RoutingError, e.message, e.backtrace if raise_error
@@ -68,6 +68,10 @@ def initialize
clear!
end
+ def helper_names
+ self.module.instance_methods.map(&:to_s)
+ end
+
def clear!
@routes = {}
@helpers = []
@@ -176,7 +180,6 @@ def #{selector}(*args)
url_for(options)
end
- protected :#{selector}
END_EVAL
helpers << selector
end
@@ -466,6 +469,13 @@ def recognize_path(path, environment = {})
req = Rack::Request.new(env)
@set.recognize(req) do |route, matches, params|
+ params.each do |key, value|
+ if value.is_a?(String)
+ value = value.dup.force_encoding(Encoding::BINARY) if value.encoding_aware?
+ params[key] = URI.unescape(value)
+ end
+ end
+
dispatcher = route.app
if dispatcher.is_a?(Dispatcher) && dispatcher.controller(params, false)
dispatcher.prepare_params!(params)
View
2 actionpack/lib/action_dispatch/testing/assertions/selector.rb
@@ -267,14 +267,12 @@ def assert_select(*args, &block)
if match_with = equals[:text]
matches.delete_if do |match|
text = ""
- text.force_encoding(match_with.encoding) if text.respond_to?(:force_encoding)
stack = match.children.reverse
while node = stack.pop
if node.tag?
stack.concat node.children.reverse
else
content = node.content
- content.force_encoding(match_with.encoding) if content.respond_to?(:force_encoding)
text << content
end
end
View
3 actionpack/lib/action_view/base.rb
@@ -184,7 +184,7 @@ class << self
attr_internal :captures, :request, :controller, :template, :config
delegate :find_template, :template_exists?, :formats, :formats=, :locale, :locale=,
- :view_paths, :view_paths=, :with_fallbacks, :update_details, :to => :lookup_context
+ :view_paths, :view_paths=, :with_fallbacks, :update_details, :with_layout_format, :to => :lookup_context
delegate :request_forgery_protection_token, :template, :params, :session, :cookies, :response, :headers,
:flash, :action_name, :controller_name, :to => :controller
@@ -201,6 +201,7 @@ def self.xss_safe? #:nodoc:
end
def self.process_view_paths(value)
+ return value.dup if value.is_a?(PathSet)
ActionView::PathSet.new(Array.wrap(value))
end
View
2 actionpack/lib/action_view/helpers/tag_helper.rb
@@ -110,7 +110,7 @@ def escape_once(html)
def content_tag_string(name, content, options, escape = true)
tag_options = tag_options(options, escape) if options
- "<#{name}#{tag_options}>#{ERB::Util.h(content)}</#{name}>".html_safe
+ "<#{name}#{tag_options}>#{escape ? ERB::Util.h(content) : content}</#{name}>".html_safe
end
def tag_options(options, escape = true)
View
38 actionpack/lib/action_view/helpers/text_helper.rb
@@ -74,6 +74,7 @@ def truncate(text, *args)
options.reverse_merge!(:length => 30)
+ text = sanitize(text) unless text.html_safe? || options[:safe]
text.truncate(options.delete(:length), options) if text
end
@@ -105,6 +106,7 @@ def highlight(text, phrases, *args)
end
options.reverse_merge!(:highlighter => '<strong class="highlight">\1</strong>')
+ text = sanitize(text) unless text.html_safe? || options[:safe]
if text.blank? || phrases.blank?
text
else
@@ -244,13 +246,14 @@ def word_wrap(text, *args)
#
def textilize(text, *options)
options ||= [:hard_breaks]
+ text = sanitize(text) unless text.html_safe? || options.delete(:safe)
if text.blank?
""
else
textilized = RedCloth.new(text, options)
textilized.to_html
- end
+ end.html_safe
end
# Returns the text with all the Textile codes turned into HTML tags,
@@ -271,8 +274,8 @@ def textilize(text, *options)
#
# textilize_without_paragraph("Visit the Rails website "here":http://www.rubyonrails.org/.)
# # => "Visit the Rails website <a href="http://www.rubyonrails.org/">here</a>."
- def textilize_without_paragraph(text)
- textiled = textilize(text)
+ def textilize_without_paragraph(text, *options)
+ textiled = textilize(text, options)
if textiled[0..2] == "<p>" then textiled = textiled[3..-1] end
if textiled[-4..-1] == "</p>" then textiled = textiled[0..-5] end
return textiled
@@ -295,8 +298,9 @@ def textilize_without_paragraph(text)
#
# markdown('![The ROR logo](http://rubyonrails.com/images/rails.png "Ruby on Rails")')
# # => '<p><img src="http://rubyonrails.com/images/rails.png" alt="The ROR logo" title="Ruby on Rails" /></p>'
- def markdown(text)
- text.blank? ? "" : BlueCloth.new(text).to_html
+ def markdown(text, options = {})
+ text = sanitize(text) unless options[:safe]
+ (text.blank? ? "" : BlueCloth.new(text).to_html).html_safe
end
# Returns +text+ transformed into HTML using simple formatting rules.
@@ -320,14 +324,15 @@ def markdown(text)
#
# simple_format("Look ma! A class!", :class => 'description')
# # => "<p class='description'>Look ma! A class!</p>"
- def simple_format(text, html_options={})
+ def simple_format(text, html_options={}, options={})
+ text = '' if text.nil?
start_tag = tag('p', html_options, true)
- text = h(text)
+ text = sanitize(text) unless text.html_safe? || options[:safe]
text.gsub!(/\r\n?/, "\n") # \r\n and \r -> \n
text.gsub!(/\n\n+/, "</p>\n\n#{start_tag}") # 2+ newline -> paragraph
text.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br
text.insert 0, start_tag
- text.safe_concat("</p>")
+ text.html_safe.safe_concat("</p>")
end
# Turns all URLs and e-mail addresses into clickable links. The <tt>:link</tt> option
@@ -368,7 +373,7 @@ def simple_format(text, html_options={})
# # => "Welcome to my new blog at <a href=\"http://www.myblog.com/\" target=\"_blank\">http://www.myblog.com</a>.
# Please e-mail me at <a href=\"mailto:me@email.com\">me@email.com</a>."
def auto_link(text, *args, &block)#link = :all, html = {}, &block)
- return '' if text.blank?
+ return ''.html_safe if text.blank?
options = args.size == 2 ? {} : args.extract_options! # this is necessary because the old auto_link API has a Hash as its last parameter
unless args.empty?
@@ -378,9 +383,9 @@ def auto_link(text, *args, &block)#link = :all, html = {}, &block)
options.reverse_merge!(:link => :all, :html => {})
case options[:link].to_sym
- when :all then auto_link_email_addresses(auto_link_urls(text, options[:html], &block), options[:html], &block)
+ when :all then auto_link_email_addresses(auto_link_urls(text, options[:html], options, &block), options[:html], &block)
when :email_addresses then auto_link_email_addresses(text, options[:html], &block)
- when :urls then auto_link_urls(text, options[:html], &block)
+ when :urls then auto_link_urls(text, options[:html], options, &block)
end
end
@@ -544,7 +549,7 @@ def set_cycle(name, cycle_object)
# Turns all urls into clickable links. If a block is given, each url
# is yielded and the result is used as the link text.
- def auto_link_urls(text, html_options = {})
+ def auto_link_urls(text, html_options = {}, options = {})
link_attributes = html_options.stringify_keys
text.gsub(AUTO_LINK_RE) do
scheme, href = $1, $&
@@ -566,21 +571,22 @@ def auto_link_urls(text, html_options = {})
link_text = block_given?? yield(href) : href
href = 'http://' + href unless scheme
- content_tag(:a, link_text, link_attributes.merge('href' => href)) + punctuation.reverse.join('')
+ content_tag(:a, link_text, link_attributes.merge('href' => href), !(options[:safe] || text.html_safe?)) + punctuation.reverse.join('')
end
- end
+ end.html_safe
end
# Turns all email addresses into clickable links. If a block is given,
# each email is yielded and the result is used as the link text.
- def auto_link_email_addresses(text, html_options = {})
+ def auto_link_email_addresses(text, html_options = {}, options = {})
text.gsub(AUTO_EMAIL_RE) do
text = $&
if auto_linked?($`, $')
- text
+ text.html_safe
else
display_text = (block_given?) ? yield(text) : text
+ display_text = sanitize(display_text) unless options[:safe]
mail_to text, display_text, html_options
end
end
View
74 actionpack/lib/action_view/lookup_context.rb
@@ -13,8 +13,13 @@ class LookupContext #:nodoc:
mattr_accessor :registered_details
self.registered_details = []
+ mattr_accessor :registered_detail_setters
+ self.registered_detail_setters = []
+
def self.register_detail(name, options = {}, &block)
self.registered_details << name
+ self.registered_detail_setters << [name, "#{name}="]
+
Accessors.send :define_method, :"_#{name}_defaults", &block
Accessors.module_eval <<-METHOD, __FILE__, __LINE__ + 1
def #{name}
@@ -23,12 +28,7 @@ def #{name}
def #{name}=(value)
value = Array.wrap(value.presence || _#{name}_defaults)
-
- if value != @details[:#{name}]
- @details_key = nil
- @details = @details.dup if @details.frozen?
- @details[:#{name}] = value.freeze
- end
+ _set_detail(:#{name}, value) if value != @details[:#{name}]
end
METHOD
end
@@ -59,8 +59,11 @@ def initialize
def initialize(view_paths, details = {})
@details, @details_key = { :handlers => default_handlers }, nil
@frozen_formats, @skip_default_locale = false, false
+
self.view_paths = view_paths
- self.update_details(details, true)
+ self.registered_detail_setters.each do |key, setter|
+ send(setter, details[key])
+ end
end
module ViewPaths
@@ -116,11 +119,11 @@ def normalize_name(name, prefix) #:nodoc:
end
def default_handlers #:nodoc:
- @default_handlers ||= Template::Handlers.extensions
+ @@default_handlers ||= Template::Handlers.extensions
end
def handlers_regexp #:nodoc:
- @handlers_regexp ||= /\.(?:#{default_handlers.join('|')})$/
+ @@handlers_regexp ||= /\.(?:#{default_handlers.join('|')})$/
end
end
@@ -141,10 +144,13 @@ def freeze_formats(formats, unless_frozen=false) #:nodoc:
end
# Overload formats= to reject [:"*/*"] values.
- def formats=(value)
- value = nil if value == [:"*/*"]
- value << :html if value == [:js]
- super(value)
+ def formats=(values)
+ if values && values.size == 1
+ value = values.first
+ values = nil if value == :"*/*"
+ values << :html if value == :js
+ end
+ super(values)
end
# Do not use the default locale on template lookup.
@@ -170,24 +176,48 @@ def locale=(value)
super(@skip_default_locale ? I18n.locale : _locale_defaults)
end
+ # A method which only uses the first format in the formats array for layout lookup.
+ # This method plays straight with instance variables for performance reasons.
+ def with_layout_format
+ if formats.size == 1
+ yield
+ else
+ old_formats = formats
+ _set_detail(:formats, formats[0,1])
+
+ begin
+ yield
+ ensure
+ _set_detail(:formats, old_formats)
+ end
+ end
+ end
+
# Update the details keys by merging the given hash into the current
# details hash. If a block is given, the details are modified just during
# the execution of the block and reverted to the previous value after.
- def update_details(new_details, force=false)
+ def update_details(new_details)
old_details = @details.dup
- registered_details.each do |key|
- send(:"#{key}=", new_details[key]) if force || new_details.key?(key)
+ registered_detail_setters.each do |key, setter|
+ send(setter, new_details[key]) if new_details.key?(key)
end
- if block_given?
- begin
- yield
- ensure
- @details = old_details
- end
+ begin
+ yield
+ ensure
+ @details_key = nil
+ @details = old_details
end
end
+
+ protected
+
+ def _set_detail(key, value)
+ @details_key = nil
+ @details = @details.dup if @details.frozen?
+ @details[key] = value.freeze
+ end
end
include Accessors
View
15 actionpack/lib/action_view/render/layouts.rb
@@ -57,15 +57,11 @@ def _layout_for(name = nil, &block) #:nodoc:
# This is the method which actually finds the layout using details in the lookup
# context object. If no layout is found, it checkes if at least a layout with
# the given name exists across all details before raising the error.
- #
- # If self.formats contains several formats, just the first one is considered in
- # the layout lookup.
def find_layout(layout)
begin
- if formats.size == 1
- _find_layout(layout)
- else
- update_details(:formats => self.formats.first){ _find_layout(layout) }
+ with_layout_format do
+ layout =~ /^\// ?
+ with_fallbacks { find_template(layout) } : find_template(layout)
end
rescue ActionView::MissingTemplate => e
update_details(:formats => nil) do
@@ -74,11 +70,6 @@ def find_layout(layout)
end
end
- def _find_layout(layout) #:nodoc:
- layout =~ /^\// ?
- with_fallbacks { find_template(layout) } : find_template(layout)
- end
-
# Contains the logic that actually renders the layout.
def _render_layout(layout, locals, &block) #:nodoc:
layout.render(self, locals){ |*name| _layout_for(*name, &block) }
View
2 actionpack/lib/action_view/template/handlers.rb
@@ -19,7 +19,7 @@ def self.extended(base)
@@default_template_handlers = nil
def self.extensions
- @@template_handlers.keys
+ @@template_extensions ||= @@template_handlers.keys
end
# Register a class that knows how to handle template files with the given
View
3 actionpack/test/controller/new_base/render_rjs_test.rb
@@ -2,7 +2,10 @@
module RenderRjs
class BasicController < ActionController::Base
+ layout "application", :only => :index_respond_to
+
self.view_paths = [ActionView::FixtureResolver.new(
+ "layouts/application.html.erb" => "",
"render_rjs/basic/index.js.rjs" => "page[:customer].replace_html render(:partial => 'customer')",
"render_rjs/basic/index_html.js.rjs" => "page[:customer].replace_html :partial => 'customer'",
"render_rjs/basic/index_no_js.js.erb" => "<%= render(:partial => 'developer') %>",
View
12 actionpack/test/dispatch/routing_test.rb
@@ -28,6 +28,10 @@ def self.matches?(request)
post :reset
resource :info
+
+ member do
+ get :crush
+ end
end
match 'account/logout' => redirect("/logout"), :as => :logout_redirect
@@ -352,6 +356,14 @@ def test_session_info_nested_singleton_resource
end
end
+ def test_member_on_resource
+ with_test_routes do
+ get '/session/crush'
+ assert_equal 'sessions#crush', @response.body
+ assert_equal '/session/crush', crush_session_path
+ end
+ end
+
def test_redirect_modulo
with_test_routes do
get '/account/modulo/name'
View
16 actionpack/test/template/lookup_context_test.rb
@@ -26,18 +26,6 @@ def teardown
assert_equal :en, @lookup_context.locale
end
- test "allows me to update details" do
- @lookup_context.update_details(:formats => [:html], :locale => :pt)
- assert_equal [:html], @lookup_context.formats
- assert_equal :pt, @lookup_context.locale
- end
-
- test "allows me to update an specific detail" do
- @lookup_context.update_details(:locale => :pt)
- assert_equal :pt, I18n.locale
- assert_equal :pt, @lookup_context.locale
- end
-
test "allows me to freeze and retrieve frozen formats" do
@lookup_context.formats.freeze
assert @lookup_context.formats.frozen?
@@ -54,7 +42,7 @@ def teardown
end
test "provides getters and setters for formats" do
- @lookup_context.formats = :html
+ @lookup_context.formats = [:html]
assert_equal [:html], @lookup_context.formats
end
@@ -138,7 +126,7 @@ def teardown
keys << @lookup_context.details_key
assert_equal 2, keys.uniq.size
- @lookup_context.formats = :html
+ @lookup_context.formats = [:html]
keys << @lookup_context.details_key
assert_equal 3, keys.uniq.size
View
2 actionpack/test/template/tag_helper_test.rb
@@ -39,6 +39,8 @@ def test_content_tag
content_tag("a", "Create", :href => "create")
assert_equal "<p>&lt;script&gt;evil_js&lt;/script&gt;</p>",
content_tag(:p, '<script>evil_js</script>')
+ assert_equal "<p><script>evil_js</script></p>",
+ content_tag(:p, '<script>evil_js</script>', nil, false)
end
def test_content_tag_with_block_in_erb
View
102 actionpack/test/template/text_helper_test.rb
@@ -45,19 +45,42 @@ def test_simple_format_should_be_html_safe
assert simple_format("<b> test with html tags </b>").html_safe?
end
- def test_simple_format_should_escape_unsafe_input
- assert_equal "<p>&lt;b&gt; test with unsafe string &lt;/b&gt;</p>", simple_format("<b> test with unsafe string </b>")
+ def test_simple_format_should_sanitize_unsafe_input
+ assert_equal "<p><b> test with unsafe string </b></p>", simple_format("<b> test with unsafe string </b><script>code!</script>")
end
- def test_simple_format_should_not_escape_safe_input
+ def test_simple_format_should_not_sanitize_input_if_safe_option
+ assert_equal "<p><b> test with unsafe string </b><script>code!</script></p>", simple_format("<b> test with unsafe string </b><script>code!</script>", {}, :safe => true)
+ end
+
+ def test_simple_format_should_not_sanitize_safe_input
assert_equal "<p><b> test with safe string </b></p>", simple_format("<b> test with safe string </b>".html_safe)
end
+ def test_truncate_should_be_html_safe
+ assert truncate("Hello World!", :length => 12).html_safe?
+ end
+
def test_truncate
assert_equal "Hello World!", truncate("Hello World!", :length => 12)
assert_equal "Hello Wor...", truncate("Hello World!!", :length => 12)
end
+ def test_truncate_should_sanitize_unsafe_input
+ assert_equal "Hello World!", truncate("Hello <script>code!</script>World!", :length => 12)
+ assert_equal "Hello Wor...", truncate("Hello <script>code!</script>World!!", :length => 12)
+ end
+
+ def test_truncate_should_not_sanitize_input_if_safe_option
+ assert_equal "Hello <sc...", truncate("Hello <script>code!</script>World!", :length => 12, :safe => true)
+ assert_equal "Hello <sc...", truncate("Hello <script>code!</script>World!!", :length => 12, :safe => true)
+ end
+
+ def test_truncate_should_not_sanitize_safe_input
+ assert_equal "Hello <sc...", truncate("Hello <script>code!</script>World!".html_safe, :length => 12)
+ assert_equal "Hello <sc...", truncate("Hello <script>code!</script>World!!".html_safe, :length => 12)
+ end
+
def test_truncate_should_use_default_length_of_30
str = "This is a string that will go longer then the default truncate length of 30"
assert_equal str[0...27] + "...", truncate(str)
@@ -93,7 +116,11 @@ def test_truncate_multibyte
end
end
- def test_highlighter
+ def test_highlight_should_be_html_safe
+ assert highlight("This is a beautiful morning", "beautiful").html_safe?
+ end
+
+ def test_highlight
assert_equal(
"This is a <strong class=\"highlight\">beautiful</strong> morning",
highlight("This is a beautiful morning", "beautiful")
@@ -117,6 +144,27 @@ def test_highlighter
assert_equal ' ', highlight(' ', 'blank text is returned verbatim')
end
+ def test_highlight_should_sanitize_unsafe_input
+ assert_equal(
+ "This is a <strong class=\"highlight\">beautiful</strong> morning",
+ highlight("This is a beautiful morning<script>code!</script>", "beautiful")
+ )
+ end
+
+ def test_highlight_should_not_sanitize_input_if_safe_option
+ assert_equal(
+ "This is a <strong class=\"highlight\">beautiful</strong> morning<script>code!</script>",
+ highlight("This is a beautiful morning<script>code!</script>", "beautiful", :safe => true)
+ )
+ end
+
+ def test_highlight_should_not_sanitize_safe_input
+ assert_equal(
+ "This is a <strong class=\"highlight\">beautiful</strong> morning<script>code!</script>",
+ highlight("This is a beautiful morning<script>code!</script>".html_safe, "beautiful")
+ )
+ end
+
def test_highlight_with_regexp
assert_equal(
"This is a <strong class=\"highlight\">beautiful!</strong> morning",
@@ -163,7 +211,7 @@ def test_highlight_with_html
highlight("<p class=\"beautiful\">This is a beautiful morning, but also a beautiful day</p>", "beautiful")
)
assert_equal(
- "<p>This is a <strong class=\"highlight\">beautiful</strong> <a href=\"http://example.com/beautiful\#top?what=beautiful%20morning&when=now+then\">morning</a>, but also a <strong class=\"highlight\">beautiful</strong> day</p>",
+ "<p>This is a <strong class=\"highlight\">beautiful</strong> <a href=\"http://example.com/beautiful\#top?what=beautiful%20morning&amp;when=now+then\">morning</a>, but also a <strong class=\"highlight\">beautiful</strong> day</p>",
highlight("<p>This is a beautiful <a href=\"http://example.com/beautiful\#top?what=beautiful%20morning&when=now+then\">morning</a>, but also a beautiful day</p>", "beautiful")
)
end
@@ -286,7 +334,17 @@ def generate_result(link_text, href = nil)
%{<a href="#{CGI::escapeHTML href}">#{CGI::escapeHTML link_text}</a>}
end
- def test_auto_linking
+ def test_auto_link_should_be_html_safe
+ email_raw = 'santiago@wyeworks.com'
+ link_raw = 'http://www.rubyonrails.org'
+
+ assert auto_link(nil).html_safe?
+ assert auto_link('').html_safe?
+ assert auto_link("#{link_raw} #{link_raw} #{link_raw}").html_safe?
+ assert auto_link("hello #{email_raw}").html_safe?
+ end
+
+ def test_auto_link
email_raw = 'david@loudthinking.com'
email_result = %{<a href="mailto:#{email_raw}">#{email_raw}</a>}
link_raw = 'http://www.rubyonrails.com'
@@ -378,6 +436,21 @@ def test_auto_linking
assert_equal %(<p>#{link10_result} Link</p>), auto_link("<p>#{link10_raw} Link</p>")
end
+ def test_auto_link_should_sanitize_unsafe_input
+ link_raw = %{http://www.rubyonrails.com?id=1&num=2}
+ assert_equal %{<a href="http://www.rubyonrails.com?id=1&amp;num=2">http://www.rubyonrails.com?id=1&amp;num=2</a>}, auto_link(link_raw)
+ end
+
+ def test_auto_link_should_sanitize_unsafe_input
+ link_raw = %{http://www.rubyonrails.com?id=1&num=2}
+ assert_equal %{<a href="http://www.rubyonrails.com?id=1&num=2">http://www.rubyonrails.com?id=1&num=2</a>}, auto_link(link_raw, :safe => true)
+ end
+
+ def test_auto_link_should_not_sanitize_safe_input
+ link_raw = %{http://www.rubyonrails.com?id=1&num=2}
+ assert_equal %{<a href="http://www.rubyonrails.com?id=1&num=2">http://www.rubyonrails.com?id=1&num=2</a>}, auto_link(link_raw.html_safe)
+ end
+
def test_auto_link_other_protocols
ftp_raw = 'ftp://example.com/file.txt'
assert_equal %(Download #{generate_result(ftp_raw)}), auto_link("Download #{ftp_raw}")
@@ -587,7 +660,12 @@ def test_cycle_no_instance_variable_clashes
assert_equal(%w{Specialized Fuji Giant}, @cycles)
end
+ # TODO test textilize_without_paragraph and markdown
if defined? RedCloth
+ def test_textilize_should_be_html_safe
+ assert textilize("*This is Textile!* Rejoice!").html_safe?
+ end
+
def test_textilize
assert_equal("<p><strong>This is Textile!</strong> Rejoice!</p>", textilize("*This is Textile!* Rejoice!"))
end
@@ -600,6 +678,18 @@ def test_textilize_with_options
assert_equal("<p>This is worded &lt;strong&gt;strongly&lt;/strong&gt;</p>", textilize("This is worded <strong>strongly</strong>", :filter_html))
end
+ def test_textilize_should_sanitize_unsafe_input
+ assert_equal("<p>This is worded <strong>strongly</strong></p>", textilize("This is worded <strong>strongly</strong><script>code!</script>"))
+ end
+
+ def test_textilize_should_not_sanitize_input_if_safe_option
+ assert_equal("<p>This is worded <strong>strongly</strong><script>code!</script></p>", textilize("This is worded <strong>strongly</strong><script>code!</script>", :safe))
+ end
+
+ def test_textilize_should_not_sanitize_safe_input
+ assert_equal("<p>This is worded <strong>strongly</strong><script>code!</script></p>", textilize("This is worded <strong>strongly</strong><script>code!</script>".html_safe))
+ end
+
def test_textilize_with_hard_breaks
assert_equal("<p>This is one scary world.<br />\n True.</p>", textilize("This is one scary world.\n True."))
end
View
2 activemodel/activemodel.gemspec
@@ -21,5 +21,5 @@ Gem::Specification.new do |s|
s.add_dependency('activesupport', version)
s.add_dependency('builder', '~> 2.1.2')
- s.add_dependency('i18n', '~> 0.4.0')
+ s.add_dependency('i18n', '~> 0.4.1')
end
View
1 activemodel/lib/active_model/observing.rb
@@ -2,6 +2,7 @@
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/module/aliasing'
require 'active_support/core_ext/string/inflections'
+require 'active_support/core_ext/string/conversions'
module ActiveModel
module Observing
View
1 activerecord/lib/active_record/associations.rb
@@ -2,6 +2,7 @@
require 'active_support/core_ext/enumerable'
require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/string/conversions'
module ActiveRecord
class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc:
View
3 activerecord/lib/active_record/associations/association_collection.rb
@@ -411,7 +411,8 @@ def method_missing(method, *args)
end
elsif @reflection.klass.scopes[method]
@_named_scopes_cache ||= {}
- @_named_scopes_cache[method] ||= with_scope(construct_scope) { @reflection.klass.send(method, *args) }
+ @_named_scopes_cache[method] ||= {}
+ @_named_scopes_cache[method][args] ||= with_scope(construct_scope) { @reflection.klass.send(method, *args) }
else
with_scope(construct_scope) do
if block_given?
View
14 activerecord/lib/active_record/autosave_association.rb
@@ -1,3 +1,5 @@
+require 'active_support/core_ext/array/wrap'
+
module ActiveRecord
# AutosaveAssociation is a module that takes care of automatically saving
# your associations when the parent is saved. In addition to saving, it
@@ -238,16 +240,10 @@ def associated_records_to_validate_or_save(association, new_record, autosave)
# go through nested autosave associations that are loaded in memory (without loading
# any new ones), and return true if is changed for autosave
def nested_records_changed_for_autosave?
- self.class.reflect_on_all_autosave_associations.each do |reflection|
- if association = association_instance_get(reflection.name)
- if [:belongs_to, :has_one].include?(reflection.macro)
- return true if association.target && association.target.changed_for_autosave?
- else
- association.target.each {|record| return true if record.changed_for_autosave? }
- end
- end
+ self.class.reflect_on_all_autosave_associations.any? do |reflection|
+ association = association_instance_get(reflection.name)
+ association && Array.wrap(association.target).any?(&:changed_for_autosave?)
end
- false
end
# Validate the association if <tt>:validate</tt> or <tt>:autosave</tt> is
View
2 activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -211,7 +211,7 @@ def checkout
# calling +checkout+ on this pool.
def checkin(conn)
@connection_mutex.synchronize do
- conn.run_callbacks :checkin do
+ conn.send(:_run_checkin_callbacks) do
@checked_out.delete conn
@queue.signal
end
View
57 activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -3,48 +3,6 @@
require 'active_support/core_ext/object/blank'
require 'set'
-module MysqlCompat #:nodoc:
- # add all_hashes method to standard mysql-c bindings or pure ruby version
- def self.define_all_hashes_method!
- raise 'Mysql not loaded' unless defined?(::Mysql)
-
- target = defined?(Mysql::Result) ? Mysql::Result : MysqlRes
- return if target.instance_methods.include?('all_hashes') ||
- target.instance_methods.include?(:all_hashes)
-
- # Ruby driver has a version string and returns null values in each_hash
- # C driver >= 2.7 returns null values in each_hash
- if Mysql.const_defined?(:VERSION) && (Mysql::VERSION.is_a?(String) || Mysql::VERSION >= 20700)
- target.class_eval <<-'end_eval', __FILE__, __LINE__ + 1
- def all_hashes # def all_hashes
- rows = [] # rows = []
- each_hash { |row| rows << row } # each_hash { |row| rows << row }
- rows # rows
- end # end
- end_eval
-
- # adapters before 2.7 don't have a version constant
- # and don't return null values in each_hash
- else
- target.class_eval <<-'end_eval', __FILE__, __LINE__ + 1
- def all_hashes # def all_hashes
- rows = [] # rows = []
- all_fields = fetch_fields.inject({}) { |fields, f| # all_fields = fetch_fields.inject({}) { |fields, f|
- fields[f.name] = nil; fields # fields[f.name] = nil; fields
- } # }
- each_hash { |row| rows << all_fields.dup.update(row) } # each_hash { |row| rows << all_fields.dup.update(row) }
- rows # rows
- end # end
- end_eval
- end
-
- unless target.instance_methods.include?('all_hashes') ||
- target.instance_methods.include?(:all_hashes)
- raise "Failed to defined #{target.name}#all_hashes method. Mysql::VERSION = #{Mysql::VERSION.inspect}"
- end
- end
-end
-
module ActiveRecord
class Base
# Establishes a connection to the database that's used by all Active Record objects.
@@ -57,17 +15,17 @@ def self.mysql_connection(config) # :nodoc:
password = config[:password].to_s
database = config[:database]
- # Require the MySQL driver and define Mysql::Result.all_hashes
unless defined? Mysql
begin
- require_library_or_gem('mysql')
+ require 'mysql'
rescue LoadError
- $stderr.puts '!!! Please install the mysql gem and try again: gem install mysql.'
- raise
+ raise "!!! Missing the mysql gem. Add it to your Gemfile: gem 'mysql', '2.8.1'"
end
- end
- MysqlCompat.define_all_hashes_method!
+ unless defined?(Mysql::Result) && Mysql::Result.method_defined?(:each_hash)
+ raise "!!! Outdated mysql gem. Upgrade to 2.8.1 or later. In your Gemfile: gem 'mysql', '2.8.1'"
+ end
+ end
mysql = Mysql.init
mysql.ssl_set(config[:sslkey], config[:sslcert], config[:sslca], config[:sslcapath], config[:sslcipher]) if config[:sslca] || config[:sslkey]
@@ -656,7 +614,8 @@ def configure_connection
def select(sql, name = nil)
@connection.query_with_result = true
result = execute(sql, name)
- rows = result.all_hashes
+ rows = []
+ result.each_hash { |row| rows << row }
result.free
rows
end
View
14 activerecord/test/cases/associations/eager_load_nested_include_test.rb
@@ -17,7 +17,7 @@ def remember; self.class.remembered << self; end
module ClassMethods
def remembered; @@remembered ||= []; end
- def random_element; @@remembered.random_element; end
+ def sample; @@remembered.sample; end
end
end
@@ -79,14 +79,14 @@ def generate_test_object_graphs
[Circle, Square, Triangle, NonPolyOne, NonPolyTwo].map(&:create!)
end
1.upto(NUM_SIMPLE_OBJS) do
- PaintColor.create!(:non_poly_one_id => NonPolyOne.random_element.id)
- PaintTexture.create!(:non_poly_two_id => NonPolyTwo.random_element.id)
+ PaintColor.create!(:non_poly_one_id => NonPolyOne.sample.id)
+ PaintTexture.create!(:non_poly_two_id => NonPolyTwo.sample.id)
end
1.upto(NUM_SHAPE_EXPRESSIONS) do
- shape_type = [Circle, Square, Triangle].random_element
- paint_type = [PaintColor, PaintTexture].random_element
- ShapeExpression.create!(:shape_type => shape_type.to_s, :shape_id => shape_type.random_element.id,
- :paint_type => paint_type.to_s, :paint_id => paint_type.random_element.id)
+ shape_type = [Circle, Square, Triangle].sample
+ paint_type = [PaintColor, PaintTexture].sample
+ ShapeExpression.create!(:shape_type => shape_type.to_s, :shape_id => shape_type.sample.id,
+ :paint_type => paint_type.to_s, :paint_id => paint_type.sample.id)
end
end
View
8 activerecord/test/cases/autosave_association_test.rb
@@ -1149,7 +1149,7 @@ def setup
include AutosaveAssociationOnACollectionAssociationTests
end
-class TestAutosaveAssociationValidationsOnAHasManyAssocication < ActiveRecord::TestCase
+class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::TestCase
self.use_transactional_fixtures = false
def setup
@@ -1165,7 +1165,7 @@ def setup
end
end
-class TestAutosaveAssociationValidationsOnAHasOneAssocication < ActiveRecord::TestCase
+class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::TestCase
self.use_transactional_fixtures = false
def setup
@@ -1186,7 +1186,7 @@ def setup
end
end
-class TestAutosaveAssociationValidationsOnABelongsToAssocication < ActiveRecord::TestCase
+class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord::TestCase
self.use_transactional_fixtures = false
def setup
@@ -1206,7 +1206,7 @@ def setup
end
end
-class TestAutosaveAssociationValidationsOnAHABTMAssocication < ActiveRecord::TestCase
+class TestAutosaveAssociationValidationsOnAHABTMAssociation < ActiveRecord::TestCase
self.use_transactional_fixtures = false
def setup
View
15 activerecord/test/cases/named_scope_test.rb
@@ -301,7 +301,7 @@ def test_find_all_should_behave_like_select
end
def test_rand_should_select_a_random_object_from_proxy
- assert_kind_of Topic, Topic.approved.random_element
+ assert_kind_of Topic, Topic.approved.sample
end
def test_should_use_where_in_query_for_named_scope
@@ -428,6 +428,19 @@ def test_named_scopes_are_cached_on_associations
assert_no_queries { post.comments.containing_the_letter_e.all }
end
+ def test_named_scopes_with_arguments_are_cached_on_associations
+ post = posts(:welcome)
+
+ one = post.comments.limit_by(1).all
+ assert_equal 1, one.size
+
+ two = post.comments.limit_by(2).all
+ assert_equal 2, two.size
+
+ assert_no_queries { post.comments.limit_by(1).all }
+ assert_no_queries { post.comments.limit_by(2).all }
+ end
+
def test_named_scopes_are_reset_on_association_reload
post = posts(:welcome)
View
4 activerecord/test/cases/nested_attributes_test.rb
@@ -734,7 +734,7 @@ def test_should_update_existing_records_with_non_standard_primary_key
end
end
-class TestHasOneAutosaveAssoictaionWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase
+class TestHasOneAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase
self.use_transactional_fixtures = false
def setup
@@ -774,7 +774,7 @@ def setup
end
end
-class TestHasManyAutosaveAssoictaionWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase
+class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase
self.use_transactional_fixtures = false
def setup
View
1 activerecord/test/models/comment.rb
@@ -1,4 +1,5 @@
class Comment < ActiveRecord::Base
+ scope :limit_by, lambda {|l| limit(l) }
scope :containing_the_letter_e, :conditions => "comments.body LIKE '%e%'"
scope :for_first_post, :conditions => { :post_id => 1 }
scope :for_first_author,
View
2 activesupport/CHANGELOG
@@ -4,7 +4,7 @@
* Ruby 1.9: support UTF-8 case folding. #4595 [Norman Clarke]
-* Renames Array#rand -> Array#random_element. [Santiago Pastorino, Rizwan Reza]
+* Removes Array#rand and backports Array#sample from Ruby 1.9, thanks to Marc-Andre Lafortune. [fxn]
* Ruby 1.9: Renames last_(month|year) to prev_(month|year) in Date and Time. [fxn]
View
9 activesupport/lib/active_support/callbacks.rb
@@ -390,9 +390,12 @@ def __define_runner(symbol) #:nodoc:
undef_method "_run_#{symbol}_callbacks" if method_defined?("_run_#{symbol}_callbacks")
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
def _run_#{symbol}_callbacks(key = nil, &blk)
- if self.class.send("_update_#{symbol}_superclass_callbacks")
- self.class.__define_runner(#{symbol.inspect})
- return _run_#{symbol}_callbacks(key, &blk)
+ @_initialized_#{symbol}_callbacks ||= begin
+ if self.class.send("_update_#{symbol}_superclass_callbacks")
+ self.class.__define_runner(#{symbol.inspect})
+ return _run_#{symbol}_callbacks(key, &blk)
+ end
+ true
end
if key
View
22 activesupport/lib/active_support/core_ext/array/random_access.rb
@@ -1,6 +1,20 @@
class Array
- # Returns a random element from the array.
- def random_element
- self[Kernel.rand(length)]
- end
+ # Backport of Array#sample based on Marc-Andre Lafortune's http://github.com/marcandre/backports/
+ def sample(n=nil)
+ return self[Kernel.rand(size)] if n.nil?
+ n = n.to_int
+ rescue Exception => e
+ raise TypeError, "Coercion error: #{n.inspect}.to_int => Integer failed:\n(#{e.message})"
+ else
+ raise TypeError, "Coercion error: obj.to_int did NOT return an Integer (was #{n.class})" unless n.kind_of? Integer
+ raise ArgumentError, "negative array size" if n < 0
+ n = size if n > size
+ result = Array.new(self)
+ n.times do |i|
+ r = i + Kernel.rand(size - i)
+ result[i], result[r] = result[r], result[i]
+ end
+ result[n..size] = []
+ result
+ end unless method_defined? :sample
end
View
1 activesupport/lib/active_support/core_ext/load_error.rb
@@ -3,6 +3,7 @@ class LoadError
/^no such file to load -- (.+)$/i,
/^Missing \w+ (?:file\s*)?([^\s]+.rb)$/i,
/^Missing API definition file in (.+)$/i,
+ /^cannot load such file -- (.+)$/i,
]
def path
View
11 activesupport/lib/active_support/core_ext/string/conversions.rb
@@ -47,4 +47,15 @@ def to_datetime
d[5] += d.pop
::DateTime.civil(*d)
end
+
+ # +constantize+ tries to find a declared constant with the name specified
+ # in the string. It raises a NameError when the name is not in CamelCase
+ # or is not initialized.
+ #
+ # Examples
+ # "Module".constantize # => Module
+ # "Class".constantize # => Class
+ def constantize
+ ActiveSupport::Inflector.constantize(self)
+ end
end
View
11 activesupport/lib/active_support/core_ext/string/inflections.rb
@@ -146,15 +146,4 @@ def humanize
def foreign_key(separate_class_name_and_id_with_underscore = true)
ActiveSupport::Inflector.foreign_key(self, separate_class_name_and_id_with_underscore)
end
-
- # +constantize+ tries to find a declared constant with the name specified
- # in the string. It raises a NameError when the name is not in CamelCase
- # or is not initialized.
- #
- # Examples
- # "Module".constantize # => Module
- # "Class".constantize # => Class
- def constantize
- ActiveSupport::Inflector.constantize(self)
- end
end
View
8 activesupport/lib/active_support/core_ext/uri.rb
@@ -6,11 +6,15 @@
str = "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E" # Ni-ho-nn-go in UTF-8, means Japanese.
parser = URI::Parser.new
+
unless str == parser.unescape(parser.escape(str))
URI::Parser.class_eval do
remove_method :unescape
- def unescape(str, escaped = @regexp[:ESCAPED])
- enc = (str.encoding == Encoding::US_ASCII) ? Encoding::UTF_8 : str.encoding
+ def unescape(str, escaped = /%[a-fA-F\d]{2}/)
+ # TODO: Are we actually sure that ASCII == UTF-8?
+ # YK: My initial experiments say yes, but let's be sure please
+ enc = str.encoding
+ enc = Encoding::UTF_8 if enc == Encoding::US_ASCII
str.gsub(escaped) { [$&[1, 2].hex].pack('C') }.force_encoding(enc)
end
end
View
32 activesupport/lib/active_support/dependencies.rb
@@ -47,6 +47,9 @@ module Dependencies #:nodoc:
mattr_accessor :autoloaded_constants
self.autoloaded_constants = []
+ mattr_accessor :references
+ self.references = {}
+
# An array of constant names that need to be unloaded on every request. Used
# to allow arbitrary constants to be marked for unloading.
mattr_accessor :explicitly_unloadable_constants
@@ -476,9 +479,37 @@ def load_missing_constant(from_mod, const_name)
def remove_unloadable_constants!
autoloaded_constants.each { |const| remove_constant const }
autoloaded_constants.clear
+ Reference.clear!
explicitly_unloadable_constants.each { |const| remove_constant const }
end
+ class Reference
+ @@constants = Hash.new { |h, k| h[k] = Inflector.constantize(k) }
+
+ attr_reader :name
+
+ def initialize(name)
+ @name = name.to_s
+ @@constants[@name] = name if name.respond_to?(:name)
+ end
+
+ def get
+ @@constants[@name]
+ end
+
+ def self.clear!
+ @@constants.clear
+ end
+ end
+
+ def ref(name)
+ references[name] ||= Reference.new(name)
+ end
+
+ def constantize(name)
+ ref(name).get
+ end
+
# Determine if the given constant has been automatically loaded.
def autoloaded?(desc)
# No name => anonymous module.
@@ -572,6 +603,7 @@ def remove_constant(const) #:nodoc:
log "removing constant #{const}"
parent.instance_eval { remove_const to_remove }
+
return true
end
View
8 activesupport/lib/active_support/message_verifier.rb
@@ -47,11 +47,11 @@ def generate(value)
def secure_compare(a, b)
return false unless a.bytesize == b.bytesize
- l = a.unpack "C#{a.bytesize}"
+ l = a.unpack "C*"
- res = 0
- b.each_byte { |byte| res |= byte ^ l.shift }
- res == 0
+ res = true
+ b.each_byte { |byte| res = (byte == l.shift) && res }
+ res
end
def generate_digest(data)
View
30 activesupport/test/core_ext/array_ext_test.rb
@@ -359,14 +359,30 @@ def test_uniq_by!
end
class ArrayExtRandomTests < ActiveSupport::TestCase
- def test_random_element_from_array
- assert_nil [].random_element
-
- Kernel.expects(:rand).with(1).returns(0)
- assert_equal 'x', ['x'].random_element
+ def test_sample_from_array
+ assert_nil [].sample
+ assert_equal [], [].sample(5)
+ assert_equal 42, [42].sample
+ assert_equal [42], [42].sample(5)
+
+ a = [:foo, :bar, 42]
+ s = a.sample(2)
+ assert_equal 2, s.size
+ assert_equal 1, (a-s).size
+ assert_equal [], a-(0..20).sum{a.sample(2)}
+
+ o = Object.new
+ def o.to_int; 1; end
+ assert_equal [0], [0].sample(o)
+
+ o = Object.new
+ assert_raises(TypeError) { [0].sample(o) }
+
+ o = Object.new
+ def o.to_int; ''; end
+ assert_raises(TypeError) { [0].sample(o) }
- Kernel.expects(:rand).with(3).returns(1)
- assert_equal 2, [1, 2, 3].random_element
+ assert_raises(ArgumentError) { [0].sample(-7) }
end
end
View
10 activesupport/test/core_ext/date_ext_test.rb
@@ -198,6 +198,16 @@ def test_advance
assert_equal Date.new(2005,2,28), Date.new(2004,2,29).advance(:years => 1) #leap day plus one year
end
+ def test_advance_does_first_years_and_then_days
+ assert_equal Date.new(2012, 2, 29), Date.new(2011, 2, 28).advance(:years => 1, :days => 1)
+ # If day was done first we would jump to 2012-03-01 instead.
+ end
+
+ def test_advance_does_first_months_and_then_days
+ assert_equal Date.new(2010, 3, 29), Date.new(2010, 2, 28).advance(:months => 1, :days => 1)
+ # If day was done first we would jump to 2010-04-01 instead.
+ end
+
def test_advance_in_calendar_reform
assert_equal Date.new(1582,10,15), Date.new(1582,10,4).advance(:days => 1)
assert_equal Date.new(1582,10,4), Date.new(1582,10,15).advance(:days => -1)
View
21 activesupport/test/dependencies_test.rb
@@ -431,6 +431,27 @@ def test_removal_from_tree_should_be_detected
end
end
+ def test_references_should_work
+ with_loading 'dependencies' do
+ root = ActiveSupport::Dependencies.load_paths.first
+ c = ActiveSupport::Dependencies.ref("ServiceOne")
+ service_one_first = ServiceOne
+ assert_equal service_one_first, c.get
+ ActiveSupport::Dependencies.clear
+ assert ! defined?(ServiceOne)
+
+ service_one_second = ServiceOne
+ assert_not_equal service_one_first, c.get
+ assert_equal service_one_second, c.get
+ end
+ end
+
+ def test_constantize_shortcut_for_cached_constant_lookups
+ with_loading 'dependencies' do
+ assert_equal ServiceOne, ActiveSupport::Dependencies.constantize("ServiceOne")
+ end
+ end
+
def test_nested_load_error_isnt_rescued
with_loading 'dependencies' do
assert_raise(MissingSourceFile) do
View
241 railties/README
@@ -3,12 +3,13 @@
Rails is a web-application framework that includes everything needed to create
database-backed web applications according to the Model-View-Control pattern.
-This pattern splits the view (also called the presentation) into "dumb" templates
-that are primarily responsible for inserting pre-built data in between HTML tags.
-The model contains the "smart" domain objects (such as Account, Product, Person,
-Post) that holds all the business logic and knows how to persist themselves to
-a database. The controller handles the incoming requests (such as Save New Account,
-Update Product, Show Post) by manipulating the model and directing data to the view.
+This pattern splits the view (also called the presentation) into "dumb"
+templates that are primarily responsible for inserting pre-built data in between
+HTML tags. The model contains the "smart" domain objects (such as Account,
+Product, Person, Post) that holds all the business logic and knows how to
+persist themselves to a database. The controller handles the incoming requests
+(such as Save New Account, Update Product, Show Post) by manipulating the model
+and directing data to the view.
In Rails, the model is handled by what's called an object-relational mapping
layer entitled Active Record. This layer allows you to present the data from
@@ -21,88 +22,65 @@ layers by its two parts: Action View and Action Controller. These two layers
are bundled in a single package due to their heavy interdependence. This is
unlike the relationship between the Active Record and Action Pack that is much
more separate. Each of these packages can be used independently outside of
-Rails. You can read more about Action Pack in
+Rails. You can read more about Action Pack in
link:files/vendor/rails/actionpack/README.html.
== Getting Started
-1. At the command prompt, start a new Rails application using the <tt>rails</tt> command
- and your application name. Ex: <tt>rails myapp</tt>
-2. Change directory into myapp and start the web server: <tt>rails server</tt> (run with --help for options)
-3. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!"
-4. Follow the guidelines to start developing your application
+1. At the command prompt, create a new Rails application:
+ <tt>rails myapp</tt> (where <tt>myapp</tt> is the application name)
+2. Change directory to <tt>myapp</tt> and start the web server:
+ <tt>cd myapp; rails server</tt> (run with --help for options)
-== Web Servers
-
-By default, Rails will try to use Mongrel if it's installed when started with <tt>rails server</tt>, otherwise
-Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails with a variety of
-other web servers.
-
-Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is
-suitable for development and deployment of Rails applications. If you have Ruby Gems installed,
-getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>.
-More info at: http://mongrel.rubyforge.org
-
-Other ruby web servers exist which can run your rails application, however <tt>rails server</tt> does
-not search for them or start them. These include {Thin}[http://code.macournoyer.com/thin/], {Ebb}[http://ebb.rubyforge.org/], and Apache with {mod_rails}[http://www.modrails.com/].
-
-For production use, often a web/proxy server such as {Apache}[http://apache.org], {Nginx}[http://nginx.net/], {LiteSpeed}[http://litespeedtech.com/], {Lighttpd}[http://www.lighttpd.net/] or {IIS}[http://www.iis.net/] is
-deployed as the front-end server, with the chosen ruby web server running in the back-end
-and receiving the proxied requests via one of several protocols (HTTP, CGI, FCGI).
-
+3. Go to http://localhost:3000/ and you'll see:
+ "Welcome aboard: You're riding the Rails!"
-== Apache .htaccess example for FCGI/CGI
+4. Follow the guidelines to start developing your application. You can find
+the following resources handy:
-General Apache options
+* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html
+* Ruby on Rails Tutorial Book: http://www.railstutorial.org/
- AddHandler fastcgi-script .fcgi
- AddHandler cgi-script .cgi
- Options +FollowSymLinks +ExecCGI
-If you don't want Rails to look in certain directories, use the following
-rewrite rules so that Apache won't rewrite certain requests.
-
- RewriteCond %{REQUEST_URI} ^/notrails.*
- RewriteRule .* - [L]
-
-Redirect all requests not available on the filesystem to Rails. By default the
-cgi dispatcher is used which is very slow, for better performance replace the
-dispatcher with the fastcgi one.
+== Web Servers
- RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
- RewriteEngine On
+By default, Rails will try to use Mongrel if it's installed when started with
+<tt>rails server</tt>, otherwise Rails will use WEBrick, the web server that
+ships with Ruby.
-If your Rails application is accessed via an Alias directive, then you MUST also
-set the RewriteBase in this htaccess file.
+Mongrel is a Ruby-based web server with a C component (which requires
+compilation) that is suitable for development. If you have Ruby Gems installed,
+getting up and running with mongrel is as easy as:
+ <tt>sudo gem install mongrel</tt>.
- Alias /myrailsapp /path/to/myrailsapp/public
- RewriteBase /myrailsapp
+You can find more info at: http://mongrel.rubyforge.org
- RewriteRule ^$ index.html [QSA]
- RewriteRule ^([^.]+)$ $1.html [QSA]
- RewriteCond %{REQUEST_FILENAME} !-f
- RewriteRule ^(.*)$ dispatch.cgi [QSA,L]
+You can alternatively run Rails applications with other Ruby web servers, e.g.,
+{Thin}[http://code.macournoyer.com/thin/], {Ebb}[http://ebb.rubyforge.org/], and
+Apache with {mod_rails}[http://www.modrails.com/]. However, <tt>rails server</tt>
+doesn't search for or start them.
-Incase Rails experiences terminal errors instead of displaying those messages you
-can supply a file here which will be rendered instead.
+For production use, often a web/proxy server, e.g., {Apache}[http://apache.org],
+{Nginx}[http://nginx.net/], {LiteSpeed}[http://litespeedtech.com/],
+{Lighttpd}[http://www.lighttpd.net/], or {IIS}[http://www.iis.net/], is deployed
+as the front end server with the chosen Ruby web server running in the back end
+and receiving the proxied requests via one of several protocols (HTTP, CGI, FCGI).
- ErrorDocument 500 /500.html
- ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly"
== Debugging Rails
-Sometimes your application goes wrong. Fortunately there are a lot of tools that
+Sometimes your application goes wrong. Fortunately there are a lot of tools that
will help you debug it and get it back on the rails.
-First area to check is the application log files. Have "tail -f" commands running
-on the server.log and development.log. Rails will automatically display debugging
-and runtime information to these files. Debugging info will also be shown in the
-browser on requests from 127.0.0.1.
+First area to check is the application log files. Have "tail -f" commands
+running on the server.log and development.log. Rails will automatically display
+debugging and runtime information to these files. Debugging info will also be
+shown in the browser on requests from 127.0.0.1.
-You can also log your own messages directly into the log file from your code using
-the Ruby logger class from inside your controllers. Example:
+You can also log your own messages directly into the log file from your code
+using the Ruby logger class from inside your controllers. Example:
class WeblogController < ActionController::Base
def destroy
@@ -114,26 +92,27 @@ the Ruby logger class from inside your controllers. Example:
The result will be a message in your log file along the lines of:
- Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1
+ Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1!
More information on how to use the logger is at http://www.ruby-doc.org/core/
-Also, Ruby documentation can be found at http://www.ruby-lang.org/ including:
+Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are
+several books available online as well:
-* The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/
-* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
+* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe)
+* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
-These two online (and free) books will bring you up to speed on the Ruby language
-and also on programming in general.
+These two books will bring you up to speed on the Ruby language and also on
+programming in general.
== Debugger
-Debugger support is available through the debugger command when you start your Mongrel or
-Webrick server with --debugger. This means that you can break out of execution at any point
-in the code, investigate and change the model, AND then resume execution!
-You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'
-Example:
+Debugger support is available through the debugger command when you start your
+Mongrel or WEBrick server with --debugger. This means that you can break out of
+execution at any point in the code, investigate and change the model, and then,
+resume execution! You need to install ruby-debug to run the server in debugging
+mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
class WeblogController < ActionController::Base
def index
@@ -146,49 +125,60 @@ So the controller will accept the action, run the first line, then present you
with a IRB prompt in the server window. Here you can do things like:
>> @posts.inspect
- => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
- #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
+ => "[#<Post:0x14a6be8
+ @attributes={"title"=>nil, "body"=>nil, "id