Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use erb Template in ruby code

Tags:

ruby

I want to use the erb template feature of ruby. But I am not able to run the sample code provided.

I find that erb is installed:

# file /usr/lib/ruby/1.9.1/erb.rb
/usr/lib/ruby/1.9.1/erb.rb: ASCII English text

and it was installed along with ruby:

# dpkg -S /usr/lib/ruby/1.9.1/erb.rb
libruby1.9.1: /usr/lib/ruby/1.9.1/erb.rb

I am running below sample code which is provided in /usr/lib/ruby/1.9.1/erb.rb

#!/usr/bin/ruby
require 'erb'
x = 42
template = ERB.new <<-EOF
  The value of x is: <%= x %>
EOF
puts template.result(binding)

I get below error when I run the code:

/workspace/ruby/erb.rb:4:in `<top (required)>': uninitialized constant ERB (NameError)
    from /workspace/ruby/erb.rb:2:in `require'
    from /workspace/ruby/erb.rb:2:in `<main>'

Question: what is missing in above code?

Here is my platform:

# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 10.04.4 LTS
Release:    10.04
Codename:   lucid

# uname -m
i686

and my ruby version:

# ruby -v
ruby 1.9.1p378 (2010-01-10 revision 26273) [i486-linux]

ANSWER:

@matt's comment is answer to this question. I had named my script as erb.rb and that was the problem. I renamed it to testing_erb.rb and it worked. Please check matt's comment for more details.

like image 618
slayedbylucifer Avatar asked Oct 25 '25 14:10

slayedbylucifer


1 Answers

Your test file is called erb.rb. In Ruby 1.9.1 the current directory is on the load path, so when you call require 'erb' it is trying to require itself. Since the file does not define ERB you get the uninitialized constant error when trying to use that constant.

Try renaming your file to something like erb_testing.rb, so that when you require erb there is no confusion between the different files.

Note that in later versions of Ruby (1.9.2+) the current directory is not in the default load path, so you wouldn’t see problems like this. It might be worth looking at upgrading your version of Ruby since 1.9.1 is pretty old now (2.1 should be released soon, and with that 1.9.1 will be four versions behind). Take a look at RVM if your package manager doesn’t have more recent releases.

One thing to note is that this error depends on the order of the entries in the load path. On my install of 1.9.1 the current directory is the last entry, so when requiring erb the version from the standard library is seen first and loaded, and there is no error. It looks like your installation puts the current directory before the standard library – I don’t know why that would be though.

like image 195
matt Avatar answered Oct 28 '25 02:10

matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!