Ruby templates: How to pass variables into inlined ERB?

前端 未结 10 1723
陌清茗
陌清茗 2020-11-30 21:18

I have an ERB template inlined into Ruby code:

require \'erb\'

DATA = {
    :a => \"HELLO\",
    :b => \"WORLD\",
}

template = ERB.new <<-EOF
          


        
10条回答
  •  青春惊慌失措
    2020-11-30 21:59

    As others said, to evaluate ERB with some set of variables, you need a proper binding. There are some solutions with defining classes and methods but I think simplest and giving most control and safest is to generate a clean binding and use it to parse the ERB. Here's my take on it (ruby 2.2.x):

    module B
      def self.clean_binding
        binding
      end
    
      def self.binding_from_hash(**vars)
        b = self.clean_binding
        vars.each do |k, v|
          b.local_variable_set k.to_sym, v
        end
        return b
      end
    end
    my_nice_binding = B.binding_from_hash(a: 5, **other_opts)
    result = ERB.new(template).result(my_nice_binding)
    

    I think with eval and without ** same can be made working with older ruby than 2.1

提交回复
热议问题