Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing binding or arguments to ERB from the command line

I have been playing around with erb from the command line recently. I wanted to make a dirt simple erb template, for example the following:

<%- name = "Joe"; quality = "fantastic" -%>
Hello. My name is <%= name %>. I hope your day is <%= quality %>.

This works if I run

erb -T - thatfile.erb

what I want to do is to make name and quality be passable from command line arguments, so that I could do something like:

./thatfile.erb "Bill" "super"

from the bash prompt and do the same thing.

I am aware that I could write a ruby script that would just read that template in and then use ERB.new(File.read("thatfile.erb")).result(binding), or writing the template after an END and doing likewise, but I'm looking for a more lightweight approach if it exists, because I don't want to write two files for each erb script that I create for this purpose.

like image 488
scott_fakename Avatar asked Jul 27 '13 07:07

scott_fakename


2 Answers

Alternatively, you can use a ruby script and load it in as a library.

# vars.rb
@hello = 'kirk'
# template.html.erb
<div><%= @hello %></div>
$ erb -r './vars' template.html.erb
like image 82
James Lim Avatar answered Sep 28 '22 07:09

James Lim


Please note that Ruby 2.2 and newer provide a much nicer solution that was implemented according to this:

erb var1=val1 var2=val2 my-template.erb
like image 29
Florin Asăvoaie Avatar answered Sep 28 '22 05:09

Florin Asăvoaie