Log in
updated 11:29 AM UTC, May 4, 2016

Ruby conditional statements in ERB file

  • Written by Madhu V Rao
  • Published in Ruby

Here is another program to demonstrate the use of conditional statements in Ruby ERB file.

This program converts the ERB file into an xml file.

require 'rubygems'
require 'erb'

class Customiser
  attr_accessor :config
  
  def initialize
    @config = true
  end
  
  def read_config_file
#    your code to read a config and populate the variable
    @config = false
  end
  
  def convert_to_erb
    template_file = File.open("test.xml.erb", "r").read
    erb = ERB.new(template_file)
    File.open("test.xml","w+") { |file| 
      file.write(erb.result(binding))
    }
  end
  
end

creator = Customiser.new
creator.read_config_file()
creator.convert_to_erb()

 

Here is the ERB file (test.xml.erb):

<database>
	<table name="something">
		<% 	if @config == true
				@val = "<choice-1> <choice-1>"		
			else
			 	@val = "<choice-2> <choice-2>"
			end
		 %>
		 <%= @val %>
	</table>
</database>	

run the program by changing the config variable value to see the difference.


Powered by Bullraider.com
Follow Us on Twitter
Find Us on Facebook
Follow Us on Google
Follow Us on Pinterest