Class: ExpoTurbo::Rails::RouteConstraint

Inherits:
Object
  • Object
show all
Defined in:
lib/expo_turbo/rails/route_constraint.rb

Constant Summary collapse

ACCEPT_ENTRY =
/[^,\s"](?:[^,"]|"[^"]*")*/

Instance Method Summary collapse

Instance Method Details

#matches?(request) ⇒ Boolean

Returns:

  • (Boolean)


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/expo_turbo/rails/route_constraint.rb', line 10

def matches?(request)
  accept = request.get_header("HTTP_ACCEPT").to_s.strip
  return false if accept.empty?

  mime_type = Mime[MIME_SYMBOL]
  return false unless mime_type

  quality = accept.scan(ACCEPT_ENTRY).filter_map do |value|
    begin
      media_range = Rack::MediaType.type(value)
      parsed = Mime::Type.parse(media_range)
    rescue Mime::Type::InvalidMimeType
      next
    end
    next unless parsed.include?(mime_type) || media_range == "*/*"

    specificity = if media_range == "*/*"
      0
    elsif media_range.end_with?("/*")
      1
    else
      2
    end

    [specificity, Rack::MediaType.params(value).fetch("q", 1).to_f]
  end.max_by { |specificity, range_quality| [specificity, range_quality] }&.last

  quality.to_f.positive?
end