add transact method

master
Kanezoh 2021-08-24 07:50:12 +09:00
parent b98bb4eb2d
commit d344fadc44
3 changed files with 25 additions and 3 deletions

View File

@ -63,4 +63,14 @@ describe "Mechanize Agent test" do
File.exists?("mechanizecr_example.html").should eq true File.exists?("mechanizecr_example.html").should eq true
File.delete("mechanizecr_example.html") File.delete("mechanizecr_example.html")
end end
it "doesn't add page to history within transact block" do
agent = Mechanize.new
agent.get("http://example.com/")
agent.history.size.should eq 1
agent.transact do
agent.get("http://example.com/")
end
agent.history.size.should eq 1
end
end end

View File

@ -138,4 +138,16 @@ class Mechanize
end end
page page
end end
# Runs given block, then resets the page history as it was before.
def transact
# save the previous history status.
history_backup = MechanizeCr::History.new(@agent.history.max_size, @agent.history.array.dup)
begin
yield self
ensure
# restore the previous history.
@agent.history = history_backup
end
end
end end

View File

@ -4,11 +4,11 @@ class MechanizeCr::History
property max_size : Int32 property max_size : Int32
property array : Array(MechanizeCr::Page) property array : Array(MechanizeCr::Page)
forward_missing_to @array delegate :size, :empty?, :last, to: array
def initialize(max_size = 100) def initialize(max_size = 100, array = Array(MechanizeCr::Page).new)
@max_size = max_size @max_size = max_size
@array = Array(MechanizeCr::Page).new @array = array
end end
def push(page, uri = nil) def push(page, uri = nil)