Invoke block in current binding?

K

Kip Cole

I have a design pattern (Rails app, using RestfulAuthentication plugin
with modifications) that wants to have a method that will temporarily
elevate user privileges like so:

def sudo
saved_current_user = current_user
current_user = admin_user
yield
current_user = saved_current_user
end

And in a method, invoke it with

sudo do
puts "Something done as admin user"
end

However I know this doesn't work because at the time the block is
passed, the binding is fixed to the defining context.

So the question is: what is the right way to achieve the desired result.
Where the desired result is to pass a block to a method to be executed
in a different context, without the caller having to know any of the
implementation details.

Thanks for any help,

--Kip
 
J

Joel VanderWerf

Kip said:
So the question is: what is the right way to achieve the desired result.
Where the desired result is to pass a block to a method to be executed
in a different context, without the caller having to know any of the
implementation details.

What about this?

Context = Struct.new :user

def sudo
context = Context.new
context.user = "admin_user"
yield context
end

outer_context = Context.new
outer_context.user = "normal_user"
puts "I am #{outer_context.user}"

sudo do |context|
puts "I am #{context.user}"
end
 
K

Kip Cole

Joel, thanks very much, much appreciated.

--Kip

Joel said:
What about this?

Context = Struct.new :user

def sudo
context = Context.new
context.user = "admin_user"
yield context
end

outer_context = Context.new
outer_context.user = "normal_user"
puts "I am #{outer_context.user}"

sudo do |context|
puts "I am #{context.user}"
end
 

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

Similar Threads

Block Trouble (Binding Issue?) 3
su {block of code.} 11
eval / current binding 1
block issues... 16
Re-naming a block 2
saving values in block problem 2
an each/block problem 11
Binding scope 10

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top