Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
= 5.1.1
* follow-up non-invasive performance optimizations across path introspection, resource services,
specifications, named route helpers, and controller helpers:
- replace per-request lookahead Regexp compilation in RequestPathIntrospection#remove_current_segment
with UTF-8-safe byte-indexed substring search (with character-index fallback for multi-slash segments)
- call service.__send__(:find, ...) directly in ResourceService#find instead of falling back through
super/method_missing, replace ActiveSupport delegate wrappers with lightweight controller readers,
and reuse lazy SingletonSpecification#build_method_name
- fast-path Specification option validation and default foreign_key derivation, and add lazy
plural_name / params_method_name helpers reused by #resources_name and #resource_params
- precompute class-level plural_route_name in resources_controller_for (invalidated if route_name
changes), guard empty enclosing/args splats and eql? filtering in NamedRouteHelper generated helpers,
and read name_prefix once per dispatch
- reduce redundant params lookups in ResourceMethods (#find_resource, #new_resource, #destroy_resource),
use anonymous block forwarding in #new_resource, and remove .tap in Helper#form_for_resource_options

= 5.1.0
* performance improvements across named route helpers, request introspection, wildcard loading,
form_for_resource, parameter filtering, and Specification initialization:
Expand Down
50 changes: 38 additions & 12 deletions lib/resources_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,7 @@ def resources_controller_for(name, options = {}, &block)

unless included_modules.include? ResourcesController::InstanceMethods
class_attribute :specifications, :route_name
class_attribute :plural_route_name, :plural_route_name_source, :instance_accessor => false
extend ResourcesController::ClassMethods
helper ResourcesController::Helper
include ResourcesController::InstanceMethods, ResourcesController::NamedRouteHelper
Expand All @@ -481,7 +482,10 @@ def resources_controller_for(name, options = {}, &block)
nested_in(*options.delete(:in)) if options[:in]

class_attribute :resource_specification, :instance_writer => false
self.resource_specification = Specification.new(name, options, &block)
spec = Specification.new(name, options, &block)
self.resource_specification = spec
self.plural_route_name_source = self.route_name.dup.freeze
self.plural_route_name = ((self.route_name == spec.name && !spec.singleton?) ? spec.plural_name : self.route_name.pluralize).freeze
end

# Creates a resource specification mapping. Use this to specify how to find an enclosing resource that
Expand Down Expand Up @@ -568,7 +572,7 @@ def resource_name

# name of the resource collection
def resources_name
@resources_name ||= resource_specification.name.pluralize
@resources_name ||= +resource_specification.plural_name
end

# returns the controller's resource class
Expand Down Expand Up @@ -662,7 +666,9 @@ def save_resource
def load_enclosing_resources
namespace_segments.each {|segment| update_name_prefix("#{segment}_") }
specifications.each_with_index do |spec, idx|
if spec == '*'
if spec.is_a?(Specification)
load_enclosing_resource_from_specification(spec)
elsif spec == '*'
load_wildcards_from(idx)
elsif spec.is_a?(String) && spec.start_with?('?')
load_wildcard(spec[1..])
Expand Down Expand Up @@ -740,7 +746,8 @@ def load_enclosing_resource_from_specification(spec)

def add_enclosing_resource(resource, options = {})
name = options[:name] || resource.class.name.underscore
update_name_prefix(options[:name_prefix] || (options[:name_prefix] == false ? '' : "#{name}_"))
prefix = options[:name_prefix]
update_name_prefix(prefix || (prefix == false ? '' : "#{name}_"))
enclosing_resources << resource
enclosing_collection_resources << resource unless options[:is_singleton]
@enclosing_resource_name = options[:name]
Expand Down Expand Up @@ -770,18 +777,30 @@ class ResourceService < BasicObject
:resource_specification, :resource_class, :enclosing_resource].freeze

attr_reader :controller
delegate :resource_specification, :resource_class, :enclosing_resource, :to => :controller

def initialize(controller)
@controller = controller
end

def resource_specification
controller.resource_specification
end

def resource_class
controller.resource_class
end

def enclosing_resource
controller.enclosing_resource
end

def method_missing(method, ...)
service.__send__(method, ...)
end

def find(...)
resource_specification.find ? resource_specification.find_custom(controller) : super
spec = resource_specification
spec.find ? spec.find_custom(controller) : service.__send__(:find, ...)
end

# build association on the enclosing resource if there is one, otherwise call new
Expand Down Expand Up @@ -811,25 +830,32 @@ def respond_to?(method, include_private = false)
end

def service
@service ||= enclosing_resource ? enclosing_resource.send(resource_specification.source) : resource_class
@service ||= if (encl = enclosing_resource)
encl.send(resource_specification.source)
else
resource_class
end
end
end

