ruby - Rails String Interpolation in a string from a database -


so here problem.

i want retrieve string stored in model , @ runtime change part of using variable rails application. here example:

i have message model, use store several unique messages. different users have same message, want able show name in middle of message, e.g.,

"hi #{user.name}, ...." 

i tried store in database gets escaped before showing in view or gets interpolated when storing in database, via rails console.

thanks in advance.

if want

"hi #{user.name}, ...." 

in database, use single quotes or escape # backslash keep ruby interpolating #{} stuff right away:

s = 'hi #{user.name}, ....' s = "hi \#{user.name}, ...." 

then, later when want interpolation could, if daring or trusted yourself, use eval:

s   = pull_the_string_from_the_database msg = eval '"' + s + '"' 

note you'll have turn s double quoted string in order eval work. work isn't nicest approach , leaves open sorts of strange , confusing errors should okay long (or other trusted people) writing strings; think you'd better off simple micro-templating system, simple this:

def fill_in(template, data)     template.gsub(/\{\{(\w+)\}\}/) { data[$1.to_sym] } end #... fill_in('hi {{user_name}}, ....', :user_name => 'pancakes') 

you use whatever delimiters wanted of course, went {{...}} because i've been using mustache.js , handlebars.js lately. naive implementation has issues (no in-template formatting options, no delimiter escaping, ...) might enough; if templates more complicated might want store bits of erb in database , use erb processor in standard library deal it.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -