Class: Hancock::Goto::Middleware
- Inherits:
-
Object
- Object
- Hancock::Goto::Middleware
- Includes:
- Rack::Utils
- Defined in:
- lib/hancock/goto/middleware.rb
Constant Summary collapse
- ATTRS =
{ disabled: 'data-hancock-goto-disabled', add_nofollow: 'data-hancock-goto-add-nofollow', add_noindex: 'data-hancock-goto-add-noindex', add_noreferrer: 'data-hancock-goto-add-noreferrer', add_noopener: 'data-hancock-goto-add-noopener', del_attrs: 'data-hancock-goto-del-attrs' }
- REL_ATTRS =
ATTRS.dup
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, options = {}) ⇒ Middleware
constructor
A new instance of Middleware.
Constructor Details
#initialize(app, options = {}) ⇒ Middleware
Returns a new instance of Middleware.
23 24 25 26 |
# File 'lib/hancock/goto/middleware.rb', line 23 def initialize(app, = {}) @app = app self end |
Instance Method Details
#call(env) ⇒ Object
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 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/hancock/goto/middleware.rb', line 28 def call(env) status, headers, response = @app.call(env) headers = HeaderHash.new(headers) if should_process?(status, headers, env) begin content = extract_content(response) if Hancock::Goto.config.href_attr_regex and content =~ Hancock::Goto.config.href_attr_regex doc = ::Nokogiri::HTML(content) doc.css(Hancock::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 =~ Hancock::Goto.config.href_regex begin _host = Addressable::URI.parse(_href).host unless Hancock::Goto.config.excluded_hosts.include?(_host) a['href'] = Rails.application.routes.url_helpers.hancock_goto_path(url: _href) a['target'] = '_blank' if a['target'].blank? set_rel_attribute(a) del_attrs(a) end rescue end end end content = doc.to_html headers['content-length'] = bytesize(content).to_s response = [content] end rescue Exception => ex # puts ex.message # puts ex.backtrace end end [status, headers, response] end |