daily pastebin goal
74%
SHARE
TWEET

Untitled

a guest Mar 14th, 2018 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. require 'nokogiri'
  2.  
  3. # Usage:
  4. #
  5. #   use Rack::Injector do |inject|
  6. #     inject.before 'h1', '<div class="injected">This was injected before</div>'
  7. #     inject.after 'h1', '<div class="injected">This was injected after</div>'
  8. #   end
  9. class Rack::Injector
  10.   def initialize(app)
  11.     @app = app
  12.     @afters = {}
  13.     @befores = {}
  14.     yield self if block_given?
  15.   end
  16.  
  17.   def call(env)
  18.     status, headers, body = @app.call(env)
  19.     response = Rack::Response.new(inject!(body.join), status, headers)
  20.     response.finish
  21.   end
  22.  
  23.   def before(selector, content)
  24.     @befores[selector] ||= []
  25.     @befores[selector] << content
  26.   end
  27.  
  28.   def after(selector, content)
  29.     @afters[selector] ||= []
  30.     @afters[selector] << content
  31.   end
  32.  
  33.   def inject!(body)
  34.     doc = Nokogiri::HTML(body)
  35.    
  36.     @afters.each do |selector, contents|
  37.       doc.search(selector).each do |node|
  38.         node.after(contents.join("\n")) if node
  39.       end
  40.     end
  41.    
  42.     @befores.each do |selector, contents|
  43.       doc.search(selector).each do |node|
  44.         node.before(contents.join("\n")) if node
  45.       end
  46.     end
  47.    
  48.     [doc.to_html]
  49.   end
  50. end
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top