[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Invoke block in current binding?

Kip Cole

7/26/2008 11:43:00 PM

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
--
Posted via http://www.ruby-....

2 Answers

Joel VanderWerf

7/27/2008 7:19:00 PM

0

Kip Cole wrote:
> 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

--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

Kip Cole

7/28/2008 8:59:00 PM

0

Joel, thanks very much, much appreciated.

--Kip

Joel VanderWerf wrote:
> Kip Cole wrote:
>> 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

--
Posted via http://www.ruby-....