class SingletonResourceService < ResourceService
def find(...)
if resource_specification.find
resource_specification.find_custom(controller)
spec = resource_specification
if spec.find
spec.find_custom(controller)
elsif controller.enclosing_resources.size > 0
enclosing_resource.send(resource_specification.source)
enclosing_resource.send(spec.source)
else
::ResourcesController.raise_cant_find_singleton(controller.resource_name, controller.resource_class)
end
end

# build association on the enclosing resource if there is one, otherwise call new
def new(...)
if enclosing_resource
enclosing_resource.send("build_#{resource_specification.source}", ...)
if (encl = enclosing_resource)
spec = resource_specification
build_method = spec.respond_to?(:build_method_name) ? spec.build_method_name : :"build_#{spec.source}"
encl.send(build_method, ...)
else
service.new(...)
end
Expand Down
26 changes: 13 additions & 13 deletions lib/resources_controller/helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,20 +97,20 @@ def respond_to_missing?(method, include_private = false)

private
def form_for_resource_options(resource, resource_name, options)
options.dup.tap do |opts|
is_new = nil
opts[:html] ||= {}
opts[:html][:method] ||= (is_new = resource.new_record?) ? :post : :put
opts[:as] = resource_name
url_options = opts[:url_options] ? opts.delete(:url_options) : nil
opts[:url] ||= if controller.resource_specification.singleton?
url_options ? resource_path(url_options) : resource_path
elsif is_new.nil? ? resource.new_record? : is_new
url_options ? resources_path(url_options) : resources_path
else
url_options ? resource_path(resource, url_options) : resource_path(resource)
end
opts = options.dup
is_new = nil
opts[:html] ||= {}
opts[:html][:method] ||= (is_new = resource.new_record?) ? :post : :put
opts[:as] = resource_name
url_options = opts.delete(:url_options) if opts[:url_options]
opts[:url] ||= if controller.resource_specification.singleton?
url_options ? resource_path(url_options) : resource_path
elsif is_new.nil? ? resource.new_record? : is_new
url_options ? resources_path(url_options) : resources_path
else
url_options ? resource_path(resource, url_options) : resource_path(resource)
end
opts
end
end
end
51 changes: 41 additions & 10 deletions lib/resources_controller/named_route_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,20 +122,26 @@ def named_route_for_helper_method(route_method)
Rails.application.routes.named_routes.get(route_key.to_sym)
end

# route_name is fixed for the life of the controller, and pluralize is the most
# expensive operation on this path, so it is memoised rather than run per call.
# route_name is fixed for the life of the controller class, so its plural form is
# precomputed on the class and only pluralized per instance if route_name is overridden.
def resources_route_name
@resources_route_name ||= route_name.pluralize
current = route_name
if self.class.respond_to?(:plural_route_name_source) && current == self.class.plural_route_name_source
self.class.plural_route_name
else
@resources_route_name ||= current.pluralize
end
end

# defines a method that calls the appropriate named route method, with appropriate args.
def define_resource_named_route_helper_method(method)
self.class.send :module_eval, <<-end_eval, __FILE__, __LINE__
def #{method}(...)
if name_prefix.to_s.empty?
prefix = name_prefix.to_s
if prefix.empty?
#{method}_for_(...)
else
send(:"#{method}_for_\#{name_prefix}", ...)
send(:"#{method}_for_\#{prefix}", ...)
end
end
end_eval
Expand All @@ -151,7 +157,7 @@ def resource_named_route_helper_method_for_name_prefix?(method)

def extract_resource_url_options(args)
du_opts = default_url_options
if args.last.is_a?(Hash) && args.last.extractable_options?
if !args.empty? && (last = args.last).is_a?(Hash) && last.extractable_options?
options = args.pop
options.merge!(du_opts) unless du_opts.empty?
options
Expand All @@ -170,9 +176,25 @@ def define_resource_named_route_helper_method_for_name_prefix(method)
self.class.send :module_eval, <<-end_eval, __FILE__, __LINE__
def #{method}(*args)
options = extract_resource_url_options(args)
encl = args.size < #{required_args} ? enclosing_collection_resources : enclosing_collection_resources - [enclosing_resource]
encl = enclosing_collection_resources
if args.size >= #{required_args} && !encl.empty?
target = enclosing_resource
encl = if encl.size == 1 && encl[0].eql?(target)
nil
else
encl.reject { |r| r.eql?(target) }
end
end
args << options if options && !options.empty?
#{route_method}(*encl, *args)
if encl.nil? || encl.empty?
args.empty? ? #{route_method} : #{route_method}(*args)
elsif args.empty?
#{route_method}(*encl)
elsif encl.size == 1
#{route_method}(encl[0], *args)
else
#{route_method}(*encl, *args)
end
end
end_eval

