Forum: Ruby on Rails Access block scope from AR object

Posted by Andrea Campolonghi (andreacfm)
on 2012-09-18 10:56
(Received via mailing list)
I need to create a sort of transaction around some Active Record objects
that perform many insert/updates.
Example:

class MyObject
    def transaction &block
        @my_var = value
        self.instance_eval block
    end
end

MyObject.new.transaction do
    Model.create
    Model.collection.create
    etc......
end

I have a gem that add a method into AR::Base and I need to read the
variables setted by the transaction inside the method at runtime.
Any way I can access the block scope from there inside?

Thanks

Andrea
Posted by Frederick Cheung (Guest)
on 2012-09-19 09:43
(Received via mailing list)
On Sep 18, 9:55am, andreacfm <acampolon...@gmail.com> wrote:
>
> MyObject.new.transaction do
>   Model.create
>   Model.collection.create
>   etc......
> end
>
> I have a gem that add a method into AR::Base and I need to read the
> variables setted by the transaction inside the method at runtime.
> Any way I can access the block scope from there inside?
>

Why not use an actual transaction? If you're generating some per
transaction value then pass it as an argument to the methods you're
calling inside the transaction.

Fred
Posted by Andrea Campolonghi (andreacfm)
on 2012-09-19 09:48
(Received via mailing list)
Fred.
The issue is that I should have to override lots of Model to support it.

Ex:
Model.create transaction_value: value

I would like something more elegant.

Andrea


On Sep 19, 2012, at 9:41 AM, Frederick Cheung 
<frederick.cheung@gmail.com> wrote:

>>         self.instance_eval block
>> variables setted by the transaction inside the method at runtime.
>> Thanks
>>
>> Andrea
>
> --
> You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
> To post to this group, send email to rubyonrails-talk@googlegroups.com.
> To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscribe@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

Andrea Campolonghi
acampolonghi@gmail.com
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.