Search code examples
rubysinatrahaml

How to evaluate Ruby code in Haml as a varaible


I was playing with ruby evaluation in haml. It doesn't work if i pass a variable to the haml template. it only works if the ruby code is already inside the template (not passed as variable), I'm sharing my source code for better explanation

require 'sinatra'
require 'haml'

get '/' do
  @user_input = params[:foo_user_input]
  puts @user_input
  haml :foo
end

__END__

@@ foo

%p= "hello"
<br>
%p= 7*7
<br>
%p= #{@user_input}
<br>
%p This is #{7*7} cake!
<br>
%p This is #{@user_input} cake!
<br>
%p= @user_input
<br>

if i pass 7*7 to the GET request, as you can see i get exactly 7*7, where it's not evaluated to 49. it only gets evaluated if i already place 7*7 in the haml template itself.

hello
49
This is 49 cake!
This is 7*7 cake!
7*7

Solution

  • When you want to evaluate Ruby code that is store in a string variable, then you can use eval like this:

    %p This is #{eval(@user_input)} cake!    
    

    Warning: But never pass strings to eval from an untrusted source. An attacker could pass code to your method that uploads our passwords to their server or that deletes your hard disk.