Skip to content

Instantly share code, notes, and snippets.

@ttilberg
Created July 23, 2020 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ttilberg/90eee60fccc9ca8b41601d831789e9f1 to your computer and use it in GitHub Desktop.
Save ttilberg/90eee60fccc9ca8b41601d831789e9f1 to your computer and use it in GitHub Desktop.
require "nokogiri"
# A base class for page objects.
# It works similar to SimpleDelegator, but parses incoming text if not done already.
# Any methods not explicitly defined are delegated to the underlying Nokogiri object.
#
# Example:
#
# class SearchPage < DocWrapper
# def results
# doc.css('li.result')
# end
# end
#
# page = Mechanize.goto 'https://www.example.com'
# search_page = SearchPage.new(page)
#
# page = File.read('test/pages/search_example.html')
# search_page = SearchPage.new(page)
#
# search_page.results.each do |result| ...
#
# # delegate other methods to underlying object
# search_page.css('h1')
#
class DocWrapper
attr_reader :doc
def initialize(doc)
doc = Nokogiri::HTML.parse doc if String === doc
@doc = doc
end
def method_missing(*args, **kwargs)
doc.send(*args, **kwargs)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment