Skip to content
Browse files

Merge commit 'rails/master'

  • Loading branch information...
2 parents 0cf4662 + 9cd50e7 commit 991d1bc200d6fdc379bc83610bc92a4e220c669e @miloops miloops committed Oct 13, 2009
Showing with 2,595 additions and 4,019 deletions.
  1. +1 −1 actionmailer/test/fixtures/helpers/example_helper.rb
  2. +2 −0 actionpack/Gemfile
  3. +4 −6 actionpack/lib/abstract_controller/callbacks.rb
  4. +1 −1 actionpack/lib/action_controller/metal/session_management.rb
  5. +6 −1 actionpack/lib/action_dispatch/http/mime_type.rb
  6. +4 −4 actionpack/lib/action_dispatch/middleware/callbacks.rb
  7. +9 −9 actionpack/lib/action_view/base.rb
  8. +3 −3 actionpack/lib/action_view/helpers/record_tag_helper.rb
  9. +5 −2 actionpack/lib/action_view/paths.rb
  10. +4 −1 actionpack/lib/action_view/render/partials.rb
  11. +13 −9 actionpack/lib/action_view/render/rendering.rb
  12. +0 −28 actionpack/test/controller/routing_test.rb
  13. +2 −0 actionpack/test/lib/controller/fake_controllers.rb
  14. +1 −1 actionpack/test/template/record_tag_helper_test.rb
  15. +1 −1 actionpack/test/{view → template}/safe_buffer_test.rb
  16. +4 −6 activemodel/lib/active_model/validations.rb
  17. +1 −1 activerecord/lib/active_record/associations/association_collection.rb
  18. +2 −2 activerecord/lib/active_record/callbacks.rb
  19. +2 −2 activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
  20. +29 −13 activerecord/lib/active_record/nested_attributes.rb
  21. +7 −7 activerecord/lib/active_record/validations.rb
  22. +34 −4 activerecord/test/cases/nested_attributes_test.rb
  23. +1 −1 activesupport/lib/active_support/autoload.rb
  24. +7 −0 activesupport/lib/active_support/cache.rb
  25. +2 −0 activesupport/lib/active_support/cache/memory_store.rb
  26. +5 −5 activesupport/lib/active_support/cache/strategy/local_cache.rb
  27. +452 −170 activesupport/lib/active_support/callbacks.rb
  28. +283 −0 activesupport/lib/active_support/deprecated_callbacks.rb
  29. +1 −1 activesupport/lib/active_support/deprecation/behaviors.rb
  30. +0 −13 activesupport/lib/active_support/memoizable.rb
  31. +1 −1 activesupport/lib/active_support/message_verifier.rb
  32. +0 −563 activesupport/lib/active_support/new_callbacks.rb
  33. +3 −1 activesupport/lib/active_support/testing/isolation.rb
  34. +41 −28 activesupport/lib/active_support/testing/setup_and_teardown.rb
  35. +19 −0 activesupport/test/caching_test.rb
  36. +21 −21 activesupport/test/{new_callback_inheritance_test.rb → callback_inheritance_test.rb}
  37. +486 −146 activesupport/test/callbacks_test.rb
  38. +1 −0 activesupport/test/message_verifier_test.rb
  39. +0 −528 activesupport/test/new_callbacks_test.rb
  40. +2 −54 activesupport/test/test_test.rb
  41. +2 −0 ci/geminstaller.yml
  42. +2 −1 railties/Rakefile
  43. +471 −13 railties/lib/rails/application.rb
  44. +1 −5 railties/lib/rails/core.rb
  45. +1 −1 railties/lib/rails/generators.rb
  46. +6 −7 railties/lib/rails/generators/rails/app/templates/config/boot.rb
  47. +99 −0 railties/lib/rails/initializable.rb
  48. +3 −558 railties/lib/rails/initializer.rb
  49. +0 −1,137 railties/lib/rails/initializer_old.rb
  50. +89 −0 railties/test/application/generators_test.rb
  51. +194 −0 railties/test/application/initializer_test.rb
  52. +2 −2 railties/test/application/load_test.rb
  53. +101 −0 railties/test/application/plugins_test.rb
  54. +68 −0 railties/test/initializable_test.rb
  55. +51 −0 railties/test/initializer/initialize_i18n_test.rb
  56. +1 −1 railties/test/initializer/path_test.rb
  57. +0 −482 railties/test/initializer_test.rb
  58. +8 −1 railties/test/isolation/abstract_unit.rb
  59. +0 −165 railties/test/new_initializer_test.rb
  60. +10 −7 railties/test/plugin_loader_test.rb
  61. +13 −3 railties/test/plugin_locator_test.rb
  62. +13 −2 railties/test/plugin_test.rb
