Web Development in Ruby : Generate Documents using Templates
To learn how to use embedded ruby to merge data with a template.
Create a name.rb class:
class Name def initialize @name = 'Bugs Bunny' end # This is only a helper method to access # the object's (private) binding method def get_binding binding end end
Create a welcome.html.erb file:
Welcome <%= @name %>
Create a play.rb class:
require 'erb' require_relative 'name' name = Name.new erb_file = File.read(File.join(__dir__, 'welcome.html.erb')) template = ERB.new(erb_file) output = template.result(name.get_binding) puts output
Read the Ruby documentation to learn about what the above code does. Start experimenting with other methods in the ERB class.
In this article you learned how to use ERB to generate dynamic documents by merging a given template with values from an object.
Ace the Technical Interview
- Easily find the gaps in your knowledge
- Get customized lessons based on where you are
- Take consistent action everyday
- Builtin accountability to keep you on track
- You will solve bigger problems over time
- Get the job of your dreams
Take the 30 Day Coding Skills Challenge
Gain confidence to attend the interview