On 2/11/06, marcus <m-lists / bristav.se> wrote:
> I need to run an ERB template (a normal Rails view template) in a Rails
> model (and then write the result to a file). The problem is that I need
> to run it in the scope of the calling controller. So I was thinking of
> creating a binding in the controller and pass into the model and use the
> binding there. I do however need to add variables from the model scope
> into the binding. How do I do this? Thought of using eval with the
> binding but it only seems to take an input string to eval (a block would
> have been nice I think).
>
> The reason I do this is that the model in question is a STI model and
> each sub class may need to add different variables. If you can think of
> a better way to accomplish what I want I'll be glad to hear :)

If I understand correctly, you want something like this:

  def outerscope
     innerscope(binding)
     p foo,bar,baz  #problematic
  end

  def innerscope(bdg)
     eval "foo=bar=baz=1", binding
  end

This works, sort of. Unfortunately, ruby's local variables are
lexically scoped, which means that once you get back to outerscope,
foo, bar, and baz (which _are_ now in outerscope's binding) won't be
recognized as local variables. (Unless you use eval again to get at
them....) For most purposes, they are unusable.

How about this instead:

  def outerscope
     vars={}
     innerscope(vars)
     p vars[:foo],vars[:bar],vars[:baz]
  end

  def innerscope(vars)
     vars[:foo]=vars[:bar]=vars[:baz]=1
  end