Skip to content

Don't modify the params hash passed to Client.new - #39

Open
Divyanshu-2907 wants to merge 1 commit into
serpapi:masterfrom
Divyanshu-2907:fix/constructor-params-mutation
Open

Divyanshu-2907 wants to merge 1 commit into
serpapi:masterfrom
Divyanshu-2907:fix/constructor-params-mutation

Conversation

@Divyanshu-2907

Copy link
Copy Markdown

Client#initialize deletes :timeout and :persistent straight from the hash the caller passes in. That causes two problems.

If you build two clients from the same config hash, the second one silently loses those settings and falls back to a 120s timeout and a persistent socket:

config = { engine: 'google', api_key: 'xxx', timeout: 5, persistent: false }
a = SerpApi::Client.new(config)
b = SerpApi::Client.new(config)
b.timeout    # => 120, expected 5
b.persistent # => true, expected false
config       # => { engine: 'google', api_key: 'xxx' }

And a frozen config hash (common for constants) raises:

SerpApi::Client.new({ engine: 'google', timeout: 5 }.freeze)
# => FrozenError: can't modify frozen Hash

The fix is to work on params.dup and take :timeout and :persistent out of the copy. I used dup rather than clone on purpose, because clone keeps the frozen flag and would still raise on a frozen hash. @params is still frozen at the end like before, so nothing changes for callers who pass a fresh hash.

I added spec/serpapi/client/constructor_spec.rb. Those specs only build clients and never hit the API, so they run without a real key.

PR #22 touched this area too, but it was closed along with a lot of other changes. This one is just the constructor fix, so it's easy to review on its own.

The constructor deleted :timeout and :persistent from the caller's hash,
so a reused config hash gave the second client the default 120s timeout
and a persistent socket. A frozen hash raised FrozenError.

Work on a dup of params instead. dup is used rather than clone because
clone keeps the frozen state.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant