From d344fadc44919b469175077a3f9fdccd56edc120 Mon Sep 17 00:00:00 2001 From: Kanezoh Date: Tue, 24 Aug 2021 07:50:12 +0900 Subject: [PATCH] add transact method --- spec/agent_spec.cr | 10 ++++++++++ src/mechanize.cr | 12 ++++++++++++ src/mechanize/history.cr | 6 +++--- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/spec/agent_spec.cr b/spec/agent_spec.cr index a729169..ed7e8f8 100644 --- a/spec/agent_spec.cr +++ b/spec/agent_spec.cr @@ -63,4 +63,14 @@ describe "Mechanize Agent test" do File.exists?("mechanizecr_example.html").should eq true File.delete("mechanizecr_example.html") 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 diff --git a/src/mechanize.cr b/src/mechanize.cr index 5533293..3bd9b7a 100644 --- a/src/mechanize.cr +++ b/src/mechanize.cr @@ -138,4 +138,16 @@ class Mechanize end page 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 diff --git a/src/mechanize/history.cr b/src/mechanize/history.cr index 183a90b..6e1600b 100644 --- a/src/mechanize/history.cr +++ b/src/mechanize/history.cr @@ -4,11 +4,11 @@ class MechanizeCr::History property max_size : Int32 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 - @array = Array(MechanizeCr::Page).new + @array = array end def push(page, uri = nil)