Getting references

J

John

How does one get a reference to a previously created object?

Here's the scenario. I'm writing a web application, so there's a
listener object that listens to incoming requests and spins off a
thread for each request. Each thread has a Context object, which holds
things like POST arguments, browser type, etc.

Suppose a request comes in, a thread is spun, and it finds a template
object for that page, fills it with text from a database, and now I
want to run macros. Finding and running macros is ridiculously easy
due to Ruby's regex support. But I want macros to have access to the
Context in which they are running. Is there any way to do this aside
from passing a reference along with each call?
 
T

ts

J> thread for each request. Each thread has a Context object, which holds
J> things like POST arguments, browser type, etc.

Well, if each thread has a Context object then you can store it as a
thread local variable

J> due to Ruby's regex support. But I want macros to have access to the
J> Context in which they are running. Is there any way to do this aside
J> from passing a reference along with each call?

retrieve the thread local variable, something like

svg% cat b.rb
#!/usr/bin/ruby

def retrieve
puts Thread.current['context']
end

Thread.new { Thread.current['context'] = 12; retrieve }
Thread.new { Thread.current['context'] = 24; retrieve }
svg%

svg% b.rb
12
24
svg%
 
R

Robert Klemme

ts said:
J> thread for each request. Each thread has a Context object, which holds
J> things like POST arguments, browser type, etc.

Well, if each thread has a Context object then you can store it as a
thread local variable

J> due to Ruby's regex support. But I want macros to have access to the
J> Context in which they are running. Is there any way to do this aside
J> from passing a reference along with each call?

retrieve the thread local variable, something like

svg% cat b.rb
#!/usr/bin/ruby

def retrieve
puts Thread.current['context']
end

Thread.new { Thread.current['context'] = 12; retrieve }
Thread.new { Thread.current['context'] = 24; retrieve }
svg%

svg% b.rb
12
24
svg%

Yeah. Another option is to have a macro interpreter that knows about the
context:

class MacroInterpreter
attr_accessor :context

def expand(macro)
# ...
end
end

Then you have to set it only once and you are not dependend on the thread.
IMHO this is cleaner than passing a hidden method argument / hidden global
(which a thread local effectively is).

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,139
Messages
2,570,805
Members
47,351
Latest member
LolaD32479

Latest Threads

Top