Why can't the Mail block see my variable?

前端 未结 3 1543
生来不讨喜
生来不讨喜 2021-02-15 11:35

I\'m new to Ruby and wondering why I am getting an error in this situation using the \'mail\' gem in a simple Sinatra app:

post \"/email/send\" do

  @recipient          


        
3条回答
  •  时光说笑
    2021-02-15 11:42

    As Julik says, Mail#delivery executes your block using #instance_exec, which simply changes self while running a block (you wouldn't be able to call methods #to and #from inside the block otherwise).

    What you really can do here is to use a fact that blocks are closures. Which means that it "remembers" all the local variables around it.

    recipient = params[:email]
    Mail.deliver do 
        to recipient # 'recipient' is a local variable, not a method, not an instance variable
    ...
    end
    

    Again, briefly:

    • instance variables and method calls depend on self
    • #instance_exec changes the self;
    • local variables don't depend on self and are remembered by blocks because blocks are closures.

提交回复
热议问题