class Capybara::Server::AnimationDisabler

Constants

DISABLE_CSS_MARKUP_TEMPLATE
DISABLE_JS_MARKUP_TEMPLATE

Attributes

disable_css_markup[R]
disable_js_markup[R]

Public Class Methods

new(app) click to toggle source
# File lib/capybara/server/animation_disabler.rb, line 17
def initialize(app)
  @app = app
  @disable_css_markup = format(DISABLE_CSS_MARKUP_TEMPLATE,
                               selector: self.class.selector_for(Capybara.disable_animation))
  @disable_js_markup = format(DISABLE_JS_MARKUP_TEMPLATE,
                              selector: self.class.selector_for(Capybara.disable_animation))
end
selector_for(css_or_bool) click to toggle source
# File lib/capybara/server/animation_disabler.rb, line 6
def self.selector_for(css_or_bool)
  case css_or_bool
  when String
    css_or_bool
  when true
    '*'
  else
    raise CapybaraError, 'Capybara.disable_animation supports either a String (the css selector to disable) or a boolean'
  end
end

Public Instance Methods

call(env) click to toggle source
# File lib/capybara/server/animation_disabler.rb, line 25
def call(env)
  @status, @headers, @body = @app.call(env)
  return [@status, @headers, @body] unless html_content?

  nonces = directive_nonces.transform_values { |nonce| "nonce=\"#{nonce}\"" if nonce && !nonce.empty? }
  response = Rack::Response.new([], @status, @headers)

  @body.each { |html| response.write insert_disable(html, nonces) }
  @body.close if @body.respond_to?(:close)

  response.finish
end

Private Instance Methods

directive_nonces() click to toggle source
# File lib/capybara/server/animation_disabler.rb, line 51
def directive_nonces
  @headers.fetch('Content-Security-Policy', '')
          .split(';')
          .map(&:split)
          .to_h do |s|
            [
              s[0], s[1..].filter_map do |value|
                /^'nonce-(?<nonce>.+)'/ =~ value
                nonce
              end[0]
            ]
          end
end
html_content?() click to toggle source
# File lib/capybara/server/animation_disabler.rb, line 42
def html_content?
  /html/.match?(@headers['Content-Type'])
end
insert_disable(html, nonces) click to toggle source
# File lib/capybara/server/animation_disabler.rb, line 46
def insert_disable(html, nonces)
  html.sub(%r{(</head>)}, "<style #{nonces['style-src']}>#{disable_css_markup}</style>\\1")
      .sub(%r{(</body>)}, "<script #{nonces['script-src']}>#{disable_js_markup}</script>\\1")
end