提交 756b32ef 编写于 作者: J José Valim

Merge remote branch 'thedarkone/performance'

......@@ -5,16 +5,18 @@ module UrlFor
include AbstractController::UrlFor
def url_options
options = {}
if _routes.equal?(env["action_dispatch.routes"])
options[:script_name] = request.script_name.dup
end
@_url_options ||= begin
options = {}
if _routes.equal?(env["action_dispatch.routes"])
options[:script_name] = request.script_name.dup
end
super.merge(options).reverse_merge(
:host => request.host_with_port,
:protocol => request.protocol,
:_path_segments => request.symbolized_path_parameters
)
super.merge(options).reverse_merge(
:host => request.host_with_port,
:protocol => request.protocol,
:_path_segments => request.symbolized_path_parameters
).freeze
end
end
end
end
......@@ -26,6 +26,10 @@ class Railtie < Rails::Railtie
options.stylesheets_dir ||= paths.public.stylesheets.to_a.first
options.page_cache_directory ||= paths.public.to_a.first
# make sure readers methods get compiled
options.asset_path ||= nil
options.asset_host ||= nil
ActiveSupport.on_load(:action_controller) do
include app.routes.mounted_helpers
extend ::AbstractController::Railties::RoutesHelpers.with(app.routes)
......@@ -33,5 +37,11 @@ class Railtie < Rails::Railtie
options.each { |k,v| send("#{k}=", v) }
end
end
config.after_initialize do
ActiveSupport.on_load(:action_controller) do
config.crystalize! if config.respond_to?(:crystalize!)
end
end
end
end
......@@ -15,12 +15,12 @@ def scheme
# Returns 'https://' if this is an SSL request and 'http://' otherwise.
def protocol
ssl? ? 'https://' : 'http://'
@protocol ||= ssl? ? 'https://' : 'http://'
end
# Is this an SSL request?
def ssl?
@env['HTTPS'] == 'on' || @env['HTTP_X_FORWARDED_PROTO'] == 'https'
@ssl ||= @env['HTTPS'] == 'on' || @env['HTTP_X_FORWARDED_PROTO'] == 'https'
end
# Returns the \host for this request, such as "example.com".
......
......@@ -105,7 +105,7 @@ def polymorphic_url(record_or_hash_or_array, options = {})
else [ record_or_hash_or_array ]
end
inflection = if options[:action].to_s == "new"
inflection = if options[:action] && options[:action].to_s == "new"
args.pop
:singular
elsif (record.respond_to?(:persisted?) && !record.persisted?)
......@@ -168,10 +168,7 @@ def routing_type(options)
end
def build_named_route_call(records, inflection, options = {})
unless records.is_a?(Array)
record = extract_record(records)
route = []
else
if records.is_a?(Array)
record = records.pop
route = records.map do |parent|
if parent.is_a?(Symbol) || parent.is_a?(String)
......@@ -180,6 +177,9 @@ def build_named_route_call(records, inflection, options = {})
ActiveModel::Naming.route_key(parent).singularize
end
end
else
record = extract_record(records)
route = []
end
if record.is_a?(Symbol) || record.is_a?(String)
......
......@@ -334,6 +334,19 @@ def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil
end
class Generator #:nodoc:
PARAMETERIZE = {
:parameterize => lambda do |name, value|
if name == :controller
value
elsif value.is_a?(Array)
value.map { |v| Rack::Mount::Utils.escape_uri(v.to_param) }.join('/')
else
return nil unless param = value.to_param
param.split('/').map { |v| Rack::Mount::Utils.escape_uri(v) }.join("/")
end
end
}
attr_reader :options, :recall, :set, :named_route
def initialize(options, recall, set, extras = false)
......@@ -422,7 +435,7 @@ def handle_nil_action!
end
def generate
path, params = @set.set.generate(:path_info, named_route, options, recall, opts)
path, params = @set.set.generate(:path_info, named_route, options, recall, PARAMETERIZE)
raise_routing_error unless path
......@@ -430,26 +443,12 @@ def generate
return [path, params.keys] if @extras
path << "?#{params.to_query}" if params.any?
path << "?#{params.to_query}" unless params.empty?
path
rescue Rack::Mount::RoutingError
raise_routing_error
end
def opts
parameterize = lambda do |name, value|
if name == :controller
value
elsif value.is_a?(Array)
value.map { |v| Rack::Mount::Utils.escape_uri(v.to_param) }.join('/')
else
return nil unless param = value.to_param
param.split('/').map { |v| Rack::Mount::Utils.escape_uri(v) }.join("/")
end
end
{:parameterize => parameterize}
end
def raise_routing_error
raise ActionController::RoutingError.new("No route matches #{options.inspect}")
end
......
......@@ -209,8 +209,7 @@ def initialize(lookup_context = nil, assigns_for_first_render = {}, controller =
@_request = controller.request if controller.respond_to?(:request)
end
config = controller && controller.respond_to?(:config) ? controller.config : {}
@_config = ActiveSupport::InheritableOptions.new(config)
@_config = controller && controller.respond_to?(:config) ? controller.config.inheritable_copy : {}
@_content_for = Hash.new { |h,k| h[k] = ActiveSupport::SafeBuffer.new }
@_virtual_path = nil
......
......@@ -705,19 +705,29 @@ def audio_tag(source, options = {})
private
def rewrite_extension?(source, dir, ext)
source_ext = File.extname(source)[1..-1]
ext && (source_ext.blank? || (ext != source_ext && File.exist?(File.join(config.assets_dir, dir, "#{source}.#{ext}"))))
def rewrite_extension(source, dir, ext)
source_ext = File.extname(source)
if source_ext.empty?
"#{source}.#{ext}"
elsif ext != source_ext[1..-1]
with_ext = "#{source}.#{ext}"
with_ext if File.exist?(File.join(config.assets_dir, dir, with_ext))
end || source
end
def rewrite_host_and_protocol(source, has_request)
host = compute_asset_host(source)
if has_request && host.present? && !is_uri?(host)
if has_request && host && !is_uri?(host)
host = "#{controller.request.protocol}#{host}"
end
"#{host}#{source}"
end
def rewrite_relative_url_root(source, relative_url_root)
relative_url_root && !source.starts_with?("#{relative_url_root}/") ? "#{relative_url_root}#{source}" : source
end
# Add the the extension +ext+ if not present. Return full URLs otherwise untouched.
# Prefix with <tt>/dir/</tt> if lacking a leading +/+. Account for relative URL
# roots. Rewrite the asset path for cache-busting asset ids. Include
......@@ -725,17 +735,15 @@ def rewrite_host_and_protocol(source, has_request)
def compute_public_path(source, dir, ext = nil, include_host = true)
return source if is_uri?(source)
source += ".#{ext}" if rewrite_extension?(source, dir, ext)
source = "/#{dir}/#{source}" unless source[0] == ?/
source = rewrite_extension(source, dir, ext) if ext
source = "/#{dir}/#{source}" unless source[0] == ?/
if controller.respond_to?(:env) && controller.env["action_dispatch.asset_path"]
source = rewrite_asset_path(source, controller.env["action_dispatch.asset_path"])
end
source = rewrite_asset_path(source, config.asset_path)
has_request = controller.respond_to?(:request)
if has_request && include_host && source !~ %r{^#{controller.config.relative_url_root}/}
source = "#{controller.config.relative_url_root}#{source}"
end
source = rewrite_relative_url_root(source, controller.config.relative_url_root) if has_request && include_host
source = rewrite_host_and_protocol(source, has_request) if include_host
source
......@@ -802,10 +810,10 @@ def rewrite_asset_path(source, path = nil)
end
asset_id = rails_asset_id(source)
if asset_id.blank?
if asset_id.empty?
source
else
source + "?#{asset_id}"
"#{source}?#{asset_id}"
end
end
......
......@@ -95,7 +95,7 @@ def url_options
# # => javascript:history.back()
def url_for(options = {})
options ||= {}
url = case options
case options
when String
options
when Hash
......@@ -106,8 +106,6 @@ def url_for(options = {})
else
polymorphic_path(options)
end
url
end
# Creates a link tag of the given +name+ using a URL created by the set
......@@ -586,20 +584,24 @@ def current_page?(options)
private
def convert_options_to_data_attributes(options, html_options)
html_options = {} if html_options.nil?
html_options = html_options.stringify_keys
if html_options.nil?
link_to_remote_options?(options) ? {'data-remote' => 'true'} : {}
else
html_options = html_options.stringify_keys
html_options['data-remote'] = 'true' if link_to_remote_options?(options) || link_to_remote_options?(html_options)
if (options.is_a?(Hash) && options.key?('remote') && options.delete('remote')) || (html_options.is_a?(Hash) && html_options.key?('remote') && html_options.delete('remote'))
html_options['data-remote'] = 'true'
end
confirm = html_options.delete('confirm')
method = html_options.delete('method')
confirm = html_options.delete("confirm")
method, href = html_options.delete("method"), html_options['href']
add_confirm_to_attributes!(html_options, confirm) if confirm
add_method_to_attributes!(html_options, method) if method
add_confirm_to_attributes!(html_options, confirm) if confirm
add_method_to_attributes!(html_options, method) if method
html_options
end
end
html_options
def link_to_remote_options?(options)
options.is_a?(Hash) && options.key?('remote') && options.delete('remote')
end
def add_confirm_to_attributes!(html_options, confirm)
......
......@@ -73,8 +73,10 @@ module Naming
# Returns an ActiveModel::Name object for module. It can be
# used to retrieve all kinds of naming-related information.
def model_name
namespace = self.parents.detect { |n| n.respond_to?(:_railtie) }
@_model_name ||= ActiveModel::Name.new(self, namespace)
@_model_name ||= begin
namespace = self.parents.detect { |n| n.respond_to?(:_railtie) }
ActiveModel::Name.new(self, namespace)
end
end
# Returns the plural class name of a record or class. Examples:
......
......@@ -9,9 +9,29 @@ module ActiveSupport
module Configurable
extend ActiveSupport::Concern
class Configuration < ActiveSupport::InheritableOptions
def crystalize!
self.class.crystalize!(keys.reject {|key| respond_to?(key)})
end
# compiles reader methods so we don't have to go through method_missing
def self.crystalize!(keys)
keys.each do |key|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{key}; _get(#{key.inspect}); end
RUBY
end
end
end
module ClassMethods
def config
@_config ||= ActiveSupport::InheritableOptions.new(superclass.respond_to?(:config) ? superclass.config : {})
@_config ||= if superclass.respond_to?(:config)
superclass.config.inheritable_copy
else
# create a new "anonymous" class that will host the compiled reader methods
Class.new(Configuration).new
end
end
def configure
......@@ -48,7 +68,7 @@ def #{name}=(value); config.#{name} = value; end
# user.config.level # => 1
#
def config
@_config ||= ActiveSupport::InheritableOptions.new(self.class.config)
@_config ||= self.class.config.inheritable_copy
end
end
end
......
......@@ -72,11 +72,20 @@ def self.#{name}=(val)
remove_possible_method(:#{name})
define_method(:#{name}) { val }
end
if singleton_class?
class_eval do
remove_possible_method(:#{name})
def #{name}
defined?(@#{name}) ? @#{name} : singleton_class.#{name}
end
end
end
val
end
def #{name}
defined?(@#{name}) ? @#{name} : singleton_class.#{name}
defined?(@#{name}) ? @#{name} : self.class.#{name}
end
def #{name}?
......@@ -87,4 +96,15 @@ def #{name}?
attr_writer name if instance_writer
end
end
private
def singleton_class?
# in case somebody is crazy enough to overwrite allocate
allocate = Class.instance_method(:allocate)
# object.class always points to a real (non-singleton) class
allocate.bind(self).call.class != self
rescue TypeError
# MRI/YARV/JRuby all disallow creating new instances of a singleton class
true
end
end
......@@ -35,11 +35,13 @@ def symbolize_keys!
# as keys, this will fail.
#
# ==== Examples
# { :name => "Rob", :years => "28" }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key(s): years"
# { :name => "Rob", :age => "28" }.assert_valid_keys("name", "age") # => raises "ArgumentError: Unknown key(s): name, age"
# { :name => "Rob", :years => "28" }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: years"
# { :name => "Rob", :age => "28" }.assert_valid_keys("name", "age") # => raises "ArgumentError: Unknown key: name"
# { :name => "Rob", :age => "28" }.assert_valid_keys(:name, :age) # => passes, raises nothing
def assert_valid_keys(*valid_keys)
unknown_keys = keys - [valid_keys].flatten
raise(ArgumentError, "Unknown key(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty?
valid_keys.flatten!
each_key do |k|
raise(ArgumentError, "Unknown key: #{k}") unless valid_keys.include?(k)
end
end
end
class Module
# Declares an attribute reader backed by an internally-named instance variable.
def attr_internal_reader(*attrs)
attrs.each do |attr|
module_eval "def #{attr}() #{attr_internal_ivar_name(attr)} end", __FILE__, __LINE__
end
attrs.each {|attr_name| attr_internal_define(attr_name, :reader)}
end
# Declares an attribute writer backed by an internally-named instance variable.
def attr_internal_writer(*attrs)
attrs.each do |attr|
module_eval "def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end", __FILE__, __LINE__
end
attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}
end
# Declares an attribute reader and writer backed by an internally-named instance
......@@ -29,4 +25,15 @@ class << self; attr_accessor :attr_internal_naming_format end
def attr_internal_ivar_name(attr)
Module.attr_internal_naming_format % attr
end
def attr_internal_define(attr_name, type)
internal_name = attr_internal_ivar_name(attr_name).sub(/\A@/, '')
class_eval do # class_eval is necessary on 1.9 or else the methods a made private
# use native attr_* methods as they are faster on some Ruby implementations
send("attr_#{type}", internal_name)
end
attr_name, internal_name = "#{attr_name}=", "#{internal_name}=" if type == :writer
alias_method attr_name, internal_name
remove_method internal_name
end
end
......@@ -18,6 +18,9 @@
#
module ActiveSupport #:nodoc:
class OrderedOptions < OrderedHash
alias_method :_get, :[] # preserve the original #[] method
protected :_get # make it protected
def []=(key, value)
super(key.to_sym, value)
end
......@@ -36,8 +39,19 @@ def method_missing(name, *args)
end
class InheritableOptions < OrderedOptions
def initialize(parent)
super() { |h,k| parent[k] }
def initialize(parent = nil)
if parent.kind_of?(OrderedOptions)
# use the faster _get when dealing with OrderedOptions
super() { |h,k| parent._get(k) }
elsif parent
super() { |h,k| parent[k] }
else
super()
end
end
def inheritable_copy
self.class.new(self)
end
end
end
......@@ -39,4 +39,22 @@ class Child < Parent
assert_equal :baz, instance.config.foo
assert_equal :bar, Parent.config.foo
end
test "configuration is crystalizeable" do
parent = Class.new { include ActiveSupport::Configurable }
child = Class.new(parent)
parent.config.bar = :foo
assert !parent.config.respond_to?(:bar)
assert !child.config.respond_to?(:bar)
assert !child.new.config.respond_to?(:bar)
parent.config.crystalize!
assert_equal :foo, parent.config.bar
assert_equal :foo, child.new.config.bar
assert_respond_to parent.config, :bar
assert_respond_to child.config, :bar
assert_respond_to child.new.config, :bar
end
end
\ No newline at end of file
......@@ -282,7 +282,7 @@ def test_assert_valid_keys
{ :failure => "stuff", :funny => "business" }.assert_valid_keys(:failure, :funny)
end
assert_raise(ArgumentError, "Unknown key(s): failore") do
assert_raise(ArgumentError, "Unknown key: failore") do
{ :failore => "stuff", :funny => "business" }.assert_valid_keys([ :failure, :funny ])
{ :failore => "stuff", :funny => "business" }.assert_valid_keys(:failure, :funny)
end
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册