class Enjoy::Goto::Middleware
Constants
- ATTRS
- REL_ATTRS
Public Class Methods
new(app, options = {})
click to toggle source
# File lib/enjoy/goto/middleware.rb, line 20 def initialize(app, options = {}) @app = app self end
Public Instance Methods
call(env)
click to toggle source
# 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
Private Instance Methods
add_attr(a, attr_name)
click to toggle source
# File lib/enjoy/goto/middleware.rb, line 64 def add_attr(a, attr_name) rel = a['rel'].blank? ? [] : a.rel.split(" ") rel << attr_name unless rel.include?(attr_name) a end
add_nofollow(a)
click to toggle source
# File lib/enjoy/goto/middleware.rb, line 70 def add_nofollow(a) add_attr('nofollow') if check_attr(a, :add_nofollow) end
add_noindex(a)
click to toggle source
# File lib/enjoy/goto/middleware.rb, line 74 def add_noindex(a) add_attr('noindex') if check_attr(a, :add_noindex) end
add_noopener(a)
click to toggle source
# File lib/enjoy/goto/middleware.rb, line 82 def add_noopener(a) add_attr('noopener') if check_attr(a, :add_noopener) end
add_noreferrer(a)
click to toggle source
# File lib/enjoy/goto/middleware.rb, line 78 def add_noreferrer(a) add_attr('noreferrer') if check_attr(a, :add_noreferrer) end
check_attr(a, attr_name)
click to toggle source
# File lib/enjoy/goto/middleware.rb, line 60 def check_attr(a, attr_name) Enjoy::Goto.config[attr_name] or (!a[ATTRS[attr_name]].blank? and !["0", "false", "no"].include?(a[ATTRS[attr_name]])) end
del_attrs(a)
click to toggle source
# File lib/enjoy/goto/middleware.rb, line 86 def del_attrs(a) if check_attr(ATTRS[del_attrs]) ATTRS.values.each do |attr| a.remove_attribute(attr) end end end
set_rel_attribute(a)
click to toggle source
# File lib/enjoy/goto/middleware.rb, line 94 def set_rel_attribute(a) REL_ATTRS.keys.each do |meth| self.send(meth, a) end end