Is there a way to limit the scope of variables in ERB (Ruby)?

Currently I can do:

r = ERB.new('Hi there <%= name %>')
r.result(OpenStruct.new(name: 'Joan').instance_eval{ binding })
# Outputs 'Hi there Joan'

But I can also do this (working in a Rails application with an administrator model):

r = ERB.new('<%= Admin.count %>')
r.result(OpenStruct.new.instance_eval{ binding })
# Outputs '10'

In other words, it has access to all the variables of my application in the context that the evaluation calls.

Is there a way to limit the scope of variables to only what I provide in a binding, for example. only a "name" and nothing more? I would like to use it in a custom template.

I tried this too (according to another SO question):

class Namespace
  def initialize(hash)
    hash.each do |key, value|
      singleton_class.send(:define_method, key) { value }
    end 
  end

  def get_binding
    binding
  end
end

The same result.

+3
source share
1 answer

ERB Ruby , . - Ruby VM Ruby.

, , , , Ruby ERB.

, , Liquid ( ) Mustache, , .

+4

All Articles