Expand All @@ -183,9 +205,18 @@ def #{method}(*args)
self.class.send :module_eval, <<-end_eval, __FILE__, __LINE__
def #{method}(*args)
options = extract_resource_url_options(args)
#{"args.unshift(resource) if enclosing_collection_resources.size + args.size < #{required_args}" if required_args > 0}
encl = enclosing_collection_resources
#{"args.unshift(resource) if encl.size + args.size < #{required_args}" if required_args > 0}
args << options if options && !options.empty?
#{route_method}(*enclosing_collection_resources, *args)
if encl.empty?
args.empty? ? #{route_method} : #{route_method}(*args)
elsif args.empty?
#{route_method}(*encl)
elsif encl.size == 1
#{route_method}(encl[0], *args)
else
#{route_method}(*encl, *args)
end
end
end_eval
end
Expand Down
34 changes: 23 additions & 11 deletions lib/resources_controller/request_path_introspection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,17 +61,27 @@ def param_keys
# Removes the current resource segment, and everything after it, from the path,
# e.g. '/users/1/forums/2' => '/users/1'.
#
# This is only called from #nesting_request_path, which is memoised per request,
# so the pattern is built at most once per request - there is no need to cache it.
# The segment is escaped so that it is matched literally, as in #remove_namespace.
# Uses direct byte-indexed substring search rather than compiling a lookahead
# Regexp per request, so the segment is matched literally with minimal allocations.
def remove_current_segment(path)
segment = Regexp.escape(current_segment.to_s)
pattern = if respond_to?(:resource_specification) && resource_specification.singleton?
%r(/#{segment}(?!.*/#{segment}).*$)
needle = "/#{current_segment}"
last = path.byterindex(needle)
return path.dup unless last

singleton = respond_to?(:resource_specification) && resource_specification.singleton?
if needle.byteindex('/', 1)
char_last = path.rindex(needle)
start = char_last - needle.length + (singleton ? 1 : 0)
return path[0, path.index(needle, start > 0 ? start : 0)]
end

idx = if singleton
last
else
%r(/#{segment}(?!.+/#{segment}).*$)
len = needle.bytesize
last >= len && path.byteslice(last - len, len) == needle ? last - len : last
end
path.sub(pattern, '')
path.byteslice(0, idx)
end

def current_segment
Expand Down Expand Up @@ -106,12 +116,14 @@ def segments_for_path_and_keys(path, keys)

def segment_for_key(key)
key_str = key.to_s
if respond_to?(:specifications) && (spec = specifications.find {|s| s.respond_to?(:key) && s.key == key_str})
return spec.segment
if respond_to?(:specifications)
specifications.each do |s|
return s.segment if s.respond_to?(:key) && s.key == key_str
end
end

resource_specification_map.each_value do |spec|
return spec.segment if spec.key == key_str
return spec.segment if spec.respond_to?(:key) && spec.key == key_str
end

key_str.delete_suffix('_id').pluralize
Expand Down
28 changes: 19 additions & 9 deletions lib/resources_controller/resource_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,31 @@ def find_resources

# finds the resource, using the passed id, defaults to the current params[:id]
def find_resource(id = nil)
id ||= respond_to?(:params) && params.is_a?(ActionController::Parameters) && params[:id]
unless id
id = respond_to?(:params) && (p = params).is_a?(ActionController::Parameters) && p[:id]
end
resource_service.find id
end

# makes a new resource, if attributes are not supplied, determine them from the
# params hash and the current resource_class, or resource_name (the latter left in for BC)
def new_resource(attributes = nil, &block)
if attributes.blank? && respond_to?(:params) && params.is_a?(ActionController::Parameters)
resource_form_name = ActiveModel::Naming.singular(resource_class)
attributes = params[resource_form_name] || params[resource_name] || {}
def new_resource(attributes = nil, &)
if attributes.blank? && respond_to?(:params)
p = params
if p.is_a?(ActionController::Parameters)
resource_form_name = ActiveModel::Naming.singular(resource_class)
name = resource_name
attributes = p[resource_form_name] || (name == resource_form_name ? nil : p[name]) || {}
end
end
resource_service.new attributes, &block
resource_service.new(attributes, &)
end

# destroys and returns the resource, using the passed id, defaults to the current params[:id]
def destroy_resource(id = nil)
id ||= respond_to?(:params) && params.is_a?(ActionController::Parameters) && params[:id]
unless id
id = respond_to?(:params) && (p = params).is_a?(ActionController::Parameters) && p[:id]
end
resource_service.destroy id
end

Expand All @@ -36,15 +44,17 @@ def destroy_resource(id = nil)

# Never trust parameters from the scary internet, only allow the white list through.
def resource_params
method_name = "#{resource_name}_params"
name = resource_name
spec = resource_specification
method_name = name == spec.name ? spec.params_method_name : :"#{name}_params"
if respond_to?(method_name, true)
send(method_name)
else
columns = resource_service.content_columns.filter_map do |c|
col_name = c.name
col_name unless EXCLUDED_PARAM_COLUMNS.include?(col_name)
end
params.fetch(resource_name) { {} }.permit(*columns)
params.fetch(name) { {} }.permit(*columns)
end
end

Expand Down
Loading
Loading