Skip to content

Commit 801980a

Browse files
authored
Merge pull request rails#42777 from jhawthorn/requested_details_hash_match
Store requested detail indexes in hashes
2 parents fd7b030 + eac19fe commit 801980a

File tree

1 file changed

+27
-28
lines changed

1 file changed

+27
-28
lines changed

actionview/lib/action_view/template_details.rb

Lines changed: 27 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,30 @@ module ActionView
44
class TemplateDetails # :nodoc:
55
class Requested
66
attr_reader :locale, :handlers, :formats, :variants
7+
attr_reader :locale_idx, :handlers_idx, :formats_idx, :variants_idx
8+
9+
ANY_HASH = Hash.new(1).merge(nil => 0).freeze
710

811
def initialize(locale:, handlers:, formats:, variants:)
912
@locale = locale
1013
@handlers = handlers
1114
@formats = formats
1215
@variants = variants
16+
17+
@locale_idx = build_idx_hash(locale)
18+
@handlers_idx = build_idx_hash(handlers)
19+
@formats_idx = build_idx_hash(formats)
20+
if variants == :any
21+
@variants_idx = ANY_HASH
22+
else
23+
@variants_idx = build_idx_hash(variants)
24+
end
1325
end
26+
27+
private
28+
def build_idx_hash(arr)
29+
[*arr, nil].each_with_index.to_h.freeze
30+
end
1431
end
1532

1633
attr_reader :locale, :handler, :format, :variant
@@ -23,28 +40,19 @@ def initialize(locale, handler, format, variant)
2340
end
2441

2542
def matches?(requested)
26-
return if format && !requested.formats.include?(format)
27-
return if locale && !requested.locale.include?(locale)
28-
unless requested.variants == :any
29-
return if variant && !requested.variants.include?(variant)
30-
end
31-
return if handler && !requested.handlers.include?(handler)
32-
33-
true
43+
requested.formats_idx[@format] &&
44+
requested.locale_idx[@locale] &&
45+
requested.variants_idx[@variant] &&
46+
requested.handlers_idx[@handler]
3447
end
3548

3649
def sort_key_for(requested)
37-
locale_match = details_match_sort_key(locale, requested.locale)
38-
format_match = details_match_sort_key(format, requested.formats)
39-
variant_match =
40-
if requested.variants == :any
41-
variant ? 1 : 0
42-
else
43-
details_match_sort_key(variant, requested.variants)
44-
end
45-
handler_match = details_match_sort_key(handler, requested.handlers)
46-
47-
[locale_match, format_match, variant_match, handler_match]
50+
[
51+
requested.formats_idx[@format],
52+
requested.locale_idx[@locale],
53+
requested.variants_idx[@variant],
54+
requested.handlers_idx[@handler]
55+
]
4856
end
4957

5058
def handler_class
@@ -54,14 +62,5 @@ def handler_class
5462
def format_or_default
5563
format || handler_class.try(:default_format)
5664
end
57-
58-
private
59-
def details_match_sort_key(have, want)
60-
if have
61-
want.index(have)
62-
else
63-
want.size
64-
end
65-
end
6665
end
6766
end

0 commit comments

Comments
 (0)