Search code examples
htmlrubyregexwebrick

String Replace Regex like mustache js for Ruby


I am new to ruby and was trying to make a simple function that would take a file and replace all the mustache with an array. For example:

simple.tpl

<p>Hello {{person_name}}</p>
<p>{{welcome_msg}}</p>

I want to change it with an array of keys and values.

class Template

    attr_accessor :file_name

    def parse_template (array_to_replace)
        str = File.read(file_name)

        array_to_replace.each do |item|
        # required code here ...
        end

        return str
    end

end

Can anyone put the required code ???

Expected Output

I don't know how multidimensional arrays work in ruby but what I want is:

the_arr = Array(
   :person_name => "John Doe",
   :welcome_msg => "Hello friend"
)
object = Template.new
object.file_name = "simple.tpl"
output = object.parse_template(the_arr);

puts output

I should get

<p>Hello John Doe</p>
<p>Hello friend</p>

Solution

  • You can use the mustache gem:

    require 'mustache'
    
    attributes = {
      :person_name => "John Doe",
      :welcome_msg => "Hello friend"
    }
    
    template = File.read('simple.tpl')
    
    output = Mustache.render(template, attributes)
    
    puts output
    # <p>Hello John Doe</p>
    # <p>Hello friend</p>