1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/actionview/lib/action_view/template_details.rb
John Hawthorn f8f9a085cc Encapsulate "details" into TemplateDetails
When dealing with the "details" for a template: locale, format,
variant, and handler, previously we would store these in an ad-hoc way
every place we did. Often as a hash or as separate instance variables on
a class.

This PR attempts to simplify this by encapsulating known details on a
template in a new ActionView::TemplateDetails class, and requested
details in ActionView::TemplateDetails::Requested.

This allowed extracting and simplifying filtering and sorting logic from
the Resolver class as well as extracting default format logic from
UnboundTemplate.

As well as reducing complexity, in the future this should make it
possible to provide suggestions on missing template errors due to
mismatched details, and might allow improved performance.

At least for now these new classes are private (:nodoc)

Co-authored-by: John Crepezzi <john.crepezzi@gmail.com>
2021-05-11 18:48:24 -07:00

67 lines
1.7 KiB
Ruby

# frozen_string_literal: true
module ActionView
class TemplateDetails # :nodoc:
class Requested
attr_reader :locale, :handlers, :formats, :variants
def initialize(locale:, handlers:, formats:, variants:)
@locale = locale
@handlers = handlers
@formats = formats
@variants = variants
end
end
attr_reader :locale, :handler, :format, :variant
def initialize(locale, handler, format, variant)
@locale = locale
@handler = handler
@format = format
@variant = variant
end
def matches?(requested)
return if format && !requested.formats.include?(format)
return if locale && !requested.locale.include?(locale)
unless requested.variants == :any
return if variant && !requested.variants.include?(variant)
end
return if handler && !requested.handlers.include?(handler)
true
end
def sort_key_for(requested)
locale_match = details_match_sort_key(locale, requested.locale)
format_match = details_match_sort_key(format, requested.formats)
variant_match =
if requested.variants == :any
variant ? 1 : 0
else
details_match_sort_key(variant, requested.variants)
end
handler_match = details_match_sort_key(handler, requested.handlers)
[locale_match, format_match, variant_match, handler_match]
end
def handler_class
Template.handler_for_extension(handler)
end
def format_or_default
format || handler_class.try(:default_format)
end
private
def details_match_sort_key(have, want)
if have
want.index(have)
else
want.size
end
end
end
end