Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute ruby template files (ERB) without a web server from command line?

I need ERB (Ruby's templating system) for templating of non-HTML files.
(Instead, I want to use it for source files such as .java, .cs, ...)

How do I "execute" Ruby templates from command line?

like image 516
ivan_ivanovich_ivanoff Avatar asked Jun 11 '09 11:06

ivan_ivanovich_ivanoff


People also ask

What is ERB file in Ruby?

ERB (Embedded RuBy) is a feature of Ruby that enables you to conveniently generate any kind of text, in any quantity, from templates. The templates themselves combine plain text with Ruby code for variable substitution and flow control, which makes them easy to write and maintain.

What is a template in Ruby?

Template Method is a behavioral design pattern that allows you to defines a skeleton of an algorithm in a base class and let subclasses override the steps without changing the overall algorithm's structure.


Video Answer


3 Answers

You should have everything you need in your ruby/bin directory. On my (WinXP, Ruby 1.8.6) system, I have ruby/bin/erb.bat

erb.bat [switches] [inputfile]
  -x               print ruby script
  -n               print ruby script with line number
  -v               enable verbose mode
  -d               set $DEBUG to true
  -r [library]     load a library
  -K [kcode]       specify KANJI code-set
  -S [safe_level]  set $SAFE (0..4)
  -T [trim_mode]   specify trim_mode (0..2, -)
  -P               ignore lines which start with "%"

so erb your_erb_file.erb should write the result to STDOUT.

(EDIT: windows has erb.bat and just plain "erb". The .bat file is just a wrapper for erb, which I guess should make the same command work pretty much the same on any OS)

See the prag prog book discussion (starts about half-way down the page).

Note also that Jack Herrington wrote a whole book about code generation that uses Ruby/ERB.

like image 129
Mike Woodhouse Avatar answered Oct 20 '22 08:10

Mike Woodhouse


Write a ruby script that does it. The API documentation is here: http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/

For example:

template = ERB.new File.read("path/to/template.erb"), nil, "%"
template.result(binding)

(Where binding is a binding with the @vars that the template needs.)

like image 35
Sam Avatar answered Oct 20 '22 07:10

Sam


Another option would be to use ruby -e, since ERB itslef is so simple.

Something like:

ruby -rerb -e "puts ERB.new(File.read(<file name here>)).result"

However, I assume you have a context you want to render the template in. How are you expecting to get that context? As an example, check out:

ruby -rerb -e "hello = 'hello'; puts ERB.new('<%= hello %> world').result(binding)"

which will print out "hello world", using the top-level, where you defined the hello variable, as the binding.

like image 15
Yehuda Katz Avatar answered Oct 20 '22 07:10

Yehuda Katz