diff --git a/CHANGELOG b/CHANGELOG index edcef89..fc53ddf 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -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: diff --git a/lib/resources_controller.rb b/lib/resources_controller.rb index 50eaf0d..03da305 100644 --- a/lib/resources_controller.rb +++ b/lib/resources_controller.rb @@ -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 @@ -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 @@ -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 @@ -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..]) @@ -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] @@ -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 @@ -811,16 +830,21 @@ 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 @@ -828,8 +852,10 @@ def find(...) # 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 diff --git a/lib/resources_controller/helper.rb b/lib/resources_controller/helper.rb index d6d6df2..84f6dd9 100644 --- a/lib/resources_controller/helper.rb +++ b/lib/resources_controller/helper.rb @@ -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 diff --git a/lib/resources_controller/named_route_helper.rb b/lib/resources_controller/named_route_helper.rb index 9e073d4..e08cf7c 100644 --- a/lib/resources_controller/named_route_helper.rb +++ b/lib/resources_controller/named_route_helper.rb @@ -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 @@ -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 @@ -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 @@ -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 diff --git a/lib/resources_controller/request_path_introspection.rb b/lib/resources_controller/request_path_introspection.rb index 91a15ee..ade111c 100644 --- a/lib/resources_controller/request_path_introspection.rb +++ b/lib/resources_controller/request_path_introspection.rb @@ -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 @@ -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 diff --git a/lib/resources_controller/resource_methods.rb b/lib/resources_controller/resource_methods.rb index b6a8441..02a17ee 100644 --- a/lib/resources_controller/resource_methods.rb +++ b/lib/resources_controller/resource_methods.rb @@ -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 @@ -36,7 +44,9 @@ 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 @@ -44,7 +54,7 @@ def resource_params 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 diff --git a/lib/resources_controller/specification.rb b/lib/resources_controller/specification.rb index 5562eb5..33aaea8 100644 --- a/lib/resources_controller/specification.rb +++ b/lib/resources_controller/specification.rb @@ -17,6 +17,9 @@ class Specification class NoClassFoundError < NameError end + VALID_OPTION_KEYS = %i[class source key find name_prefix segment as].freeze + SIMPLE_NAME_PATTERN = /\A[a-z0-9_]+\z/ + attr_reader :name, :source, :klass, :key, :name_prefix, :segment, :find, :ivar_name attr_accessor :as @@ -48,28 +51,40 @@ def self.new(name, options = {}, &block) # # Passing a block is the same as passing :find => Proc def initialize(spec_name, options = {}, &block) - options.assert_valid_keys(:class, :source, :key, :find, :name_prefix, :segment, :as) + validate_option_keys(options) @name = spec_name.to_s @find = block || options.delete(:find) @segment = options[:segment] ? options[:segment].to_s : nil @source = options[:source] ? options[:source].to_s : nil unless @segment && @source plural = @name.pluralize + @plural_name = plural.dup.freeze @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 = singleton? ? false : (options[:key] ? options[:key].to_s : @name.foreign_key) + @key = singleton? ? false : (options[:key] ? options[:key].to_s : default_foreign_key) @as = options[:as] @ivar_name = :"@#{@name}" end + # returns the frozen plural name string (e.g. 'users'), + # computed lazily when :segment and :source are both supplied + def plural_name + @plural_name ||= @name.pluralize.freeze + 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}" + @collection_ivar_name ||= :"@#{plural_name}" + end + + # returns the strong-parameters method symbol (e.g. :user_params), computed lazily + def params_method_name + @params_method_name ||= :"#{@name}_params" end # returns false @@ -94,6 +109,20 @@ def find_resource(controller) end private + def validate_option_keys(options) + return if options.empty? + + options.each_key do |k| + unless VALID_OPTION_KEYS.include?(k) + raise ArgumentError, "Unknown key: #{k.inspect}. Valid keys are: #{VALID_OPTION_KEYS.map(&:inspect).join(', ')}" + end + end + end + + def default_foreign_key + SIMPLE_NAME_PATTERN.match?(@name) ? "#{@name}_id" : @name.foreign_key + end + def infer_class ((source && source.classify) || name.camelize).constantize rescue NameError => e @@ -109,10 +138,16 @@ class SingletonSpecification < Specification # * :source: a singular string or symbol (e.g. :blog). This is used to find the class or association name # * :segment: (e.g. 'blog') the segment name in the route that is matched def initialize(spec_name, options = {}, &block) - options[:segment] ||= spec_name.to_s - options[:source] ||= spec_name.to_s + name_str = spec_name.to_s + options[:segment] ||= name_str + options[:source] ||= name_str - super(spec_name, options, &block) + super(name_str, options, &block) + end + + # returns the association builder method symbol (e.g. :build_info), computed lazily + def build_method_name + @build_method_name ||= :"build_#{@source}" end # returns true diff --git a/lib/resources_controller/version.rb b/lib/resources_controller/version.rb index a59d359..2b8a99c 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.1.0" + VERSION = "5.1.1" end diff --git a/spec/lib/action_view_helper_spec.rb b/spec/lib/action_view_helper_spec.rb index dd07629..c347faa 100644 --- a/spec/lib/action_view_helper_spec.rb +++ b/spec/lib/action_view_helper_spec.rb @@ -69,6 +69,12 @@ def self.it_should_forward_to_controller(msg, *args) expect(@view).to receive(:form_for).with(@resource, {:as => 'forum', :html => {:method => :post}, :url => '/forums'}) @view.form_for_resource{} end + + it 'should preserve falsey :url_options entries in form options' do + expect(@view).to receive(:resources_path).with(no_args).and_return('/forums') + expect(@view).to receive(:form_for).with(@resource, {:as => 'forum', :html => {:method => :post}, :url => '/forums', :url_options => nil}) + @view.form_for_resource(:url_options => nil) {} + end end describe "Helper#form_for_resource (when resource is new record) and resource is singleton" do diff --git a/spec/lib/include_actions_spec.rb b/spec/lib/include_actions_spec.rb index e3d9552..1ac296f 100644 --- a/spec/lib/include_actions_spec.rb +++ b/spec/lib/include_actions_spec.rb @@ -19,6 +19,10 @@ class ExceptFooBarController < ActionController::Base include_actions Actions, :except => [:foo, :bar] end + class StringOptionsController < ActionController::Base + include_actions Actions, :only => ['bar', :faz] + end + describe "Include actions use case" do it "ActionController should have actions from actions module" do expect(ActionsController.action_methods).to eq(['foo', 'bar', 'faz'].to_set) @@ -31,5 +35,10 @@ class ExceptFooBarController < ActionController::Base it "ExceptFooBarController should not have :foo, :bar from actions module" do expect(ExceptFooBarController.action_methods).to eq(['faz'].to_set) end + + it "StringOptionsController should handle string and symbol action names" do + expect(StringOptionsController.action_methods).to eq(['bar', 'faz'].to_set) + expect(Actions.action_methods_to_remove(:only => :foo)).to all(be_a(String)) + end end end diff --git a/spec/lib/named_route_helper_spec.rb b/spec/lib/named_route_helper_spec.rb index 9d3f80d..789ac8c 100644 --- a/spec/lib/named_route_helper_spec.rb +++ b/spec/lib/named_route_helper_spec.rb @@ -84,4 +84,119 @@ def name_prefix 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 + + it "should dispatch cached prefixes directly across multiple nestings without method_missing" do + fresh_class = Class.new(ApplicationController) do + resources_controller_for :tags + end + sub_class = Class.new(fresh_class) + forum = Forum.new(:id => 1) + post = Post.new(:id => 2) + tag = Tag.new(:id => 3) + + c1 = fresh_class.new + c1.request = ActionDispatch::TestRequest.create + c1.send(:add_enclosing_resource, forum, :name => 'forum') + c1.resource = tag + expect(c1.resource_path).to eq('/forums/1/tags/3') + expect(c1.enclosing_resource_path(99)).to eq('/forums/99') + + c2 = fresh_class.new + c2.request = ActionDispatch::TestRequest.create + c2.send(:add_enclosing_resource, forum, :name => 'forum') + c2.send(:add_enclosing_resource, post, :name => 'post') + c2.resource = tag + expect(c2.resource_path).to eq('/forums/1/posts/2/tags/3') + expect(c2.enclosing_resource_path).to eq('/forums/1/posts/2') + + c_sub = sub_class.new + c_sub.request = ActionDispatch::TestRequest.create + c_sub.send(:add_enclosing_resource, forum, :name => 'forum') + c_sub.resource = tag + + # After warmup, helpers dispatch to already-defined prefixed methods without hitting method_missing + expect(c1).not_to receive(:method_missing) + expect(c2).not_to receive(:method_missing) + expect(c_sub).not_to receive(:method_missing) + expect(c1.resource_path(tag)).to eq('/forums/1/tags/3') + expect(c2.resource_path(99)).to eq('/forums/1/posts/2/tags/99') + expect(c_sub.resource_path(tag)).to eq('/forums/1/tags/3') + + # Parent adding a new prefix after subclass registered its own prefix still works via fallback + user = User.new(:id => 4, :login => 'alice') + address = Address.new(:id => 5) + c_sub_addr = sub_class.new + c_sub_addr.request = ActionDispatch::TestRequest.create + c_sub_addr.send(:add_enclosing_resource, user, :name => 'user') + c_sub_addr.send(:add_enclosing_resource, address, :name => 'address') + c_sub_addr.resource = tag + expect(c_sub_addr.resource_path).to eq('/users/alice/addresses/5/tags/3') + + c_parent_post = fresh_class.new + c_parent_post.request = ActionDispatch::TestRequest.create + c_parent_post.send(:add_enclosing_resource, forum, :name => 'forum') + c_parent_post.send(:add_enclosing_resource, post, :name => 'post') + c_parent_post.resource = tag + expect(c_parent_post.resource_path).to eq('/forums/1/posts/2/tags/3') + end + + it "should preserve eql? semantics when filtering enclosing_collection_resources" do + fresh_class = Class.new(ApplicationController) do + resources_controller_for :tags + end + eq_only = Class.new do + def initialize(param) + @param = param + end + + def to_param + @param + end + + def ==(_other) + true + end + + def eql?(other) + equal?(other) + end + end + + first = eq_only.new('1') + second = eq_only.new('2') + ctrl = fresh_class.new + ctrl.request = ActionDispatch::TestRequest.create + ctrl.send(:add_enclosing_resource, first, :name => 'forum') + ctrl.send(:add_enclosing_resource, second, :name => 'post') + + # `enclosing_resources_path` (forum_posts_path) has required_args == 1; + # passing 1 arg filters out only `second` (eql?), leaving `first` intact. + expect(ctrl.enclosing_resources_path(99)).to eq('/forums/1/posts.99') + end + + it "should reuse class-level plural_route_name and still honor route_name overrides" do + expect(@controller.send(:resources_route_name)).to equal(ForumsController.plural_route_name) + expect(@controller.send(:resources_route_name)).to eq('forums') + + class_override = Class.new(ApplicationController) do + resources_controller_for :forums + self.route_name = 'board' + end + expect(class_override.new.send(:resources_route_name)).to eq('boards') + + mutated_class = Class.new(ApplicationController) do + resources_controller_for :forums + end + mutated_class.route_name.replace('board') + expect(mutated_class.new.send(:resources_route_name)).to eq('boards') + + instance_override = Class.new(ApplicationController) do + resources_controller_for :forums + + def route_name + 'topic' + end + end + expect(instance_override.new.send(:resources_route_name)).to eq('topics') + end end diff --git a/spec/lib/request_path_introspection_spec.rb b/spec/lib/request_path_introspection_spec.rb index ab9c159..2503d39 100644 --- a/spec/lib/request_path_introspection_spec.rb +++ b/spec/lib/request_path_introspection_spec.rb @@ -109,6 +109,50 @@ class User < ActiveRecord::Base; end allow(@controller).to receive(:rc_request_path).and_return('/v1X0/2') expect(@controller.send(:nesting_request_path)).to eq('/v1X0/2') end + + it "should handle multibyte UTF-8 paths and consecutive matching segments" do + allow(@controller).to receive(:rc_request_path).and_return('/café/forums/2') + expect(@controller.send(:nesting_request_path)).to eq('/café') + + @controller.instance_variable_set(:@nesting_request_path, nil) + allow(@controller).to receive(:rc_request_path).and_return('/日本語/forums') + expect(@controller.send(:nesting_request_path)).to eq('/日本語') + + @controller.instance_variable_set(:@nesting_request_path, nil) + allow(@controller).to receive(:rc_request_path).and_return('/ééééé/forums') + expect(@controller.send(:nesting_request_path)).to eq('/ééééé') + + @controller.instance_variable_set(:@nesting_request_path, nil) + allow(@controller).to receive(:rc_request_path).and_return('/日本語/forums/forums') + expect(@controller.send(:nesting_request_path)).to eq('/日本語') + + @controller.instance_variable_set(:@nesting_request_path, nil) + allow(@controller).to receive(:rc_request_path).and_return('/forums/forums/forums') + expect(@controller.send(:nesting_request_path)).to eq('/forums') + + @controller.instance_variable_set(:@nesting_request_path, nil) + allow(@controller).to receive(:resource_specification).and_return(ResourcesController::Specification.new(:forum, :class => RequestPathIntrospectionSpec::Forum, :segment => 'a/a')) + allow(@controller).to receive(:rc_request_path).and_return('/日本語/a/a/a/a') + expect(@controller.send(:nesting_request_path)).to eq('/日本語') + + @controller.instance_variable_set(:@nesting_request_path, nil) + allow(@controller).to receive(:resource_specification).and_return(ResourcesController::Specification.new(:forum, :class => RequestPathIntrospectionSpec::Forum, :singleton => true, :segment => 'a/a')) + allow(@controller).to receive(:rc_request_path).and_return('/x/a/a/a/a') + expect(@controller.send(:nesting_request_path)).to eq('/x/a') + end + + it "should return a fresh mutable string from remove_current_segment on no-match and byte-0 match" do + unmatched = +'/other/1' + res_unmatched = @controller.send(:remove_current_segment, unmatched) + expect(res_unmatched).to eq('/other/1') + expect(res_unmatched).not_to equal(unmatched) + expect(res_unmatched.frozen?).to eq(false) + + matched = +'/forums/1' + res_matched = @controller.send(:remove_current_segment, matched) + expect(res_matched).to eq('') + expect(res_matched.frozen?).to eq(false) + end it "should remove any controller namespace" do allow(@controller).to receive(:controller_path).and_return('some/name/space/forums') @@ -214,6 +258,33 @@ def request_path(*) expect(@controller.send(:segment_for_key, 'user_id')).to eq('users') end end + + describe "when a subclass overrides a mapped enclosing resource key" do + before do + @klass.map_enclosing_resource :user, :segment => 'peeps', :key => 'old_user_id', :class => RequestPathIntrospectionSpec::User + @subklass = Class.new(@klass) do + map_enclosing_resource :user, :segment => 'peeps', :key => 'new_user_id', :class => RequestPathIntrospectionSpec::User + end + @subcontroller = @subklass.new + end + + it "should stay in sync with overridden, reassigned, mutated, and duck-typed mappings" do + expect(@subcontroller.send(:segment_for_key, 'new_user_id')).to eq('peeps') + expect(@subcontroller.send(:segment_for_key, 'old_user_id')).to eq('old_users') + expect(@controller.send(:segment_for_key, 'old_user_id')).to eq('peeps') + + duck_spec = Struct.new(:key, :segment).new('duck_id', 'ducks_custom') + @subklass.resource_specification_map = { 'ducks_custom' => duck_spec } + expect(@subcontroller.send(:segment_for_key, 'duck_id')).to eq('ducks_custom') + + duck_spec2 = Struct.new(:key, :segment).new('other_id', 'others_custom') + @subklass.resource_specification_map['others_custom'] = duck_spec2 + expect(@subcontroller.send(:segment_for_key, 'other_id')).to eq('others_custom') + + allow(@subcontroller).to receive(:specifications).and_return([Struct.new(:key, :segment).new('spec_id', 'spec_seg')]) + expect(@subcontroller.send(:segment_for_key, 'spec_id')).to eq('spec_seg') + end + end end end end diff --git a/spec/lib/resource_methods_spec.rb b/spec/lib/resource_methods_spec.rb index 16e6b42..e50575a 100644 --- a/spec/lib/resource_methods_spec.rb +++ b/spec/lib/resource_methods_spec.rb @@ -47,6 +47,16 @@ class MyController < ActionController::Base expect(user).to receive(:destroy).and_return(user) expect(@controller.send(:destroy_resource, "42")).to eq(user) end + + it "#find_resource(false) and #destroy_resource(false) should fall back to params[:id]" do + allow(@controller).to receive(:params).and_return(ActionController::Parameters.new(:id => "99")) + expect(User).to receive(:find).with("99").and_return(user = double) + expect(@controller.send(:find_resource, false)).to eq(user) + + expect(User).to receive(:find).with("99").and_return(user2 = double) + expect(user2).to receive(:destroy).and_return(user2) + expect(@controller.send(:destroy_resource, false)).to eq(user2) + end end describe "when an enclosing resource is added (a forum)" do @@ -93,6 +103,45 @@ class MyController < ActionController::Base expect(permitted.permitted?).to be true expect(permitted.to_h).to eq('login' => 'alice') end + + it "honors an overridden resource_name when dispatching to *_params" do + custom_class = Class.new(ActionController::Base) do + resources_controller_for :users + + def resource_name + 'member' + end + + private + + def member_params + {:login => 'from_member_params'} + end + end + + expect(custom_class.new.send(:resource_params)).to eq(:login => 'from_member_params') + end + end + + describe "#new_resource params lookup" do + it "does not look up the same param key twice when resource_name matches model singular" do + params = ActionController::Parameters.new + expect(params).to receive(:[]).with('user').once.and_return(nil) + allow(@controller).to receive(:params).and_return(params) + expect(User).to receive(:new).with({}) + @controller.send(:new_resource) + end + + it "falls back to params[resource_name] when resource_name differs from model singular" do + custom_class = Class.new(ActionController::Base) do + resources_controller_for :member, :class => User + end + controller = custom_class.new + params = ActionController::Parameters.new(:member => {:login => 'bob'}) + allow(controller).to receive(:params).and_return(params) + expect(User).to receive(:new).with(params[:member]) + controller.send(:new_resource) + end end end diff --git a/spec/lib/resource_service_forwarding_spec.rb b/spec/lib/resource_service_forwarding_spec.rb index 383e8f9..4368785 100644 --- a/spec/lib/resource_service_forwarding_spec.rb +++ b/spec/lib/resource_service_forwarding_spec.rb @@ -21,6 +21,10 @@ def new(attributes, validate:) def build(attributes, validate:) [:build, attributes, validate, yield(:build)] end + + def destroy(id, filters = nil, force: false) + [:destroy, id, filters, force] + end end Controller = Struct.new(:resource_class, :enclosing_resource, :resource_specification) @@ -58,6 +62,26 @@ def build_item(attributes, validate:) expect(result).to eq([:find, 42, filters, 2, 'block find']) end + it "calls service.find directly without falling back to method_missing" do + expect(proxy).not_to receive(:method_missing) + + result = proxy.find(42, filters, limit: 2) { |operation| "block #{operation}" } + expect(result).to eq([:find, 42, filters, 2, 'block find']) + end + + it "invokes private #find on the underlying service and respects #controller overrides" do + private_find_service = Class.new do + private + def find(id); [:private_find, id]; end + end.new + alt_controller = Controller.new(private_find_service, nil, specification) + overriding_proxy = Class.new(ResourcesController::ResourceService) do + define_method(:controller) { alt_controller } + end.new(controller) + + expect(overriding_proxy.find(7)).to eq([:private_find, 7]) + end + context "with a custom finder block" do let(:specification) do ResourcesController::Specification.new(:item, :class => Service) { [:custom, resource_class] } @@ -96,6 +120,41 @@ def build_item(attributes, validate:) expect(result).to eq([:build, attributes, false, 'block build']) end + + it "forwards positional and keyword arguments through destroy to both find and service.destroy without forwarding blocks" do + destroyed = nil + find_block_given = nil + destroy_block_given = nil + allow(service).to receive(:find).with(42, filters, limit: 2) do |*_a, **_kw, &blk| + find_block_given = !blk.nil? + :found_record + end + allow(service).to receive(:destroy).with(42, filters, limit: 2) do |*a, **kw, &blk| + destroy_block_given = !blk.nil? + destroyed = [a, kw] + end + + expect(proxy.destroy(42, filters, limit: 2) { raise 'block should not be forwarded' }).to eq(:found_record) + expect(destroyed).to eq([[42, filters], {:limit => 2}]) + expect(find_block_given).to eq(false) + expect(destroy_block_given).to eq(false) + end + + it "respects subclass overrides of enclosing_resource and resource_specification" do + custom_proxy_class = Class.new(ResourcesController::ResourceService) do + def enclosing_resource + nil + end + + def resource_specification + ResourcesController::Specification.new(:item, :class => Service) { :overridden_custom_find } + end + end + + custom_proxy = custom_proxy_class.new(controller) + expect(custom_proxy.find(42)).to eq(:overridden_custom_find) + expect(custom_proxy.new(attributes, validate: false) { |op| "block #{op}" }).to eq([:new, attributes, false, 'block new']) + end end context "with a singleton resource service" do @@ -116,6 +175,22 @@ def build_item(attributes, validate:) expect(result).to eq([:build_item, attributes, false, 'block build_item']) end + + it "respects subclass overrides of enclosing_resource and resource_specification" do + custom_singleton_class = Class.new(ResourcesController::SingletonResourceService) do + def enclosing_resource + nil + end + + def resource_specification + ResourcesController::Specification.new(:item, :singleton => true, :class => Service) { :overridden_singleton_find } + end + end + + custom_proxy = custom_singleton_class.new(controller) + expect(custom_proxy.find).to eq(:overridden_singleton_find) + expect(custom_proxy.new(attributes, validate: false) { |op| "block #{op}" }).to eq([:new, attributes, false, 'block new']) + end end end end diff --git a/spec/lib/resources_controller_spec.rb b/spec/lib/resources_controller_spec.rb index 5d4477e..c4571f8 100644 --- a/spec/lib/resources_controller_spec.rb +++ b/spec/lib/resources_controller_spec.rb @@ -82,6 +82,18 @@ expect(@controller.instance_variable_get(:@name_prefix)).to eq('') expect(@controller.name_prefix).to eq('') end + + it "should handle a frozen @name_prefix safely and not mutate retained earlier references" do + @controller.send :update_name_prefix, 'forum_' + earlier = @controller.name_prefix + @controller.send :update_name_prefix, 'user_' + expect(earlier).to eq('forum_') + expect(@controller.name_prefix).to eq('forum_user_') + + @controller.instance_variable_set(:@name_prefix, 'forum_'.freeze) + @controller.send :update_name_prefix, 'user_' + expect(@controller.name_prefix).to eq('forum_user_') + end end describe "ResourcesController::Specification" do @@ -90,6 +102,8 @@ 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) + expect(spec.plural_name).to eq('accounts') + expect(spec.build_method_name).to eq(:build_account) end it "should treat false for :segment, :source, and :key as absent" do @@ -99,6 +113,29 @@ expect(spec.klass).to eq(Forum) expect(spec.key).to eq('forum_id') end + + it "should validate option keys and expose lazy params_method_name" do + expect { + ResourcesController::Specification.new(:forum, :bogus => true) + }.to raise_error(ArgumentError, /Unknown key: :bogus/) + + spec = ResourcesController::Specification.new('Admin::Forum', :class => Forum) + expect(spec.key).to eq('forum_id') + expect(spec.params_method_name).to eq(:"Admin::Forum_params") + end + + it "should return an independent mutable string from controller#resources_name without corrupting Specification" do + spec = ForumsController.resource_specification + c1 = ForumsController.new + c2 = ForumsController.new + expect(c1.resources_name).to eq('forums') + + c1.resources_name << '_mutated' + expect(spec.plural_name).to eq('forums') + expect(spec.segment).to eq('forums') + expect(spec.source).to eq('forums') + expect(c2.resources_name).to eq('forums') + end end describe "ResourcesController#add_enclosing_resource hook" do @@ -127,6 +164,53 @@ def add_enclosing_resource(resource, options = {}) expect(controller.instance_variable_get(:@forum)).to eq(forum) end + it "should respect rewritten :name and :as in add_enclosing_resource overrides" do + forum = Forum.create! + klass = Class.new(ApplicationController) do + resources_controller_for :posts, :in => :forum + + private + + def add_enclosing_resource(resource, options = {}) + super(resource, options.merge(:name => 'board', :as => 'parent_board')) + 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.instance_variable_get(:@board)).to eq(forum) + expect(controller.instance_variable_get(:@parent_board)).to eq(forum) + expect(controller.instance_variable_defined?(:@forum)).to eq(false) + end + + it "should load enclosing resources from duck-typed mapped specifications without ivar_name" do + forum = Forum.create! + duck_spec = Struct.new(:segment, :key, :name, :name_prefix, :as) do + def singleton?; false; end + def find_from(_controller); Forum.first; end + end.new('boards', 'board_id', 'board', 'board_', 'parent_board') + + klass = Class.new(ApplicationController) do + resources_controller_for :posts + end + klass.resource_specification_map = { 'boards' => duck_spec } + + controller = klass.new + req = ActionDispatch::TestRequest.create + req.path = "/boards/#{forum.id}/posts" + allow(controller).to receive(:request).and_return(req) + allow(controller).to receive(:params).and_return(ActionController::Parameters.new(:board_id => forum.id.to_s)) + + controller.send(:load_enclosing_resources) + expect(controller.instance_variable_get(:@board)).to eq(forum) + expect(controller.instance_variable_get(:@parent_board)).to eq(forum) + end + it "should support :as on a mapped wildcard specification" do account = User.create! klass = Class.new(ApplicationController) do