View
2 actionmailer/test/fixtures/helpers/example_helper.rb
@@ -1,5 +1,5 @@
module ExampleHelper
def example_format(text)
- "<em><strong><small>#{text}</small></strong></em>"
+ "<em><strong><small>#{h(text)}</small></strong></em>".html_safe!
end
end
View
2 actionpack/Gemfile
@@ -1,5 +1,7 @@
rails_root = Pathname.new(File.dirname(__FILE__)).join("..")
+Gem.sources.each { |uri| source uri }
+
gem "rack", "~> 1.0.0"
gem "rack-test", "~> 0.5.0"
gem "activesupport", "3.0.pre", :vendored_at => rails_root.join("activesupport")
View
10 actionpack/lib/abstract_controller/callbacks.rb
@@ -1,13 +1,11 @@
-require "active_support/new_callbacks"
-
module AbstractController
module Callbacks
extend ActiveSupport::Concern
- # Uses ActiveSupport::NewCallbacks as the base functionality. For
+ # Uses ActiveSupport::Callbacks as the base functionality. For
# more details on the whole callback system, read the documentation
- # for ActiveSupport::NewCallbacks.
- include ActiveSupport::NewCallbacks
+ # for ActiveSupport::Callbacks.
+ include ActiveSupport::Callbacks
included do
define_callbacks :process_action, :terminator => "response_body"
@@ -16,7 +14,7 @@ module Callbacks
# Override AbstractController::Base's process_action to run the
# process_action callbacks around the normal behavior.
def process_action(method_name)
- _run_process_action_callbacks(method_name) do
+ run_callbacks(:process_action, method_name) do
super
end
end
View
2 actionpack/lib/action_controller/metal/session_management.rb
@@ -16,7 +16,7 @@ def session_store=(store)
self.session_store = ActiveRecord::SessionStore
else
@@session_store = store.is_a?(Symbol) ?
- Session.const_get(store.to_s.camelize) :
+ ActionDispatch::Session.const_get(store.to_s.camelize) :
store
end
end
View
7 actionpack/lib/action_dispatch/http/mime_type.rb
@@ -10,7 +10,12 @@ def symbols
%w(<< concat shift unshift push pop []= clear compact! collect!
delete delete_at delete_if flatten! map! insert reject! reverse!
replace slice! sort! uniq!).each do |method|
- define_method(method) {|*args| @symbols = nil; super(*args) }
+ module_eval <<-CODE
+ def #{method}(*args)
+ @symbols = nil
+ super
+ end
+ CODE
end
end
View
8 actionpack/lib/action_dispatch/middleware/callbacks.rb
@@ -1,6 +1,6 @@
module ActionDispatch
class Callbacks
- include ActiveSupport::NewCallbacks
+ include ActiveSupport::Callbacks
define_callbacks :call, :terminator => "result == false", :rescuable => true
define_callbacks :prepare, :scope => :name
@@ -37,12 +37,12 @@ class << self
def initialize(app, prepare_each_request = false)
@app, @prepare_each_request = app, prepare_each_request
- _run_prepare_callbacks
+ run_callbacks(:prepare)
end
def call(env)
- _run_call_callbacks do
- _run_prepare_callbacks if @prepare_each_request
+ run_callbacks(:call) do
+ run_callbacks(:prepare) if @prepare_each_request
@app.call(env)
end
end
View
18 actionpack/lib/action_view/base.rb
@@ -236,15 +236,15 @@ def self.for_controller(controller)
# they are in AC.
if controller.class.respond_to?(:_helper_serial)
klass = @views[controller.class._helper_serial] ||= Class.new(self) do
- name = controller.class.name.gsub(/::/, '__')
-
- Subclasses.class_eval do
- if method(:const_defined?).arity == 1
- remove_const(name) if const_defined?(name) # Ruby 1.8.x
- else
- remove_const(name) if const_defined?(name, false) # Ruby 1.9.x
- end
- const_set(name, self)
+ const_set(:CONTROLLER_CLASS, controller.class)
+
+ # Try to make stack traces clearer
+ def self.name
+ "ActionView for #{CONTROLLER_CLASS}"
+ end
+
+ def inspect
+ "#<#{self.class.name}>"
end
if controller.respond_to?(:_helpers)
View
6 actionpack/lib/action_view/helpers/record_tag_helper.rb
@@ -15,7 +15,7 @@ module RecordTagHelper
def div_for(record, *args, &block)
content_tag_for(:div, record, *args, &block)
end
-
+
# content_tag_for creates an HTML element with id and class parameters
# that relate to the specified Active Record object. For example:
#
@@ -34,7 +34,7 @@ def div_for(record, *args, &block)
# <% content_tag_for(:tr, @person, :foo) do %> ...
#
# produces:
- #
+ #
# <tr id="foo_person_123" class="person">...
#
# content_tag_for also accepts a hash of options, which will be converted to
@@ -50,7 +50,7 @@ def div_for(record, *args, &block)
def content_tag_for(tag_name, record, *args, &block)
prefix = args.first.is_a?(Hash) ? nil : args.shift
options = args.extract_options!
- options.merge!({ :class => "#{dom_class(record)} #{options[:class]}".strip, :id => dom_id(record, prefix) })
+ options.merge!({ :class => "#{dom_class(record, prefix)} #{options[:class]}".strip, :id => dom_id(record, prefix) })
content_tag(tag_name, options, &block)
end
end
View
7 actionpack/lib/action_view/paths.rb
@@ -1,8 +1,11 @@
module ActionView #:nodoc:
class PathSet < Array #:nodoc:
- def self.type_cast(obj)
+ def self.type_cast(obj, cache = nil)
+ # TODO: Clean this up
if obj.is_a?(String)
- cache = !defined?(Rails) || !Rails.respond_to?(:configuration) || Rails.configuration.cache_classes
+ if cache.nil?
+ cache = !defined?(Rails) || Rails.application.config.cache_classes
+ end
FileSystemResolverWithFallback.new(obj, :cache => cache)
else
obj
View
5 actionpack/lib/action_view/render/partials.rb
@@ -296,7 +296,10 @@ def find_template(path = @path)
end
def _find_template(path)
- prefix = @view.controller.controller_path unless path.include?(?/)
+ if controller = @view.controller
+ prefix = controller.controller_path unless path.include?(?/)
+ end
+
@view.find(path, {:formats => @view.formats}, prefix, true)
end
View
22 actionpack/lib/action_view/render/rendering.rb
@@ -14,6 +14,7 @@ def render(options = {}, locals = {}, &block) #:nodoc:
case options
when Hash
layout = options[:layout]
+ options[:locals] ||= {}
if block_given?
return concat(_render_partial(options.merge(:partial => layout), &block))
@@ -25,11 +26,11 @@ def render(options = {}, locals = {}, &block) #:nodoc:
if file = options[:file]
template = find(file, {:formats => formats})
- _render_template(template, layout, :locals => options[:locals] || {})
+ _render_template(template, layout, :locals => options[:locals])
elsif inline = options[:inline]
_render_inline(inline, layout, options)
elsif text = options[:text]
- _render_text(text, layout, options)
+ _render_text(text, layout, options[:locals])
end
when :update
update_page(&block)
@@ -80,16 +81,19 @@ def _layout_for(name = nil)
def _render_inline(inline, layout, options)
handler = Template.handler_class_for_extension(options[:type] || "erb")
- template = Template.new(options[:inline], "inline #{options[:inline].inspect}", handler, {})
- locals = options[:locals] || {}
+ template = Template.new(options[:inline],
+ "inline #{options[:inline].inspect}", handler, {})
+
+ locals = options[:locals]
content = template.render(self, locals)
- content = layout.render(self, locals) {|*name| _layout_for(*name) { content } } if layout
- content
+ _render_text(content, layout, locals)
end
- def _render_text(text, layout, options)
- text = layout.render(self, options[:locals]) { text } if layout
- text
+ def _render_text(content, layout, locals)
+ content = layout.render(self, locals) do |*name|
+ _layout_for(*name) { content }
+ end if layout
+ content
end
# This is the API to render a ViewContext's template from a controller.
View
28 actionpack/test/controller/routing_test.rb
@@ -240,18 +240,6 @@ def test_basic_named_route
x.send(:home_url))
end
- def test_basic_named_route_with_relative_url_root
- rs.draw do |map|
- map.home '', :controller => 'content', :action => 'list'
- end
- x = setup_for_named_route
- ActionController::Base.relative_url_root = "/foo"
- assert_equal("http://test.host/foo/",
- x.send(:home_url))
- assert_equal "/foo/", x.send(:home_path)
- ActionController::Base.relative_url_root = nil
- end
-
def test_named_route_with_option
rs.draw do |map|
map.page 'page/:title', :controller => 'content', :action => 'show_page'
@@ -307,19 +295,6 @@ def test_named_route_with_nested_controller
x.send(:users_url))
end
- def test_optimised_named_route_call_never_uses_url_for
- rs.draw do |map|
- map.users 'admin/user', :controller => '/admin/user', :action => 'index'
- map.user 'admin/user/:id', :controller=>'/admin/user', :action=>'show'
- end
- x = setup_for_named_route
- x.expects(:url_for).never
- x.send(:users_url)
- x.send(:users_path)
- x.send(:user_url, 2, :foo=>"bar")
- x.send(:user_path, 3, :bar=>"foo")
- end
-
def test_optimised_named_route_with_host
rs.draw do |map|
map.pages 'pages', :controller => 'content', :action => 'show_page', :host => 'foo.com'
@@ -984,9 +959,6 @@ def test_draw_default_route
end
assert_equal 1, set.routes.size
- route = set.routes.first
-
- assert route.segments.last.optional?
assert_equal '/users/show/10', set.generate(:controller => 'users', :action => 'show', :id => 10)
assert_equal '/users/index/10', set.generate(:controller => 'users', :id => 10)
View
2 actionpack/test/lib/controller/fake_controllers.rb
@@ -7,6 +7,7 @@ module Admin
class << self; alias_method :const_available?, :const_defined?; end
class UserController < ActionController::Base; end
class NewsFeedController < ActionController::Base; end
+ class StuffController < ActionController::Base; end
end
module Api
@@ -26,6 +27,7 @@ class HiController < ActionController::Base; end
class ImageController < ActionController::Base; end
class PeopleController < ActionController::Base; end
class SessionsController < ActionController::Base; end
+class StuffController < ActionController::Base; end
class SubpathBooksController < ActionController::Base; end
class WeblogController < ActionController::Base; end
View
2 actionpack/test/template/record_tag_helper_test.rb
@@ -27,7 +27,7 @@ def test_content_tag_for
end
def test_content_tag_for_prefix
- expected = %(<ul class="post" id="archived_post_45"></ul>)
+ expected = %(<ul class="archived_post" id="archived_post_45"></ul>)
actual = content_tag_for(:ul, @post, :archived) { }
assert_dom_equal expected, actual
end
View
2 actionpack/test/view/safe_buffer_test.rb → actionpack/test/template/safe_buffer_test.rb
@@ -26,7 +26,7 @@ def setup
end
test "Should not mess with a previously escape test" do
- @buffer << CGI.escapeHTML("<script>")
+ @buffer << ERB::Util.html_escape("<script>")
assert_equal "&lt;script&gt;", @buffer
end
View
10 activemodel/lib/active_model/validations.rb
@@ -1,12 +1,10 @@
require 'active_support/core_ext/array/extract_options'
require 'active_support/core_ext/hash/keys'
-require 'active_support/concern'
-require 'active_support/callbacks'
module ActiveModel
module Validations
extend ActiveSupport::Concern
- include ActiveSupport::NewCallbacks
+ include ActiveSupport::Callbacks
included do
define_callbacks :validate, :scope => :name
@@ -99,7 +97,7 @@ def valid?
def invalid?
!valid?
end
-
+
protected
# Hook method defining how an attribute value should be retieved. By default this is assumed
# to be an instance named after the attribute. Override this method in subclasses should you
@@ -110,9 +108,9 @@ def invalid?
# def initialize(data = {})
# @data = data
# end
- #
+ #
# private
- #
+ #
# def read_attribute_for_validation(key)
# @data[key]
# end
View
2 activerecord/lib/active_record/associations/association_collection.rb
@@ -476,7 +476,7 @@ def remove_records(*records)
def callback(method, record)
callbacks_for(method).each do |callback|
- ActiveSupport::Callbacks::Callback.new(method, callback, record).call(@owner, record)
+ ActiveSupport::DeprecatedCallbacks::Callback.new(method, callback, record).call(@owner, record)
end
end
View
4 activerecord/lib/active_record/callbacks.rb
@@ -20,7 +20,7 @@ module ActiveRecord
# * (6) <tt>after_save</tt>
#
# That's a total of eight callbacks, which gives you immense power to react and prepare for each state in the
- # Active Record lifecycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar, except that each
+ # Active Record lifecycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar, except that each
# <tt>_on_create</tt> callback is replaced by the corresponding <tt>_on_update</tt> callback.
#
# Examples:
@@ -210,7 +210,7 @@ module ActiveRecord
# instead of quietly returning +false+.
module Callbacks
extend ActiveSupport::Concern
- include ActiveSupport::NewCallbacks
+ include ActiveSupport::Callbacks
CALLBACKS = [
:after_initialize, :after_find, :before_validation, :after_validation,
View
4 activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -32,7 +32,7 @@ module ConnectionAdapters # :nodoc:
class AbstractAdapter
include Quoting, DatabaseStatements, SchemaStatements
include QueryCache
- include ActiveSupport::Callbacks
+ include ActiveSupport::DeprecatedCallbacks
define_callbacks :checkout, :checkin
@@row_even = true
@@ -75,7 +75,7 @@ def supports_count_distinct?
def supports_ddl_transactions?
false
end
-
+
# Does this adapter support savepoints? PostgreSQL and MySQL do, SQLite
# does not.
def supports_savepoints?
View
42 activerecord/lib/active_record/nested_attributes.rb
@@ -3,11 +3,14 @@
module ActiveRecord
module NestedAttributes #:nodoc:
+ class TooManyRecords < ActiveRecordError
+ end
+
extend ActiveSupport::Concern
included do
- class_inheritable_accessor :reject_new_nested_attributes_procs, :instance_writer => false
- self.reject_new_nested_attributes_procs = {}
+ class_inheritable_accessor :nested_attributes_options, :instance_writer => false
+ self.nested_attributes_options = {}
end
# == Nested Attributes
@@ -203,6 +206,12 @@ module ClassMethods
# do not have a <tt>_destroy</tt> value that evaluates to true.
# Passing <tt>:all_blank</tt> instead of a Proc will create a proc
# that will reject a record where all the attributes are blank.
+ # [:limit]
+ # Allows you to specify the maximum number of the associated records that
+ # can be processes with the nested attributes. If the size of the
+ # nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecords
+ # exception is raised. If omitted, any number associations can be processed.
+ # Note that the :limit option is only applicable to one-to-many associations.
#
# Examples:
# # creates avatar_attributes=
@@ -214,7 +223,7 @@ module ClassMethods
def accepts_nested_attributes_for(*attr_names)
options = { :allow_destroy => false }
options.update(attr_names.extract_options!)
- options.assert_valid_keys(:allow_destroy, :reject_if)
+ options.assert_valid_keys(:allow_destroy, :reject_if, :limit)
attr_names.each do |association_name|
if reflection = reflect_on_association(association_name)
@@ -227,18 +236,18 @@ def accepts_nested_attributes_for(*attr_names)
reflection.options[:autosave] = true
- self.reject_new_nested_attributes_procs[association_name.to_sym] = if options[:reject_if] == :all_blank
- proc { |attributes| attributes.all? {|k,v| v.blank?} }
- else
- options[:reject_if]
+ self.nested_attributes_options[association_name.to_sym] = options
+
+ if options[:reject_if] == :all_blank
+ self.nested_attributes_options[association_name.to_sym][:reject_if] = proc { |attributes| attributes.all? {|k,v| v.blank?} }
end
# def pirate_attributes=(attributes)
# assign_nested_attributes_for_one_to_one_association(:pirate, attributes, false)
# end
class_eval %{
def #{association_name}_attributes=(attributes)
- assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes, #{options[:allow_destroy]})
+ assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes)
end
}, __FILE__, __LINE__
else
@@ -282,7 +291,8 @@ def _delete #:nodoc:
# If the given attributes include a matching <tt>:id</tt> attribute _and_ a
# <tt>:_destroy</tt> key set to a truthy value, then the existing record
# will be marked for destruction.
- def assign_nested_attributes_for_one_to_one_association(association_name, attributes, allow_destroy)
+ def assign_nested_attributes_for_one_to_one_association(association_name, attributes)
+ options = self.nested_attributes_options[association_name]
attributes = attributes.with_indifferent_access
if attributes['id'].blank?
@@ -295,7 +305,7 @@ def assign_nested_attributes_for_one_to_one_association(association_name, attrib
end
end
elsif (existing_record = send(association_name)) && existing_record.id.to_s == attributes['id'].to_s
- assign_to_or_mark_for_destruction(existing_record, attributes, allow_destroy)
+ assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
end
end
@@ -326,11 +336,17 @@ def assign_nested_attributes_for_one_to_one_association(association_name, attrib
# { :name => 'John' },
# { :id => '2', :_destroy => true }
# ])
- def assign_nested_attributes_for_collection_association(association_name, attributes_collection, allow_destroy)
+ def assign_nested_attributes_for_collection_association(association_name, attributes_collection)
+ options = self.nested_attributes_options[association_name]
+
unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
end
+ if options[:limit] && attributes_collection.size > options[:limit]
+ raise TooManyRecords, "Maximum #{options[:limit]} records are allowed. Got #{attributes_collection.size} records instead."
+ end
+
if attributes_collection.is_a? Hash
attributes_collection = attributes_collection.sort_by { |index, _| index.to_i }.map { |_, attributes| attributes }
end
@@ -343,7 +359,7 @@ def assign_nested_attributes_for_collection_association(association_name, attrib
send(association_name).build(attributes.except(*UNASSIGNABLE_KEYS))
end
elsif existing_record = send(association_name).detect { |record| record.id.to_s == attributes['id'].to_s }
- assign_to_or_mark_for_destruction(existing_record, attributes, allow_destroy)
+ assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
end
end
end
@@ -372,7 +388,7 @@ def reject_new_record?(association_name, attributes)
end
def call_reject_if(association_name, attributes)
- callback = self.class.reject_new_nested_attributes_procs[association_name]
+ callback = self.nested_attributes_options[association_name][:reject_if]
case callback
when Symbol
View
14 activerecord/lib/active_record/validations.rb
@@ -59,15 +59,15 @@ def full_messages(options = {})
end
# Translates an error message in it's default scope (<tt>activerecord.errrors.messages</tt>).
- # Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>, if it's not there,
- # it's looked up in <tt>models.MODEL.MESSAGE</tt> and if that is not there it returns the translation of the
- # default message (e.g. <tt>activerecord.errors.messages.MESSAGE</tt>). The translated model name,
+ # Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>, if it's not there,
+ # it's looked up in <tt>models.MODEL.MESSAGE</tt> and if that is not there it returns the translation of the
+ # default message (e.g. <tt>activerecord.errors.messages.MESSAGE</tt>). The translated model name,
# translated attribute name and the value are available for interpolation.
#
# When using inheritance in your models, it will check all the inherited models too, but only if the model itself
# hasn't been found. Say you have <tt>class Admin < User; end</tt> and you wanted the translation for the <tt>:blank</tt>
# error +message+ for the <tt>title</tt> +attribute+, it looks for these translations:
- #
+ #
# <ol>
# <li><tt>activerecord.errors.models.admin.attributes.title.blank</tt></li>
# <li><tt>activerecord.errors.models.admin.blank</tt></li>
@@ -80,10 +80,10 @@ def generate_message(attribute, message = :invalid, options = {})
message, options[:default] = options[:default], message if options[:default].is_a?(Symbol)
defaults = @base.class.self_and_descendants_from_active_record.map do |klass|
- [ :"models.#{klass.name.underscore}.attributes.#{attribute}.#{message}",
+ [ :"models.#{klass.name.underscore}.attributes.#{attribute}.#{message}",
:"models.#{klass.name.underscore}.#{message}" ]
end
-
+
defaults << options.delete(:default)
defaults = defaults.compact.flatten << :"messages.#{message}"
@@ -104,7 +104,7 @@ def generate_message(attribute, message = :invalid, options = {})
module Validations
extend ActiveSupport::Concern
- include ActiveSupport::Callbacks
+ include ActiveSupport::DeprecatedCallbacks
include ActiveModel::Validations
included do
View
38 activerecord/test/cases/nested_attributes_test.rb
@@ -29,13 +29,13 @@ def teardown
Pirate.accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
end
- def test_base_should_have_an_empty_reject_new_nested_attributes_procs
- assert_equal Hash.new, ActiveRecord::Base.reject_new_nested_attributes_procs
+ def test_base_should_have_an_empty_nested_attributes_options
+ assert_equal Hash.new, ActiveRecord::Base.nested_attributes_options
end
- def test_should_add_a_proc_to_reject_new_nested_attributes_procs
+ def test_should_add_a_proc_to_nested_attributes_options
[:parrots, :birds, :birds_with_reject_all_blank].each do |name|
- assert_instance_of Proc, Pirate.reject_new_nested_attributes_procs[name]
+ assert_instance_of Proc, Pirate.nested_attributes_options[name][:reject_if]
end
end
@@ -603,3 +603,33 @@ def setup
include NestedAttributesOnACollectionAssociationTests
end
+
+class TestNestedAttributesLimit < ActiveRecord::TestCase
+ def setup
+ Pirate.accepts_nested_attributes_for :parrots, :limit => 2
+
+ @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ end
+
+ def teardown
+ Pirate.accepts_nested_attributes_for :parrots, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ end
+
+ def test_limit_with_less_records
+ @pirate.attributes = { :parrots_attributes => { 'foo' => { :name => 'Big Big Love' } } }
+ assert_difference('Parrot.count') { @pirate.save! }
+ end
+
+ def test_limit_with_number_exact_records
+ @pirate.attributes = { :parrots_attributes => { 'foo' => { :name => 'Lovely Day' }, 'bar' => { :name => 'Blown Away' } } }
+ assert_difference('Parrot.count', 2) { @pirate.save! }
+ end
+
+ def test_limit_with_exceeding_records
+ assert_raises(ActiveRecord::NestedAttributes::TooManyRecords) do
+ @pirate.attributes = { :parrots_attributes => { 'foo' => { :name => 'Lovely Day' },
+ 'bar' => { :name => 'Blown Away' },
+ 'car' => { :name => 'The Happening' }} }
+ end
+ end
+end
View
2 activesupport/lib/active_support/autoload.rb
@@ -8,14 +8,14 @@ module ActiveSupport
autoload :Concern, 'active_support/concern'
autoload :ConcurrentHash, 'active_support/concurrent_hash'
autoload :DependencyModule, 'active_support/dependency_module'
+ autoload :DeprecatedCallbacks, 'active_support/deprecated_callbacks'
autoload :Deprecation, 'active_support/deprecation'
autoload :Gzip, 'active_support/gzip'
autoload :Inflector, 'active_support/inflector'
autoload :Memoizable, 'active_support/memoizable'
autoload :MessageEncryptor, 'active_support/message_encryptor'
autoload :MessageVerifier, 'active_support/message_verifier'
autoload :Multibyte, 'active_support/multibyte'
- autoload :NewCallbacks, 'active_support/new_callbacks'
autoload :OptionMerger, 'active_support/option_merger'
autoload :Orchestra, 'active_support/orchestra'
autoload :OrderedHash, 'active_support/ordered_hash'
View
7 activesupport/lib/active_support/cache.rb
@@ -115,6 +115,13 @@ def silence!
self
end
+ def mute
+ previous_silence, @silence = defined?(@silence) && @silence, true
+ yield
+ ensure
+ @silence = previous_silence
+ end
+
# Fetches data from the cache, using the given key. If there is data in
# the cache with the given key, then that data is returned.
#
View
2 activesupport/lib/active_support/cache/memory_store.rb
@@ -1,3 +1,5 @@
+require 'active_support/core_ext/object/duplicable'
+
module ActiveSupport
module Cache
# A cache store implementation which stores everything into memory in the
View
10 activesupport/lib/active_support/cache/strategy/local_cache.rb
@@ -44,7 +44,7 @@ def read(key, options = nil)
nil
elsif value.nil?
value = super
- local_cache.write(key, value || NULL) if local_cache
+ local_cache.mute { local_cache.write(key, value || NULL) } if local_cache
value.duplicable? ? value.dup : value
else
# forcing the value to be immutable
@@ -54,12 +54,12 @@ def read(key, options = nil)
def write(key, value, options = nil)
value = value.to_s if respond_to?(:raw?) && raw?(options)
- local_cache.write(key, value || NULL) if local_cache
+ local_cache.mute { local_cache.write(key, value || NULL) } if local_cache
super
end
def delete(key, options = nil)
- local_cache.write(key, NULL) if local_cache
+ local_cache.mute { local_cache.write(key, NULL) } if local_cache
super
end
@@ -76,7 +76,7 @@ def exist(key, options = nil)
def increment(key, amount = 1)
if value = super
- local_cache.write(key, value.to_s) if local_cache
+ local_cache.mute { local_cache.write(key, value.to_s) } if local_cache
value
else
nil
@@ -85,7 +85,7 @@ def increment(key, amount = 1)
def decrement(key, amount = 1)
if value = super
- local_cache.write(key, value.to_s) if local_cache
+ local_cache.mute { local_cache.write(key, value.to_s) } if local_cache
value
else
nil
View
622 activesupport/lib/active_support/callbacks.rb
@@ -1,4 +1,6 @@
-require 'active_support/core_ext/array/extract_options'
+require 'active_support/core_ext/array/wrap'
+require 'active_support/core_ext/class/inheritable_attributes'
+require 'active_support/core_ext/kernel/reporting'
module ActiveSupport
# Callbacks are hooks into the lifecycle of an object that allow you to trigger logic
@@ -10,23 +12,23 @@ module ActiveSupport
# class Storage
# include ActiveSupport::Callbacks
#
- # define_callbacks :before_save, :after_save
+ # define_callbacks :save
# end
#
# class ConfigStorage < Storage
- # before_save :saving_message
+ # set_callback :save, :before, :saving_message
# def saving_message
# puts "saving..."
# end
#
- # after_save do |object|
+ # set_callback :save, :after do |object|
# puts "saved"
# end
#
# def save
- # run_callbacks(:before_save)
- # puts "- save"
- # run_callbacks(:after_save)
+ # run_callbacks :save do
+ # puts "- save"
+ # end
# end
# end
#
@@ -44,28 +46,28 @@ module ActiveSupport
# class Storage
# include ActiveSupport::Callbacks
#
- # define_callbacks :before_save, :after_save
+ # define_callbacks :save
#
- # before_save :prepare
+ # set_callback :save, :before, :prepare
# def prepare
# puts "preparing save"
# end
# end
#
# class ConfigStorage < Storage
- # before_save :saving_message
+ # set_callback :save, :before, :saving_message
# def saving_message
# puts "saving..."
# end
#
- # after_save do |object|
+ # set_callback :save, :after do |object|
# puts "saved"
# end
#
# def save
- # run_callbacks(:before_save)
- # puts "- save"
- # run_callbacks(:after_save)
+ # run_callbacks :save do
+ # puts "- save"
+ # end
# end
# end
#
@@ -77,205 +79,485 @@ module ActiveSupport
# saving...
# - save
# saved
+ #
module Callbacks
- class CallbackChain < Array
- def self.build(kind, *methods, &block)
- methods, options = extract_options(*methods, &block)
- methods.map! { |method| Callback.new(kind, method, options) }
- new(methods)
+ def self.included(klass)
+ klass.extend ClassMethods
+ end
+
+ def run_callbacks(kind, *args, &block)
+ send("_run_#{kind}_callbacks", *args, &block)
+ end
+
+ class Callback
+ @@_callback_sequence = 0
+
+ attr_accessor :chain, :filter, :kind, :options, :per_key, :klass
+
+ def initialize(chain, filter, kind, options, klass)
+ @chain, @kind, @klass = chain, kind, klass
+ normalize_options!(options)
+
+ @per_key = options.delete(:per_key)
+ @raw_filter, @options = filter, options
+ @filter = _compile_filter(filter)
+ @compiled_options = _compile_options(options)
+ @callback_id = next_id
+
+ _compile_per_key_options
+ end
+
+ def clone(chain, klass)
+ obj = super()
+ obj.chain = chain
+ obj.klass = klass
+ obj.per_key = @per_key.dup
+ obj.options = @options.dup
+ obj.per_key[:if] = @per_key[:if].dup
+ obj.per_key[:unless] = @per_key[:unless].dup
+ obj.options[:if] = @options[:if].dup
+ obj.options[:unless] = @options[:unless].dup
+ obj
end
- def run(object, options = {}, &terminator)
- enumerator = options[:enumerator] || :each
+ def normalize_options!(options)
+ options[:if] = Array.wrap(options[:if])
+ options[:unless] = Array.wrap(options[:unless])
- unless block_given?
- send(enumerator) { |callback| callback.call(object) }
- else
- send(enumerator) do |callback|
- result = callback.call(object)
- break result if terminator.call(result, object)
+ options[:per_key] ||= {}
+ options[:per_key][:if] = Array.wrap(options[:per_key][:if])
+ options[:per_key][:unless] = Array.wrap(options[:per_key][:unless])
+ end
+
+ def name
+ chain.name
+ end
+
+ def next_id
+ @@_callback_sequence += 1
+ end
+
+ def matches?(_kind, _filter)
+ @kind == _kind && @filter == _filter
+ end
+
+ def _update_filter(filter_options, new_options)
+ filter_options[:if].push(new_options[:unless]) if new_options.key?(:unless)
+ filter_options[:unless].push(new_options[:if]) if new_options.key?(:if)
+ end
+
+ def recompile!(_options, _per_key)
+ _update_filter(self.options, _options)
+ _update_filter(self.per_key, _per_key)
+
+ @callback_id = next_id
+ @filter = _compile_filter(@raw_filter)
+ @compiled_options = _compile_options(@options)
+ _compile_per_key_options
+ end
+
+ def _compile_per_key_options
+ key_options = _compile_options(@per_key)
+
+ @klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
+ def _one_time_conditions_valid_#{@callback_id}?
+ true #{key_options[0]}
end
- end
+ RUBY_EVAL
end
- # TODO: Decompose into more Array like behavior
- def replace_or_append!(chain)
- if index = index(chain)
- self[index] = chain
- else
- self << chain
+ # This will supply contents for before and around filters, and no
+ # contents for after filters (for the forward pass).
+ def start(key=nil, object=nil)
+ return if key && !object.send("_one_time_conditions_valid_#{@callback_id}?")
+
+ # options[0] is the compiled form of supplied conditions
+ # options[1] is the "end" for the conditional
+ #
+ if @kind == :before || @kind == :around
+ if @kind == :before
+ # if condition # before_save :filter_name, :if => :condition
+ # filter_name
+ # end
+ filter = <<-RUBY_EVAL
+ unless halted
+ result = #{@filter}
+ halted = (#{chain.config[:terminator]})
+ end
+ RUBY_EVAL
+
+ [@compiled_options[0], filter, @compiled_options[1]].compact.join("\n")
+ else
+ # Compile around filters with conditions into proxy methods
+ # that contain the conditions.
+ #
+ # For `around_save :filter_name, :if => :condition':
+ #
+ # def _conditional_callback_save_17
+ # if condition
+ # filter_name do
+ # yield self
+ # end
+ # else
+ # yield self
+ # end
+ # end
+ #
+ name = "_conditional_callback_#{@kind}_#{next_id}"
+ txt, line = <<-RUBY_EVAL, __LINE__ + 1
+ def #{name}(halted)
+ #{@compiled_options[0] || "if true"} && !halted
+ #{@filter} do
+ yield self
+ end
+ else
+ yield self
+ end
+ end
+ RUBY_EVAL
+ @klass.class_eval(txt, __FILE__, line)
+ "#{name}(halted) do"
+ end
end
- self
end
- def find(callback, &block)
- select { |c| c == callback && (!block_given? || yield(c)) }.first
- end
+ # This will supply contents for around and after filters, but not
+ # before filters (for the backward pass).
+ def end(key=nil, object=nil)
+ return if key && !object.send("_one_time_conditions_valid_#{@callback_id}?")
- def delete(callback)
- super(callback.is_a?(Callback) ? callback : find(callback))
+ if @kind == :around || @kind == :after
+ # if condition # after_save :filter_name, :if => :condition
+ # filter_name
+ # end
+ if @kind == :after
+ [@compiled_options[0], @filter, @compiled_options[1]].compact.join("\n")
+ else
+ "end"
+ end
+ end
end
private
- def self.extract_options(*methods, &block)
- methods.flatten!
- options = methods.extract_options!
- methods << block if block_given?
- return methods, options
- end
- def extract_options(*methods, &block)
- self.class.extract_options(*methods, &block)
+ # Options support the same options as filters themselves (and support
+ # symbols, string, procs, and objects), so compile a conditional
+ # expression based on the options
+ def _compile_options(options)
+ return [] if options[:if].empty? && options[:unless].empty?
+
+ conditions = []
+
+ unless options[:if].empty?
+ conditions << Array.wrap(_compile_filter(options[:if]))
end
- end
- class Callback
- attr_reader :kind, :method, :identifier, :options
+ unless options[:unless].empty?
+ conditions << Array.wrap(_compile_filter(options[:unless])).map {|f| "!#{f}"}
+ end
- def initialize(kind, method, options = {})
- @kind = kind
- @method = method
- @identifier = options[:identifier]
- @options = options
+ ["if #{conditions.flatten.join(" && ")}", "end"]
end
- def ==(other)
- case other
- when Callback
- (self.identifier && self.identifier == other.identifier) || self.method == other.method
+ # Filters support:
+ #
+ # Arrays:: Used in conditions. This is used to specify
+ # multiple conditions. Used internally to
+ # merge conditions from skip_* filters
+ # Symbols:: A method to call
+ # Strings:: Some content to evaluate
+ # Procs:: A proc to call with the object
+ # Objects:: An object with a before_foo method on it to call
+ #
+ # All of these objects are compiled into methods and handled
+ # the same after this point:
+ #
+ # Arrays:: Merged together into a single filter
+ # Symbols:: Already methods
+ # Strings:: class_eval'ed into methods
+ # Procs:: define_method'ed into methods
+ # Objects::
+ # a method is created that calls the before_foo method
+ # on the object.
+ #
+ def _compile_filter(filter)
+ method_name = "_callback_#{@kind}_#{next_id}"
+ case filter
+ when Array
+ filter.map {|f| _compile_filter(f)}
+ when Symbol
+ filter
+ when String
+ "(#{filter})"
+ when Proc
+ @klass.send(:define_method, method_name, &filter)
+ return method_name if filter.arity <= 0
+
+ method_name << (filter.arity == 1 ? "(self)" : " self, Proc.new ")
else
- (self.identifier && self.identifier == other) || self.method == other
+ @klass.send(:define_method, "#{method_name}_object") { filter }
+
+ _normalize_legacy_filter(kind, filter)
+ scopes = Array.wrap(chain.config[:scope])
+ method_to_call = scopes.map{ |s| s.is_a?(Symbol) ? send(s) : s }.join("_")
+
+ @klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
+ def #{method_name}(&blk)
+ #{method_name}_object.send(:#{method_to_call}, self, &blk)
+ end
+ RUBY_EVAL
+
+ method_name
end
end
- def eql?(other)
- self == other
+ def _normalize_legacy_filter(kind, filter)
+ if !filter.respond_to?(kind) && filter.respond_to?(:filter)
+ filter.metaclass.class_eval(
+ "def #{kind}(context, &block) filter(context, &block) end",
+ __FILE__, __LINE__ - 1)
+ elsif filter.respond_to?(:before) && filter.respond_to?(:after) && kind == :around
+ def filter.around(context)
+ should_continue = before(context)
+ yield if should_continue
+ after(context)
+ end
+ end
end
+ end
- def dup
- self.class.new(@kind, @method, @options.dup)
+ # An Array with a compile method
+ class CallbackChain < Array
+ attr_reader :name, :config
+
+ def initialize(name, config)
+ @name = name
+ @config = {
+ :terminator => "false",
+ :rescuable => false,
+ :scope => [ :kind ]
+ }.merge(config)
end
- def hash
- if @identifier
- @identifier.hash
- else
- @method.hash
+ def compile(key=nil, object=nil)
+ method = []
+ method << "value = nil"
+ method << "halted = false"
+
+ each do |callback|
+ method << callback.start(key, object)
+ end
+
+ if config[:rescuable]
+ method << "rescued_error = nil"
+ method << "begin"
+ end
+
+ method << "value = yield if block_given? && !halted"
+
+ if config[:rescuable]
+ method << "rescue Exception => e"
+ method << "rescued_error = e"
+ method << "end"
end
+
+ reverse_each do |callback|
+ method << callback.end(key, object)
+ end
+
+ method << "raise rescued_error if rescued_error" if config[:rescuable]
+ method << "halted ? false : (block_given? ? value : true)"
+ method.compact.join("\n")
end
- def call(*args, &block)
- evaluate_method(method, *args, &block) if should_run_callback?(*args)
- rescue LocalJumpError
- raise ArgumentError,
- "Cannot yield from a Proc type filter. The Proc must take two " +
- "arguments and execute #call on the second argument."
+ def clone(klass)
+ chain = CallbackChain.new(@name, @config.dup)
+ callbacks = map { |c| c.clone(chain, klass) }
+ chain.push(*callbacks)
end
+ end
- private
- def evaluate_method(method, *args, &block)
- case method
- when Symbol
- object = args.shift
- object.send(method, *args, &block)
- when String
- eval(method, args.first.instance_eval { binding })
- when Proc, Method
- method.call(*args, &block)
- else
- if method.respond_to?(kind)
- method.send(kind, *args, &block)
- else
- raise ArgumentError,
- "Callbacks must be a symbol denoting the method to call, a string to be evaluated, " +
- "a block to be invoked, or an object responding to the callback method."
+ module ClassMethods
+ # Make the run_callbacks :save method. The generated method takes
+ # a block that it'll yield to. It'll call the before and around filters
+ # in order, yield the block, and then run the after filters.
+ #
+ # run_callbacks :save do
+ # save
+ # end
+ #
+ # The run_callbacks :save method can optionally take a key, which
+ # will be used to compile an optimized callback method for each
+ # key. See #define_callbacks for more information.
+ #
+ def __define_runner(symbol) #:nodoc:
+ body = send("_#{symbol}_callbacks").compile(nil)
+
+ body, line = <<-RUBY_EVAL, __LINE__
+ def _run_#{symbol}_callbacks(key = nil, &blk)
+ if key
+ name = "_run__\#{self.class.name.hash.abs}__#{symbol}__\#{key.hash.abs}__callbacks"
+
+ unless respond_to?(name)
+ self.class.__create_keyed_callback(name, :#{symbol}, self, &blk)
end
+
+ send(name, &blk)
+ else
+ #{body}
+ end
end
+ private :_run_#{symbol}_callbacks
+ RUBY_EVAL
+
+ silence_warnings do
+ undef_method "_run_#{symbol}_callbacks" if method_defined?("_run_#{symbol}_callbacks")
+ class_eval body, __FILE__, line
end
+ end
- def should_run_callback?(*args)
- [options[:if]].flatten.compact.all? { |a| evaluate_method(a, *args) } &&
- ![options[:unless]].flatten.compact.any? { |a| evaluate_method(a, *args) }
+ # This is called the first time a callback is called with a particular
+ # key. It creates a new callback method for the key, calculating
+ # which callbacks can be omitted because of per_key conditions.
+ #
+ def __create_keyed_callback(name, kind, object, &blk) #:nodoc:
+ @_keyed_callbacks ||= {}
+ @_keyed_callbacks[name] ||= begin
+ str = send("_#{kind}_callbacks").compile(name, object)
+ class_eval "def #{name}() #{str} end", __FILE__, __LINE__
+ true
end
- end
+ end
- def self.included(base)
- base.extend ClassMethods
- end
+ # This is used internally to append, prepend and skip callbacks to the
+ # CallbackChain.
+ #
+ def __update_callbacks(name, filters = [], block = nil) #:nodoc:
+ type = [:before, :after, :around].include?(filters.first) ? filters.shift : :before
+ options = filters.last.is_a?(Hash) ? filters.pop : {}
+ filters.unshift(block) if block
- module ClassMethods
- def define_callbacks(*callbacks)
- callbacks.each do |callback|
- class_eval <<-"end_eval", __FILE__, __LINE__ + 1
- def self.#{callback}(*methods, &block) # def self.before_save(*methods, &block)
- callbacks = CallbackChain.build(:#{callback}, *methods, &block) # callbacks = CallbackChain.build(:before_save, *methods, &block)
- @#{callback}_callbacks ||= CallbackChain.new # @before_save_callbacks ||= CallbackChain.new
- @#{callback}_callbacks.concat callbacks # @before_save_callbacks.concat callbacks
- end # end
- #
- def self.#{callback}_callback_chain # def self.before_save_callback_chain
- @#{callback}_callbacks ||= CallbackChain.new # @before_save_callbacks ||= CallbackChain.new
- #
- if superclass.respond_to?(:#{callback}_callback_chain) # if superclass.respond_to?(:before_save_callback_chain)
- CallbackChain.new( # CallbackChain.new(
- superclass.#{callback}_callback_chain + # superclass.before_save_callback_chain +
- @#{callback}_callbacks # @before_save_callbacks
- ) # )
- else # else
- @#{callback}_callbacks # @before_save_callbacks
- end # end
- end # end
- end_eval
+ chain = send("_#{name}_callbacks")
+ yield chain, type, filters, options if block_given?
+
+ __define_runner(name)
+ end
+
+ # Set callbacks for a previously defined callback.
+ #
+ # Syntax:
+ # set_callback :save, :before, :before_meth
+ # set_callback :save, :after, :after_meth, :if => :condition
+ # set_callback :save, :around, lambda { |r| stuff; yield; stuff }
+ #
+ # Use skip_callback to skip any defined one.
+ #
+ # When creating or skipping callbacks, you can specify conditions that
+ # are always the same for a given key. For instance, in ActionPack,
+ # we convert :only and :except conditions into per-key conditions.
+ #
+ # before_filter :authenticate, :except => "index"
+ # becomes
+ # dispatch_callback :before, :authenticate, :per_key => {:unless => proc {|c| c.action_name == "index"}}
+ #
+ # Per-Key conditions are evaluated only once per use of a given key.
+ # In the case of the above example, you would do:
+ #
+ # run_callbacks(:dispatch, action_name) { ... dispatch stuff ... }
+ #
+ # In that case, each action_name would get its own compiled callback
+ # method that took into consideration the per_key conditions. This
+ # is a speed improvement for ActionPack.
+ #
+ def set_callback(name, *filters, &block)
+ __update_callbacks(name, filters, block) do |chain, type, filters, options|
+ filters.map! do |filter|
+ chain.delete_if {|c| c.matches?(type, filter) }
+ Callback.new(chain, filter, type, options.dup, self)
+ end
+
+ options[:prepend] ? chain.unshift(*filters) : chain.push(*filters)
end
end
- end
- # Runs all the callbacks defined for the given options.
- #
- # If a block is given it will be called after each callback receiving as arguments:
- #
- # * the result from the callback
- # * the object which has the callback
- #
- # If the result from the block evaluates to +true+, the callback chain is stopped.
- #
- # Example:
- # class Storage
- # include ActiveSupport::Callbacks
- #
- # define_callbacks :before_save, :after_save
- # end
- #
- # class ConfigStorage < Storage
- # before_save :pass
- # before_save :pass
- # before_save :stop
- # before_save :pass
- #
- # def pass
- # puts "pass"
- # end
- #
- # def stop
- # puts "stop"
- # return false
- # end
- #
- # def save
- # result = run_callbacks(:before_save) { |result, object| result == false }
- # puts "- save" if result
- # end
- # end
- #
- # config = ConfigStorage.new
- # config.save
- #
- # Output:
- # pass
- # pass
- # stop
- def run_callbacks(kind, options = {}, &block)
- self.class.send("#{kind}_callback_chain").run(self, options, &block)
+ # Skip a previously defined callback for a given type.
+ #
+ def skip_callback(name, *filters, &block)
+ __update_callbacks(name, filters, block) do |chain, type, filters, options|
+ chain = send("_#{name}_callbacks=", chain.clone(self))
+
+ filters.each do |filter|
+ filter = chain.find {|c| c.matches?(type, filter) }
+
+ if filter && options.any?
+ filter.recompile!(options, options[:per_key] || {})
+ else
+ chain.delete(filter)
+ end
+ end
+ end
+ end
+
+ # Reset callbacks for a given type.
+ #
+ def reset_callbacks(symbol)
+ send("_#{symbol}_callbacks").clear
+ __define_runner(symbol)
+ end
+
+ # Define callbacks types.
+ #
+ # ==== Example
+ #
+ # define_callbacks :validate
+ #
+ # ==== Options
+ #
+ # * <tt>:terminator</tt> - Indicates when a before filter is considered
+ # to be halted.
+ #
+ # define_callbacks :validate, :terminator => "result == false"
+ #
+ # In the example above, if any before validate callbacks returns false,
+ # other callbacks are not executed. Defaults to "false".
+ #
+ # * <tt>:rescuable</tt> - By default, after filters are not executed if
+ # the given block or an before_filter raises an error. Supply :rescuable => true
+ # to change this behavior.
+ #
+ # * <tt>:scope</tt> - Show which methods should be executed when a class
+ # is giben as callback:
+ #
+ # define_callbacks :filters, :scope => [ :kind ]
+ #
+ # When a class is given:
+ #
+ # before_filter MyFilter
+ #
+ # It will call the type of the filter in the given class, which in this
+ # case, is "before".
+ #
+ # If, for instance, you supply the given scope:
+ #
+ # define_callbacks :validate, :scope => [ :kind, :name ]
+ #
+ # It will call "#{kind}_#{name}" in the given class. So "before_validate"
+ # will be called in the class below:
+ #
+ # before_validate MyValidation
+ #
+ # Defaults to :kind.
+ #
+ def define_callbacks(*symbols)
+ config = symbols.last.is_a?(Hash) ? symbols.pop : {}
+ symbols.each do |symbol|
+ extlib_inheritable_accessor("_#{symbol}_callbacks") do
+ CallbackChain.new(symbol, config)
+ end
+
+ __define_runner(symbol)
+ end
+ end
end
end
end
View
283 activesupport/lib/active_support/deprecated_callbacks.rb
@@ -0,0 +1,283 @@
+require 'active_support/core_ext/array/extract_options'
+
+module ActiveSupport
+ # Callbacks are hooks into the lifecycle of an object that allow you to trigger logic
+ # before or after an alteration of the object state.
+ #
+ # Mixing in this module allows you to define callbacks in your class.
+ #
+ # Example:
+ # class Storage
+ # include ActiveSupport::DeprecatedCallbacks
+ #
+ # define_callbacks :before_save, :after_save
+ # end
+ #
+ # class ConfigStorage < Storage
+ # before_save :saving_message
+ # def saving_message
+ # puts "saving..."
+ # end
+ #
+ # after_save do |object|
+ # puts "saved"
+ # end
+ #
+ # def save
+ # run_callbacks(:before_save)
+ # puts "- save"
+ # run_callbacks(:after_save)
+ # end
+ # end
+ #
+ # config = ConfigStorage.new
+ # config.save
+ #
+ # Output:
+ # saving...
+ # - save
+ # saved
+ #
+ # Callbacks from parent classes are inherited.
+ #
+ # Example:
+ # class Storage
+ # include ActiveSupport::DeprecatedCallbacks
+ #
+ # define_callbacks :before_save, :after_save
+ #
+ # before_save :prepare
+ # def prepare
+ # puts "preparing save"
+ # end
+ # end
+ #
+ # class ConfigStorage < Storage
+ # before_save :saving_message
+ # def saving_message
+ # puts "saving..."
+ # end
+ #
+ # after_save do |object|
+ # puts "saved"
+ # end
+ #
+ # def save
+ # run_callbacks(:before_save)
+ # puts "- save"
+ # run_callbacks(:after_save)
+ # end
+ # end
+ #
+ # config = ConfigStorage.new
+ # config.save
+ #
+ # Output:
+ # preparing save
+ # saving...
+ # - save
+ # saved
+ module DeprecatedCallbacks
+ class CallbackChain < Array
+ def self.build(kind, *methods, &block)
+ methods, options = extract_options(*methods, &block)
+ methods.map! { |method| Callback.new(kind, method, options) }
+ new(methods)
+ end
+
+ def run(object, options = {}, &terminator)
+ enumerator = options[:enumerator] || :each
+
+ unless block_given?
+ send(enumerator) { |callback| callback.call(object) }
+ else
+ send(enumerator) do |callback|
+ result = callback.call(object)
+ break result if terminator.call(result, object)
+ end
+ end
+ end
+
+ # TODO: Decompose into more Array like behavior
+ def replace_or_append!(chain)
+ if index = index(chain)
+ self[index] = chain
+ else
+ self << chain
+ end
+ self
+ end
+
+ def find(callback, &block)
+ select { |c| c == callback && (!block_given? || yield(c)) }.first
+ end
+
+ def delete(callback)
+ super(callback.is_a?(Callback) ? callback : find(callback))
+ end
+
+ private
+ def self.extract_options(*methods, &block)
+ methods.flatten!
+ options = methods.extract_options!
+ methods << block if block_given?
+ return methods, options
+ end
+
+ def extract_options(*methods, &block)
+ self.class.extract_options(*methods, &block)
+ end
+ end
+
+ class Callback
+ attr_reader :kind, :method, :identifier, :options
+
+ def initialize(kind, method, options = {})
+ @kind = kind
+ @method = method
+ @identifier = options[:identifier]
+ @options = options
+ end
+
+ def ==(other)
+ case other
+ when Callback
+ (self.identifier && self.identifier == other.identifier) || self.method == other.method
+ else
+ (self.identifier && self.identifier == other) || self.method == other
+ end
+ end
+
+ def eql?(other)
+ self == other
+ end
+
+ def dup
+ self.class.new(@kind, @method, @options.dup)
+ end
+
+ def hash
+ if @identifier
+ @identifier.hash
+ else
+ @method.hash
+ end
+ end
+
+ def call(*args, &block)
+ evaluate_method(method, *args, &block) if should_run_callback?(*args)
+ rescue LocalJumpError
+ raise ArgumentError,
+ "Cannot yield from a Proc type filter. The Proc must take two " +
+ "arguments and execute #call on the second argument."
+ end
+
+ private
+ def evaluate_method(method, *args, &block)
+ case method
+ when Symbol
+ object = args.shift
+ object.send(method, *args, &block)
+ when String
+ eval(method, args.first.instance_eval { binding })
+ when Proc, Method
+ method.call(*args, &block)
+ else
+ if method.respond_to?(kind)
+ method.send(kind, *args, &block)
+ else
+ raise ArgumentError,
+ "Callbacks must be a symbol denoting the method to call, a string to be evaluated, " +
+ "a block to be invoked, or an object responding to the callback method."
+ end
+ end
+ end
+
+ def should_run_callback?(*args)
+ [options[:if]].flatten.compact.all? { |a| evaluate_method(a, *args) } &&
+ ![options[:unless]].flatten.compact.any? { |a| evaluate_method(a, *args) }
+ end
+ end
+
+ def self.included(base)
+ base.extend ClassMethods
+ end
+
+ module ClassMethods
+ def define_callbacks(*callbacks)
+ ActiveSupport::Deprecation.warn('ActiveSupport::DeprecatedCallbacks has been deprecated in favor of ActiveSupport::Callbacks', caller)
+
+ callbacks.each do |callback|
+ class_eval <<-"end_eval", __FILE__, __LINE__ + 1
+ def self.#{callback}(*methods, &block) # def self.before_save(*methods, &block)
+ callbacks = CallbackChain.build(:#{callback}, *methods, &block) # callbacks = CallbackChain.build(:before_save, *methods, &block)
+ @#{callback}_callbacks ||= CallbackChain.new # @before_save_callbacks ||= CallbackChain.new
+ @#{callback}_callbacks.concat callbacks # @before_save_callbacks.concat callbacks
+ end # end
+ #
+ def self.#{callback}_callback_chain # def self.before_save_callback_chain
+ @#{callback}_callbacks ||= CallbackChain.new # @before_save_callbacks ||= CallbackChain.new
+ #
+ if superclass.respond_to?(:#{callback}_callback_chain) # if superclass.respond_to?(:before_save_callback_chain)
+ CallbackChain.new( # CallbackChain.new(
+ superclass.#{callback}_callback_chain + # superclass.before_save_callback_chain +
+ @#{callback}_callbacks # @before_save_callbacks
+ ) # )
+ else # else
+ @#{callback}_callbacks # @before_save_callbacks
+ end # end
+ end # end
+ end_eval
+ end
+ end
+ end
+
+ # Runs all the callbacks defined for the given options.
+ #
+ # If a block is given it will be called after each callback receiving as arguments:
+ #
+ # * the result from the callback
+ # * the object which has the callback
+ #
+ # If the result from the block evaluates to +true+, the callback chain is stopped.
+ #
+ # Example:
+ # class Storage
+ # include ActiveSupport::DeprecatedCallbacks
+ #
+ # define_callbacks :before_save, :after_save
+ # end
+ #
+ # class ConfigStorage < Storage
+ # before_save :pass
+ # before_save :pass
+ # before_save :stop
+ # before_save :pass
+ #
+ # def pass
+ # puts "pass"
+ # end
+ #
+ # def stop
+ # puts "stop"
+ # return false
+ # end
+ #
+ # def save
+ # result = run_callbacks(:before_save) { |result, object| result == false }
+ # puts "- save" if result
+ # end
+ # end
+ #
+ # config = ConfigStorage.new
+ # config.save
+ #
+ # Output:
+ # pass
+ # pass
+ # stop
+ def run_callbacks(kind, options = {}, &block)
+ self.class.send("#{kind}_callback_chain").run(self, options, &block)
+ end
+ end
+end
View
2 activesupport/lib/active_support/deprecation/behaviors.rb
@@ -23,7 +23,7 @@ def default_behavior
$stderr.puts callstack.join("\n ") if debug
},
'development' => Proc.new { |message, callstack|
- logger = defined?(Rails) ? Rails.logger : Logger.new($stderr)
+ logger = (Rails.logger if defined?(Rails)) || Logger.new($stderr)
logger.warn message
logger.debug callstack.join("\n ") if debug
}
View
13 activesupport/lib/active_support/memoizable.rb
@@ -2,19 +2,6 @@
require 'active_support/core_ext/module/aliasing'
module ActiveSupport
- module SafelyMemoizable
- def safely_memoize(*symbols)
- symbols.each do |symbol|
- class_eval <<-RUBY, __FILE__, __LINE__ + 1
- def #{symbol}(*args)
- memoized = @_memoized_#{symbol} || ::ActiveSupport::ConcurrentHash.new
- memoized[args] ||= memoized_#{symbol}(*args)
- end
- RUBY
- end
- end
- end
-
module Memoizable
def self.memoized_ivar_for(symbol)
"@_memoized_#{symbol.to_s.sub(/\?\Z/, '_query').sub(/!\Z/, '_bang')}".to_sym
View
2 activesupport/lib/active_support/message_verifier.rb
@@ -29,7 +29,7 @@ def verify(signed_message)
raise InvalidSignature if signed_message.blank?
data, digest = signed_message.split("--")
- if secure_compare(digest, generate_digest(data))
+ if data.present? && digest.present? && secure_compare(digest, generate_digest(data))
Marshal.load(ActiveSupport::Base64.decode64(data))
else
raise InvalidSignature
View
563 activesupport/lib/active_support/new_callbacks.rb
@@ -1,563 +0,0 @@
-require 'active_support/core_ext/array/wrap'
-require 'active_support/core_ext/class/inheritable_attributes'
-require 'active_support/core_ext/kernel/reporting'
-
-module ActiveSupport
- # Callbacks are hooks into the lifecycle of an object that allow you to trigger logic
- # before or after an alteration of the object state.
- #
- # Mixing in this module allows you to define callbacks in your class.
- #
- # Example:
- # class Storage
- # include ActiveSupport::Callbacks
- #
- # define_callbacks :save
- # end
- #
- # class ConfigStorage < Storage
- # set_callback :save, :before, :saving_message
- # def saving_message
- # puts "saving..."
- # end
- #
- # set_callback :save, :after do |object|
- # puts "saved"
- # end
- #
- # def save
- # _run_set_callback :save,s do
- # puts "- save"
- # end
- # end
- # end
- #
- # config = ConfigStorage.new
- # config.save
- #
- # Output:
- # saving...
- # - save
- # saved
- #
- # Callbacks from parent classes are inherited.
- #
- # Example:
- # class Storage
- # include ActiveSupport::Callbacks
- #
- # define_callbacks :save
- #
- # set_callback :save, :before, :prepare
- # def prepare
- # puts "preparing save"
- # end
- # end
- #
- # class ConfigStorage < Storage
- # set_callback :save, :before, :saving_message
- # def saving_message
- # puts "saving..."
- # end
- #
- # set_callback :save, :after do |object|
- # puts "saved"
- # end
- #
- # def save
- # _run_set_callback :save,s do
- # puts "- save"
- # end
- # end
- # end
- #
- # config = ConfigStorage.new
- # config.save
- #
- # Output:
- # preparing save
- # saving...
- # - save
- # saved
- #
- module NewCallbacks
- def self.included(klass)
- klass.extend ClassMethods
- end
-
- def run_callbacks(kind, options = {}, &blk)
- send("_run_#{kind}_callbacks", &blk)
- end
-
- class Callback
- @@_callback_sequence = 0
-
- attr_accessor :chain, :filter, :kind, :options, :per_key, :klass
-
- def initialize(chain, filter, kind, options, klass)
- @chain, @kind, @klass = chain, kind, klass
- normalize_options!(options)
-
- @per_key = options.delete(:per_key)
- @raw_filter, @options = filter, options
- @filter = _compile_filter(filter)
- @compiled_options = _compile_options(options)
- @callback_id = next_id
-
- _compile_per_key_options
- end
-
- def clone(chain, klass)
- obj = super()
- obj.chain = chain
- obj.klass = klass
- obj.per_key = @per_key.dup
- obj.options = @options.dup
- obj.per_key[:if] = @per_key[:if].dup
- obj.per_key[:unless] = @per_key[:unless].dup
- obj.options[:if] = @options[:if].dup
- obj.options[:unless] = @options[:unless].dup
- obj
- end
-
- def normalize_options!(options)
- options[:if] = Array.wrap(options[:if])
- options[:unless] = Array.wrap(options[:unless])
-
- options[:per_key] ||= {}
- options[:per_key][:if] = Array.wrap(options[:per_key][:if])
- options[:per_key][:unless] = Array.wrap(options[:per_key][:unless])
- end
-
- def name
- chain.name
- end
-
- def next_id
- @@_callback_sequence += 1
- end
-
- def matches?(_kind, _filter)
- @kind == _kind && @filter == _filter
- end
-
- def _update_filter(filter_options, new_options)
- filter_options[:if].push(new_options[:unless]) if new_options.key?(:unless)
- filter_options[:unless].push(new_options[:if]) if new_options.key?(:if)
- end
-
- def recompile!(_options, _per_key)
- _update_filter(self.options, _options)
- _update_filter(self.per_key, _per_key)
-
- @callback_id = next_id
- @filter = _compile_filter(@raw_filter)
- @compiled_options = _compile_options(@options)
- _compile_per_key_options
- end
-
- def _compile_per_key_options
- key_options = _compile_options(@per_key)
-
- @klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
- def _one_time_conditions_valid_#{@callback_id}?
- true #{key_options[0]}
- end
- RUBY_EVAL
- end
-
- # This will supply contents for before and around filters, and no
- # contents for after filters (for the forward pass).
- def start(key=nil, object=nil)
- return if key && !object.send("_one_time_conditions_valid_#{@callback_id}?")
-
- # options[0] is the compiled form of supplied conditions
- # options[1] is the "end" for the conditional
- #
- if @kind == :before || @kind == :around
- if @kind == :before
- # if condition # before_save :filter_name, :if => :condition
- # filter_name
- # end
- filter = <<-RUBY_EVAL
- unless halted
- result = #{@filter}
- halted = (#{chain.config[:terminator]})
- end
- RUBY_EVAL
-
- [@compiled_options[0], filter, @compiled_options[1]].compact.join("\n")
- else
- # Compile around filters with conditions into proxy methods
- # that contain the conditions.
- #
- # For `around_save :filter_name, :if => :condition':
- #
- # def _conditional_callback_save_17
- # if condition
- # filter_name do
- # yield self
- # end
- # else
- # yield self
- # end
- # end
- #
- name = "_conditional_callback_#{@kind}_#{next_id}"
- txt, line = <<-RUBY_EVAL, __LINE__ + 1
- def #{name}(halted)
- #{@compiled_options[0] || "if true"} && !halted
- #{@filter} do
- yield self
- end
- else
- yield self
- end
- end
- RUBY_EVAL