Created
July 23, 2020 03:25
-
-
Save ttilberg/90eee60fccc9ca8b41601d831789e9f1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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