Skip to content

Commit e5a39bb

Browse files
committed
fix: Optimize route generation in rfc6570_route/s helper
The #rfc6570_routes helper directly delegates to #to_rfc6570 on the named routes collection now, avoiding manual iteration and an extra lookup via #rfc6570_route. Otherwise, both methods the context-local #_routes method now, instead of Rails.application.routes, which eases testing. New helper specs verify both method in detail now too.
1 parent 1b478cc commit e5a39bb

File tree

2 files changed

+47
-8
lines changed

2 files changed

+47
-8
lines changed

lib/rails/rfc6570.rb

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -88,16 +88,11 @@ def to_rfc6570(**opts)
8888

8989
module Helper
9090
def rfc6570_routes(**opts)
91-
routes = {}
92-
Rails.application.routes.named_routes.names.each do |key|
93-
routes[key] = rfc6570_route(key, **opts)
94-
end
95-
96-
routes
91+
_routes.named_routes.to_rfc6570(**opts, ctx: self)
9792
end
9893

9994
def rfc6570_route(name, **opts)
100-
route = Rails.application.routes.named_routes[name]
95+
route = _routes.named_routes[name]
10196
raise KeyError.new "No named routed for `#{name}'." unless route
10297

10398
route.to_rfc6570(**opts, ctx: self)
@@ -120,7 +115,7 @@ def rfc6570_params_for(defs)
120115

121116
def params_for(controller, action)
122117
ctr = "#{controller.camelize}Controller".constantize
123-
ctr.rfc6570_defs[action.to_sym] if ctr.respond_to?(:rfc6570_defs)
118+
ctr.rfc6570_params_for(action.to_sym) if ctr.respond_to?(:rfc6570_params_for)
124119
rescue NameError
125120
nil
126121
end

spec/rails/rfc6570/helper_spec.rb

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# frozen_string_literal: true
2+
3+
require 'spec_helper'
4+
5+
RSpec.describe Rails::RFC6570::Helper do
6+
subject(:helper) do
7+
routes = self.routes
8+
9+
Class.new do
10+
def url_options
11+
{host: 'www.example.org'}
12+
end
13+
14+
include routes.url_helpers
15+
include Rails::RFC6570::Helper
16+
end.new
17+
end
18+
19+
let(:routes) do
20+
ActionDispatch::Routing::RouteSet.new.tap do |routes|
21+
routes.draw do
22+
get '/path/:id', to: 'controller#action', as: :test1
23+
end
24+
end
25+
end
26+
27+
describe '#rfc6570_routes' do
28+
it 'returns dictionary of all named routes' do
29+
expect(helper.rfc6570_routes).to eq({
30+
test1: Addressable::Template.new('http://www.example.org/path/{id}'),
31+
})
32+
end
33+
end
34+
35+
describe '#rfc6570_route' do
36+
it 'returns template for named route' do
37+
expect(helper.rfc6570_route(:test1)).to eq Addressable::Template.new('http://www.example.org/path/{id}')
38+
end
39+
40+
it 'raise KeyError with unknown named route' do
41+
expect { helper.rfc6570_route(:not_found) }.to raise_error KeyError
42+
end
43+
end
44+
end

0 commit comments

Comments
 (0)