diff --git a/CHANGELOG.md b/CHANGELOG.md index 33ead6e..c32e124 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ This project adheres to [Semantic Versioning](http://semver.org/) and [Keep a Ch ### Changes - Optimize named `*_rfc6570` helpers by removing unnecessary indirection +- Optimize `#rfc6570_routes` and `#rfc6570_route` helpers ### Fixes diff --git a/lib/rails/rfc6570.rb b/lib/rails/rfc6570.rb index 8606f65..cf5bbeb 100644 --- a/lib/rails/rfc6570.rb +++ b/lib/rails/rfc6570.rb @@ -88,16 +88,11 @@ def to_rfc6570(**opts) module Helper def rfc6570_routes(**opts) - routes = {} - Rails.application.routes.named_routes.names.each do |key| - routes[key] = rfc6570_route(key, **opts) - end - - routes + _routes.named_routes.to_rfc6570(**opts, ctx: self) end def rfc6570_route(name, **opts) - route = Rails.application.routes.named_routes[name] + route = _routes.named_routes[name] raise KeyError.new "No named routed for `#{name}'." unless route route.to_rfc6570(**opts, ctx: self) @@ -120,7 +115,7 @@ def rfc6570_params_for(defs) def params_for(controller, action) ctr = "#{controller.camelize}Controller".constantize - ctr.rfc6570_defs[action.to_sym] if ctr.respond_to?(:rfc6570_defs) + ctr.rfc6570_params_for(action.to_sym) if ctr.respond_to?(:rfc6570_params_for) rescue NameError nil end diff --git a/spec/rails/rfc6570/helper_spec.rb b/spec/rails/rfc6570/helper_spec.rb new file mode 100644 index 0000000..ff9dabb --- /dev/null +++ b/spec/rails/rfc6570/helper_spec.rb @@ -0,0 +1,44 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe Rails::RFC6570::Helper do + subject(:helper) do + routes = self.routes + + Class.new do + def url_options + {host: 'www.example.org'} + end + + include routes.url_helpers + include Rails::RFC6570::Helper + end.new + end + + let(:routes) do + ActionDispatch::Routing::RouteSet.new.tap do |routes| + routes.draw do + get '/path/:id', to: 'controller#action', as: :test1 + end + end + end + + describe '#rfc6570_routes' do + it 'returns dictionary of all named routes' do + expect(helper.rfc6570_routes).to eq({ + test1: Addressable::Template.new('http://www.example.org/path/{id}'), + }) + end + end + + describe '#rfc6570_route' do + it 'returns template for named route' do + expect(helper.rfc6570_route(:test1)).to eq Addressable::Template.new('http://www.example.org/path/{id}') + end + + it 'raise KeyError with unknown named route' do + expect { helper.rfc6570_route(:not_found) }.to raise_error KeyError + end + end +end