Search code examples
ruby-on-railsruby-on-rails-2redcloth

RedCloth and Ruby string interpolation possible?


I have a view which renders a block of text through RedCloth and I would want to add some variables to that text, f.ex. through ruby string interpolation.

Is this in any way possible?


Solution

  • I am assuming you use redcloth, so your users/editors will enter text, but they will be given a few keywords they can enter and which will be filled in at render time. For example something like author, date, ... but of course I have no idea what your website is for.

    The cleanest delayed string interpolation is to use the % operator.

    Some nonsense example for demonstration purposes only :

    some_text = "flap %{cookie} some more %{action} NOW!" 
    filled_in_text = some_text % {cookie: 'banana', action: 'eating' }
    Redcloth.new(filled_in_text).to_html
    

    So you will retrieve some_text from the database (model), what the user/editor typed, and then interpolate using the % and a hash of possible (supported values). The result you just hand to redcloth.