From 9f5b5f84d94dd2b4f438f29fac3729966b9ab142 Mon Sep 17 00:00:00 2001 From: Jason Lee Date: Fri, 13 Nov 2026 13:33:54 +0100 Subject: [PATCH] Non-invasive performance optimizations across routing, introspection, and helpers - Defer named_routes lookups in NamedRouteHelper until helper code generation and avoid unnecessary allocations/send calls - Scan RequestPathIntrospection segments by index and streamline segment_for_key, resource_params, and load_wildcards_from - Avoid redundant #new_record? calls in Helper#form_for_resource_options and skip eager pluralization/foreign_key work in Specification - Raise ResourceMismatch cleanly on exhausted nesting_segments and forward blocks/keywords via method_missing - Add regression specs, update inline/RDoc comments, and bump version to 5.1.0 Co-authored-by: Antigravity --- CHANGELOG | 14 +++ lib/resources_controller.rb | 53 ++++++--- lib/resources_controller/helper.rb | 26 +++-- .../named_route_helper.rb | 103 +++++++++++------- .../request_path_introspection.rb | 50 ++++++--- lib/resources_controller/resource_methods.rb | 5 +- lib/resources_controller/specification.rb | 26 +++-- lib/resources_controller/version.rb | 2 +- spec/lib/action_view_helper_spec.rb | 18 +++ spec/lib/named_route_helper_spec.rb | 65 +++++++++++ spec/lib/request_path_introspection_spec.rb | 13 +++ spec/lib/resource_methods_spec.rb | 17 +++ spec/lib/resources_controller_spec.rb | 91 ++++++++++++++++ 13 files changed, 389 insertions(+), 94 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 1a379a4..edcef89 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,17 @@ += 5.1.0 + * performance improvements across named route helpers, request introspection, wildcard loading, + form_for_resource, parameter filtering, and Specification initialization: + - defer Rails named route lookups in NamedRouteHelper until helper method generation, checking + route availability via respond_to? and replacing dynamic send calls with direct route calls + - extract NamedRouteHelper#extract_resource_url_options using du_opts.dup / in-place merge! and + forward arguments cleanly with `...` across NamedRouteHelper and Helper#method_missing + - scan RequestPathIntrospection path segments by index without array shifting, and simplify + segment_for_key / resource_params / load_wildcards_from loops to avoid temporary allocations + - avoid redundant #new_record? calls in Helper#form_for_resource_options and skip eager + pluralization / foreign_key inflection in Specification when options already supply them + * raise ResourceMismatch instead of NoMethodError when nesting segments are exhausted in + load_enclosing_resource_from_specification, and forward blocks/keywords via method_missing + = 5.0.3 * use native argument forwarding in resource service proxies to reduce temporary allocations, with regression coverage for positional hashes, keywords, blocks, and custom finders diff --git a/lib/resources_controller.rb b/lib/resources_controller.rb index 1d678a6..50eaf0d 100644 --- a/lib/resources_controller.rb +++ b/lib/resources_controller.rb @@ -682,9 +682,11 @@ def load_wildcard(as = nil) segment = seg[:segment] singleton = seg[:singleton] - if resource_specification_map[segment] - spec = resource_specification_map[segment] - spec = spec.dup.tap {|s| s.as = as} if as + if (spec = resource_specification_map[segment]) + if as + spec = spec.dup + spec.as = as + end else spec = Specification.new(singleton ? segment : segment.singularize, :singleton => singleton, :as => as) end @@ -697,24 +699,43 @@ def load_wildcard(as = nil) # and how many single wildcards are prior to that. What is left over from # the current route enclosing names will be the number of wildcards we need to load def load_wildcards_from(start) - specs = specifications.slice(start..-1) - encls = nesting_segments.slice(enclosing_resources.size..-1) + specs = specifications + segments = nesting_segments + encl_offset = enclosing_resources.size + + spec_idx = nil + idx = start + while idx < specs.length + if specs[idx].is_a?(Specification) + spec_idx = idx + break + end + idx += 1 + end - if spec = specs.find {|s| s.is_a?(Specification)} - spec_seg = encls.index {|e| e[:segment] == spec.segment && e[:singleton] == spec.singleton?} or ResourcesController.raise_resource_mismatch(self) - number_of_wildcards = spec_seg - (specs.index(spec) -1) + if spec_idx + spec = specs[spec_idx] + seg_idx = encl_offset + while seg_idx < segments.length + e = segments[seg_idx] + break if e[:segment] == spec.segment && e[:singleton] == spec.singleton? + seg_idx += 1 + end + ResourcesController.raise_resource_mismatch(self) if seg_idx >= segments.length + number_of_wildcards = (seg_idx - encl_offset) - (spec_idx - start - 1) else - number_of_wildcards = encls.length - (specs.length - 1) + number_of_wildcards = (segments.length - encl_offset) - (specs.length - start - 1) end number_of_wildcards.times { load_wildcard } end def load_enclosing_resource_from_specification(spec) - spec.segment == nesting_segments[enclosing_resources.size][:segment] or ResourcesController.raise_resource_mismatch(self) - spec.find_from(self).tap do |resource| - add_enclosing_resource(resource, :name => spec.name, :name_prefix => spec.name_prefix, :is_singleton => spec.singleton?, :as => spec.as) - end + seg = nesting_segments[enclosing_resources.size] + (seg && spec.segment == seg[:segment]) or ResourcesController.raise_resource_mismatch(self) + resource = spec.find_from(self) + add_enclosing_resource(resource, :name => spec.name, :name_prefix => spec.name_prefix, :is_singleton => spec.singleton?, :as => spec.as) + resource end def add_enclosing_resource(resource, options = {}) @@ -722,7 +743,7 @@ def add_enclosing_resource(resource, options = {}) update_name_prefix(options[:name_prefix] || (options[:name_prefix] == false ? '' : "#{name}_")) enclosing_resources << resource enclosing_collection_resources << resource unless options[:is_singleton] - instance_variable_set(:@enclosing_resource_name, options[:name]) + @enclosing_resource_name = options[:name] instance_variable_set(:"@#{name}", resource) instance_variable_set(:"@#{options[:as]}", resource) if options[:as] end @@ -795,7 +816,7 @@ def service end class SingletonResourceService < ResourceService - def find(*args, **kwargs) + def find(...) if resource_specification.find resource_specification.find_custom(controller) elsif controller.enclosing_resources.size > 0 @@ -814,7 +835,7 @@ def new(...) end end - def destroy(*args, **kwargs) + def destroy(...) find.destroy end diff --git a/lib/resources_controller/helper.rb b/lib/resources_controller/helper.rb index 08bed8f..d6d6df2 100644 --- a/lib/resources_controller/helper.rb +++ b/lib/resources_controller/helper.rb @@ -52,6 +52,7 @@ def self.included(base) # Calls form_for with the appropriate action and method for the resource # # resource.new_record? is used to decide between a create or update action + # (unless both :html[:method] and :url are provided) # # You can optionally pass a resource object, default is to use self.resource # @@ -80,12 +81,12 @@ def form_for_resource(*args, &block) # Delegate named_route helper method to the controller. Create the delegation # to short circuit the method_missing call for future invocations. - def method_missing(method, *args, &block) + def method_missing(method, ...) if controller.resource_named_route_helper_method?(method) self.class.send(:delegate, method, :to => :controller) - controller.send(method, *args) + controller.send(method, ...) else - super(method, *args, &block) + super end end @@ -96,15 +97,18 @@ def respond_to_missing?(method, include_private = false) private def form_for_resource_options(resource, resource_name, options) - options.dup.tap do |options| - options[:html] ||= {} - options[:html][:method] ||= resource.new_record? ? :post : :put - options[:as] = resource_name - args = options[:url_options] ? [options.delete(:url_options)] : [] - options[:url] ||= if resource.new_record? - controller.resource_specification.singleton? ? resource_path(*args) : resources_path(*args) + 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 - controller.resource_specification.singleton? ? resource_path(*args) : resource_path(resource, *args) + url_options ? resource_path(resource, url_options) : resource_path(resource) end end end diff --git a/lib/resources_controller/named_route_helper.rb b/lib/resources_controller/named_route_helper.rb index 399b52e..9e073d4 100644 --- a/lib/resources_controller/named_route_helper.rb +++ b/lib/resources_controller/named_route_helper.rb @@ -34,16 +34,16 @@ class CantMapRoute < ArgumentError #:nodoc: # methods module NamedRouteHelper - def method_missing(method, *args, &block) + def method_missing(method, ...) # TODO: test that methods are only defined once - if resource_named_route_helper_method?(method, raise_error = true) + if resource_named_route_helper_method?(method, true) define_resource_named_route_helper_method(method) - send(method, *args) + send(method, ...) elsif resource_named_route_helper_method_for_name_prefix?(method) define_resource_named_route_helper_method_for_name_prefix(method) - send(method, *args) + send(method, ...) else - super(method, *args, &block) + super end end @@ -52,15 +52,15 @@ def respond_to_missing?(method, include_private = false) end # return true if the passed method (e.g. 'resources_path') corresponds to a defined - # named route helper method + # named route helper method (checked via respond_to? without querying named_routes) def resource_named_route_helper_method?(resource_method, raise_error = false) method_str = resource_method.to_s return false unless method_str.end_with?('_path', '_url') if method_str.include?('enclosing_resource') - _, route_method = route_and_method_from_enclosing_resource_method_and_name_prefix(method_str, name_prefix) + route_method = route_method_from_enclosing_resource_method_and_name_prefix(method_str, name_prefix) elsif method_str.include?('resource') - _, route_method = route_and_method_from_resource_method_and_name_prefix(method_str, name_prefix) + route_method = route_method_from_resource_method_and_name_prefix(method_str, name_prefix) else return false end @@ -84,31 +84,42 @@ def raise_resource_url_mapping_error(resource_method, route_method) end_str end - # passed something like (^|.*_)enclosing_resource(s)_.*(url|path)\z, will - # return the [route, route_method] for the expanded resource - def route_and_method_from_enclosing_resource_method_and_name_prefix(method, name_prefix) - if enclosing_resource - enclosing_route = name_prefix.delete_suffix('_') - method_str = method.to_s - is_plural = method_str.include?('enclosing_resources') - substitution = is_plural ? enclosing_route.pluralize : enclosing_route - route_method = method_str.sub(is_plural ? 'enclosing_resources' : 'enclosing_resource', substitution) - route_key = route_method.end_with?('_path') ? route_method.delete_suffix('_path') : route_method.delete_suffix('_url') - [Rails.application.routes.named_routes.get(route_key.to_sym), route_method] - else + def route_method_from_enclosing_resource_method_and_name_prefix(method, name_prefix) + unless enclosing_resource raise NoMethodError, "Tried to map :#{method} but there is no enclosing_resource for this controller" end + + enclosing_route = name_prefix.delete_suffix('_') + method_str = method.to_s + is_plural = method_str.include?('enclosing_resources') + substitution = is_plural ? enclosing_route.pluralize : enclosing_route + method_str.sub(is_plural ? 'enclosing_resources' : 'enclosing_resource', substitution) end - - # passed something like (^|.*_)resource(s)_.*(url|path)\z, will + + # passed something like (^|.*_)enclosing_resource(s)_.*(url|path)\z, will # return the [route, route_method] for the expanded resource - def route_and_method_from_resource_method_and_name_prefix(method, name_prefix) + def route_and_method_from_enclosing_resource_method_and_name_prefix(method, name_prefix) + route_method = route_method_from_enclosing_resource_method_and_name_prefix(method, name_prefix) + [named_route_for_helper_method(route_method), route_method] + end + + def route_method_from_resource_method_and_name_prefix(method, name_prefix) method_str = method.to_s is_resources = method_str.include?('resources_') replacement = "#{name_prefix}#{is_resources ? resources_route_name : route_name}" - route_method = method_str.sub(is_resources ? 'resources' : 'resource', replacement) - route_key = route_method.end_with?('_path') ? route_method.delete_suffix('_path') : route_method.delete_suffix('_url') - [Rails.application.routes.named_routes.get(route_key.to_sym), route_method] + method_str.sub(is_resources ? 'resources' : 'resource', replacement) + end + + # passed something like (^|.*_)resource(s)_.*(url|path)\z, will + # return the [route, route_method] for the expanded resource + def route_and_method_from_resource_method_and_name_prefix(method, name_prefix) + route_method = route_method_from_resource_method_and_name_prefix(method, name_prefix) + [named_route_for_helper_method(route_method), route_method] + end + + def named_route_for_helper_method(route_method) + route_key = route_method.delete_suffix(route_method.end_with?('_path') ? '_path' : '_url') + 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 @@ -120,17 +131,33 @@ def resources_route_name # 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}(*args) - send "#{method}_for_\#{name_prefix}", *args + def #{method}(...) + if name_prefix.to_s.empty? + #{method}_for_(...) + else + send(:"#{method}_for_\#{name_prefix}", ...) + end end end_eval end def resource_named_route_helper_method_for_name_prefix?(method) method_str = method.to_s - return false unless method_str.include?('_for_') + idx = method_str.index('_for_') + return false unless idx - resource_named_route_helper_method?(method_str.split('_for_', 2).first) + resource_named_route_helper_method?(method_str[0, idx]) + end + + def extract_resource_url_options(args) + du_opts = default_url_options + if args.last.is_a?(Hash) && args.last.extractable_options? + options = args.pop + options.merge!(du_opts) unless du_opts.empty? + options + elsif !du_opts.empty? + du_opts.dup + end end def define_resource_named_route_helper_method_for_name_prefix(method) @@ -142,11 +169,10 @@ def define_resource_named_route_helper_method_for_name_prefix(method) self.class.send :module_eval, <<-end_eval, __FILE__, __LINE__ def #{method}(*args) - options = args.extract_options! - options.merge!(default_url_options) - args = args.size < #{required_args} ? enclosing_collection_resources + args : enclosing_collection_resources - [enclosing_resource] + args - args << options unless options.empty? - send :#{route_method}, *args + options = extract_resource_url_options(args) + encl = args.size < #{required_args} ? enclosing_collection_resources : enclosing_collection_resources - [enclosing_resource] + args << options if options && !options.empty? + #{route_method}(*encl, *args) end end_eval @@ -156,11 +182,10 @@ def #{method}(*args) self.class.send :module_eval, <<-end_eval, __FILE__, __LINE__ def #{method}(*args) - options = args.extract_options! - options.merge!(default_url_options) + options = extract_resource_url_options(args) #{"args.unshift(resource) if enclosing_collection_resources.size + args.size < #{required_args}" if required_args > 0} - args << options unless options.empty? - send :#{route_method}, *enclosing_collection_resources, *args + args << options if options && !options.empty? + #{route_method}(*enclosing_collection_resources, *args) end end_eval end diff --git a/lib/resources_controller/request_path_introspection.rb b/lib/resources_controller/request_path_introspection.rb index cc4842b..91a15ee 100644 --- a/lib/resources_controller/request_path_introspection.rb +++ b/lib/resources_controller/request_path_introspection.rb @@ -22,29 +22,39 @@ def nesting_request_path # returns an array of hashes like {:segment => 'forum', :singleton => false} def nesting_segments - @nesting_segments ||= segments_for_path_and_keys(nesting_request_path, param_keys) + @nesting_segments ||= begin + path = nesting_request_path + path.empty? || path == '/' ? [] : segments_for_path_and_keys(path, param_keys) + end end # returns an array of segments correspopnding to the namespace of the controller. # If your controller is at a non standard location wrt it's path, you can modify this array in a before filter # to help resources_controller do the right thing def namespace_segments - unless @namespace_segments - namespace = controller_path.delete_suffix(controller_name).delete_suffix('/') - @namespace_segments = if namespace.empty? + @namespace_segments ||= begin + path = controller_path + name = controller_name + if path == name [] else - rc_request_path.start_with?("/#{namespace}") ? namespace.split('/') : [] + namespace = path.delete_suffix(name).delete_suffix('/') + if namespace.empty? || !rc_request_path.start_with?("/#{namespace}") + [] + else + namespace.split('/') + end end end - @namespace_segments end def param_keys - params.each_key.filter_map do |k| + keys = [] + params.each_key do |k| k_str = k.to_s - k_str if k_str.end_with?('_id') + keys << k_str if k_str.end_with?('_id') end + keys end private @@ -77,16 +87,18 @@ def remove_namespace(path) end def segments_for_path_and_keys(path, keys) - key_segments = keys.map{|k| segment_for_key(k)} + key_segments = keys.map {|k| segment_for_key(k)} path_segments = path.delete_prefix('/').split('/') segments = [] - while path_segments.any? do - segment = path_segments.shift + i = 0 + while i < path_segments.length + segment = path_segments[i] if key_segments.include?(segment) segments << {:segment => segment, :singleton => false} - path_segments.shift # swallow following :id + i += 2 # swallow following :id else segments << {:segment => segment, :singleton => true} + i += 1 end end segments @@ -94,13 +106,15 @@ 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} - spec.segment - elsif spec = resource_specification_map.values.find{|s| s.key == key_str} - spec.segment - else - key_str.delete_suffix('_id').pluralize + if respond_to?(:specifications) && (spec = specifications.find {|s| s.respond_to?(:key) && s.key == key_str}) + return spec.segment end + + resource_specification_map.each_value do |spec| + return spec.segment if spec.key == key_str + end + + key_str.delete_suffix('_id').pluralize end end end diff --git a/lib/resources_controller/resource_methods.rb b/lib/resources_controller/resource_methods.rb index b7713a9..b6a8441 100644 --- a/lib/resources_controller/resource_methods.rb +++ b/lib/resources_controller/resource_methods.rb @@ -40,7 +40,10 @@ def resource_params if respond_to?(method_name, true) send(method_name) else - columns = resource_service.content_columns.map(&:name) - EXCLUDED_PARAM_COLUMNS + 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) end end diff --git a/lib/resources_controller/specification.rb b/lib/resources_controller/specification.rb index ae24654..5562eb5 100644 --- a/lib/resources_controller/specification.rb +++ b/lib/resources_controller/specification.rb @@ -17,7 +17,7 @@ class Specification class NoClassFoundError < NameError end - attr_reader :name, :source, :klass, :key, :name_prefix, :segment, :find, :ivar_name, :collection_ivar_name + attr_reader :name, :source, :klass, :key, :name_prefix, :segment, :find, :ivar_name attr_accessor :as # factory for Specification and SingletonSpecification @@ -51,15 +51,25 @@ def initialize(spec_name, options = {}, &block) options.assert_valid_keys(:class, :source, :key, :find, :name_prefix, :segment, :as) @name = spec_name.to_s @find = block || options.delete(:find) - plural = name.pluralize - @segment = (options[:segment] && options[:segment].to_s) || plural - @source = (options[:source] && options[:source].to_s) || plural - @name_prefix = options[:name_prefix] || (options[:name_prefix] == false ? +'' : "#{name}_") + @segment = options[:segment] ? options[:segment].to_s : nil + @source = options[:source] ? options[:source].to_s : nil + unless @segment && @source + plural = @name.pluralize + @segment ||= plural + @source ||= plural + @collection_ivar_name = :"@#{plural}" + end + @name_prefix = options[:name_prefix] || (options[:name_prefix] == false ? +'' : "#{@name}_") @klass = options[:class] || infer_class - @key = (options[:key] && options[:key].to_s) || name.foreign_key + @key = singleton? ? false : (options[:key] ? options[:key].to_s : @name.foreign_key) @as = options[:as] - @ivar_name = :"@#{name}" - @collection_ivar_name = :"@#{plural}" + @ivar_name = :"@#{@name}" + end + + # returns the plural collection instance variable symbol (e.g. :@users), + # computed lazily when :segment and :source are both supplied + def collection_ivar_name + @collection_ivar_name ||= :"@#{name.pluralize}" end # returns false diff --git a/lib/resources_controller/version.rb b/lib/resources_controller/version.rb index 5522cc2..a59d359 100644 --- a/lib/resources_controller/version.rb +++ b/lib/resources_controller/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module ResourcesController - VERSION = "5.0.3" + VERSION = "5.1.0" end diff --git a/spec/lib/action_view_helper_spec.rb b/spec/lib/action_view_helper_spec.rb index 476dcc6..dd07629 100644 --- a/spec/lib/action_view_helper_spec.rb +++ b/spec/lib/action_view_helper_spec.rb @@ -115,4 +115,22 @@ def self.it_should_forward_to_controller(msg, *args) expect(@view).to receive(:form_for).with(@resource, {:as => 'forum', :html => {:method => :put}, :url => '/forums/1'}) @view.form_for_resource{} end + + it 'should not call new_record? when :url and :html[:method] are both provided' do + custom_resource = double('CustomResource') + expect(custom_resource).not_to receive(:new_record?) + expect(@view).to receive(:form_for).with(custom_resource, {:as => 'forum', :html => {:method => :patch}, :url => '/custom'}) + @view.form_for_resource(custom_resource, :url => '/custom', :html => {:method => :patch}) {} + end + + it 'should forward keyword arguments and blocks when delegating named route helpers' do + forwarded = nil + allow(@controller).to receive(:edit_resource_path) do |*args, **kwargs, &block| + forwarded = [args, kwargs, block&.call] + '/forums/1/edit?tab=settings' + end + + expect(@view.edit_resource_path(tab: 'settings') { :ok }).to eq('/forums/1/edit?tab=settings') + expect(forwarded).to eq([[], {:tab => 'settings'}, :ok]) + end end diff --git a/spec/lib/named_route_helper_spec.rb b/spec/lib/named_route_helper_spec.rb index 9bce4e4..9d3f80d 100644 --- a/spec/lib/named_route_helper_spec.rb +++ b/spec/lib/named_route_helper_spec.rb @@ -19,4 +19,69 @@ it "should expose named route helpers through #method" do expect(@controller.method(:resource_path)).to be_a(Method) end + + it "should check route availability without querying named_routes" do + fresh_class = Class.new(ApplicationController) do + resources_controller_for :forums + end + fresh_controller = fresh_class.new + expect(Rails.application.routes.named_routes).not_to receive(:get) + expect(fresh_controller.respond_to?(:resource_path)).to eq(true) + expect(fresh_controller.respond_to?(:resource_nonexistent_path)).to eq(false) + end + + it "should forward keyword arguments through newly defined named route helpers and super" do + fresh_class = Class.new(ApplicationController) do + resources_controller_for :forums + + def method_missing(method, *args, **kwargs, &block) + return [method, args, kwargs, block&.call] if method == :custom_missing_with_forward + + super + end + end + fresh_controller = fresh_class.new + fresh_controller.request = ActionDispatch::TestRequest.create + fresh_controller.resource = Forum.new(:id => 2) + + expect(fresh_controller.resource_path(foo: 'bar')).to eq('/forums/2?foo=bar') + expect(fresh_controller.custom_missing_with_forward(1, key: 'val') { :yielded }).to eq( + [:custom_missing_with_forward, [1], {:key => 'val'}, :yielded] + ) + end + + it "should handle nil name_prefix in generated named route helpers" do + fresh_class = Class.new(ApplicationController) do + resources_controller_for :forums + + def name_prefix + nil + end + end + fresh_controller = fresh_class.new + fresh_controller.request = ActionDispatch::TestRequest.create + fresh_controller.resource = Forum.new(:id => 2) + + expect(fresh_controller.resource_path).to eq('/forums/2') + end + + it "should merge default_url_options into generated route helpers" do + @controller.request = ActionDispatch::TestRequest.create + @controller.resource = Forum.new(:id => 2) + allow(@controller).to receive(:default_url_options).and_return(:locale => 'en') + + expect(@controller.resources_path).to eq('/forums?locale=en') + expect(@controller.resource_path(:foo => 'bar')).to eq('/forums/2?foo=bar&locale=en') + end + + it "should merge default_url_options into enclosing route helpers" do + tag_controller = TagsController.new + tag_controller.request = ActionDispatch::TestRequest.create + forum = Forum.new(:id => 1) + tag_controller.send(:add_enclosing_resource, forum, :name => 'forum') + allow(tag_controller).to receive(:default_url_options).and_return(:locale => 'en') + + expect(tag_controller.enclosing_resource_path).to eq('/forums/1?locale=en') + expect(tag_controller.enclosing_resource_path(9, :foo => 'bar')).to eq('/forums/9?foo=bar&locale=en') + end end diff --git a/spec/lib/request_path_introspection_spec.rb b/spec/lib/request_path_introspection_spec.rb index 5cabb1c..ab9c159 100644 --- a/spec/lib/request_path_introspection_spec.rb +++ b/spec/lib/request_path_introspection_spec.rb @@ -149,7 +149,20 @@ def request_path(*) expect(@controller.send(:namespace_segments)).to eq(['some', 'name', 'space']) end + it "#namespace_segments should return a mutable empty array when controller_path matches controller_name" do + segments = @controller.send(:namespace_segments) + expect(segments).to eq([]) + segments << 'custom' + expect(@controller.send(:namespace_segments)).to eq(['custom']) + end + describe "#nesting_segments" do + it "should return [] without scanning params when nesting_request_path is empty" do + @controller.params[:user_id] = '1' + expect(@controller).not_to receive(:param_keys) + expect(@controller.send(:nesting_segments)).to eq([]) + end + describe "when params include :user_id" do before do @controller.params[:user_id] = '1' diff --git a/spec/lib/resource_methods_spec.rb b/spec/lib/resource_methods_spec.rb index 3ba6fa1..16e6b42 100644 --- a/spec/lib/resource_methods_spec.rb +++ b/spec/lib/resource_methods_spec.rb @@ -77,6 +77,23 @@ class MyController < ActionController::Base expect(@controller.send(:destroy_resource, "42")).to eq(user) end end + + describe "#resource_params fallback" do + it "permits content columns excluding timestamps" do + columns = [ + double(:name => 'login'), + double(:name => 'created_at'), + double(:name => 'updated_at') + ] + allow(User).to receive(:content_columns).and_return(columns) + allow(@controller).to receive(:params).and_return( + ActionController::Parameters.new(:user => { :login => 'alice', :created_at => '2026-01-01', :updated_at => '2026-01-02' }) + ) + permitted = @controller.send(:resource_params) + expect(permitted.permitted?).to be true + expect(permitted.to_h).to eq('login' => 'alice') + end + end end class MySingletonController < ActionController::Base diff --git a/spec/lib/resources_controller_spec.rb b/spec/lib/resources_controller_spec.rb index 891be3c..5d4477e 100644 --- a/spec/lib/resources_controller_spec.rb +++ b/spec/lib/resources_controller_spec.rb @@ -84,6 +84,97 @@ end end +describe "ResourcesController::Specification" do + it "should keep singleton key false and compute collection_ivar_name lazily" do + spec = ResourcesController::Specification.new(:account, :singleton => true, :class => User) + expect(spec.key).to eq(false) + expect(spec.instance_variable_get(:@collection_ivar_name)).to be_nil + expect(spec.collection_ivar_name).to eq(:@accounts) + end + + it "should treat false for :segment, :source, and :key as absent" do + spec = ResourcesController::Specification.new(:forum, :segment => false, :source => false, :key => false) + expect(spec.segment).to eq('forums') + expect(spec.source).to eq('forums') + expect(spec.klass).to eq(Forum) + expect(spec.key).to eq('forum_id') + end +end + +describe "ResourcesController#add_enclosing_resource hook" do + it "should invoke add_enclosing_resource overrides during load_enclosing_resources" do + forum = Forum.create! + klass = Class.new(ApplicationController) do + resources_controller_for :posts, :in => :forum + attr_reader :added_enclosing + + private + + def add_enclosing_resource(resource, options = {}) + (@added_enclosing ||= []) << [resource, options[:name]] + super + end + end + + controller = klass.new + req = ActionDispatch::TestRequest.create + req.path = "/forums/#{forum.id}/posts" + allow(controller).to receive(:request).and_return(req) + allow(controller).to receive(:params).and_return(ActionController::Parameters.new(:forum_id => forum.id.to_s)) + + controller.send(:load_enclosing_resources) + expect(controller.added_enclosing).to eq([[forum, 'forum']]) + expect(controller.instance_variable_get(:@forum)).to eq(forum) + end + + it "should support :as on a mapped wildcard specification" do + account = User.create! + klass = Class.new(ApplicationController) do + resources_controller_for :tags, :in => '?taggable' + end + + controller = klass.new + controller.instance_variable_set(:@current_user, account) + req = ActionDispatch::TestRequest.create + req.path = '/account/tags' + allow(controller).to receive(:request).and_return(req) + allow(controller).to receive(:params).and_return(ActionController::Parameters.new) + + controller.send(:load_enclosing_resources) + expect(controller.instance_variable_get(:@account)).to eq(account) + expect(controller.instance_variable_get(:@taggable)).to eq(account) + end + + it "should raise ResourceMismatch when nesting segments are exhausted for a specification" do + klass = Class.new(ApplicationController) do + resources_controller_for :posts, :in => :forum + end + + controller = klass.new + req = ActionDispatch::TestRequest.create + req.path = '/posts' + allow(controller).to receive(:request).and_return(req) + allow(controller).to receive(:params).and_return(ActionController::Parameters.new) + + expect { controller.send(:load_enclosing_resources) }.to raise_error(ResourcesController::ResourceMismatch) + end + + it "should raise ResourceMismatch when wildcard lookup exhausts nesting segments" do + user = User.create! + klass = Class.new(ApplicationController) do + resources_controller_for :tags, :in => [:user, '?taggable', :forum] + end + + controller = klass.new + req = ActionDispatch::TestRequest.create + req.path = "/users/#{user.id}/tags" + allow(controller).to receive(:request).and_return(req) + allow(controller).to receive(:params).and_return(ActionController::Parameters.new(:user_id => user.id.to_s)) + + expect { controller.send(:load_enclosing_resources) }.to raise_error(ResourcesController::ResourceMismatch) + end +end + describe "deprecated methods" do before do @controller = ForumsController.new