Class: Enjoy::Goto::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/enjoy/goto/middleware.rb

Constant Summary collapse

ATTRS =
{
  disabled:       'data-enjoy-goto-disabled',
  add_nofollow:   'data-enjoy-goto-add-nofollow',
  add_noindex:    'data-enjoy-goto-add-noindex',
  add_noreferrer: 'data-enjoy-goto-add-noreferrer',
  add_noopener:   'data-enjoy-goto-add-noopener',
  del_attrs:      'data-enjoy-goto-del-attrs'
}
REL_ATTRS =
ATTRS

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Middleware

Returns a new instance of Middleware.



20
21
22
23
# File 'lib/enjoy/goto/middleware.rb', line 20

def initialize(app, options = {})
  @app = app
  self
end

Instance Method Details

#call(env) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/enjoy/goto/middleware.rb', line 25

def call(env)
  status, headers, body = @app.call(env)

  if headers['Content-Type'].to_s.include?('text/html')
    begin
      doc = Nokogiri::HTML.fragment(body.body)
      doc.css(Enjoy::Goto.config[:css_selector]).each do |a|
        if (!a[ATTRS[:disabled]].blank? and !["0", "false", "no"].include?(a[ATTRS[:disabled]]))
          del_attrs(a)
          next
        end

        _href = a['href']
        if _href =~ Enjoy::Goto.config[:href_regex]
          begin
            _host = Addressable::URI.parse(_href).host
            unless Enjoy::Goto.config[:excluded_hosts].include?(_host)
              a['href'] = Rails.application.routes.url_helpers.enjoy_goto_path(url: _href)
              a['target'] = '_blank' if a['target'].blank?
              set_rel_attribute(a)
              del_attrs(a)
            end
          rescue
          end
        end
      end
      return [status, headers, [doc.to_html]]
    rescue
    end
  end

  [status, headers, body]
end