Skip to content

Instantly share code, notes, and snippets.

@zeisler
Created January 22, 2016 21:06
Show Gist options
  • Save zeisler/1bdac10bc3e02c60e707 to your computer and use it in GitHub Desktop.
Save zeisler/1bdac10bc3e02c60e707 to your computer and use it in GitHub Desktop.
Pass attributes to child thread so that the current request id can be logged
require "thread"
class Thread
alias_method :_initialize, :initialize
def initialize(*args, &block)
inheritable_attributes = Thread.current.inheritable_attributes
_initialize(*args) do
Thread.current.inheritable_attributes = inheritable_attributes
block.call
end
end
def inheritable_attributes
self[:inheritable_attributes] || {}
end
def inheritable_attributes=(value)
self[:inheritable_attributes] = value
end
end
require "rory/thread"
RSpec.describe Thread do
after { Thread.current[:inheritable_attributes] = nil }
describe ".new" do
context "when inheritable_attributes is nil" do
before { Thread.current[:inheritable_attributes] = nil }
it "when creating a new thread it copies inheritable_attributes" do
thread = Thread.new {
[Thread.current.__id__, Thread.current[:inheritable_attributes]]
}
thread.join
expect(thread.value).to eq [thread.__id__, {}]
end
end
context "when inheritable_attributes has a value" do
before { Thread.current[:inheritable_attributes] = {:rory_request_id => SecureRandom.uuid} }
it "when creating a new thread it copies inheritable_attributes" do
thread = Thread.new {
[Thread.current.__id__, Thread.current[:inheritable_attributes]]
}
thread.join
expect(thread.value).to eq [thread.__id__, Thread.current[:inheritable_attributes]]
end
end
end
describe ".inheritable_attributes" do
it "defaults to a Hash" do
expect(Thread.current.inheritable_attributes).to be_an_instance_of(Hash)
end
end
describe ".inheritable_attributes=" do
it "defaults to a Hash" do
Thread.current.inheritable_attributes = "hello"
expect(Thread.current.inheritable_attributes).to eq "hello"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment