Search code examples
javascriptruby-on-railsrubystring-interpolation

Embed ruby interpolation into <script> tag of html string (variable)?


I'm struggling with embedding ruby interpolation into the string variable that is an html string. I guess it sounds a bit confusing and I hope the code will help to understand:

  def devise_error_messages!
    return '' if resource.errors.empty?
    messages = resource.errors.full_messages
    html = <<-HTML
      <script type='text/javascript'>
        toastr.options = {
          'closeButton': true,
          'debug': false,
          'newestOnTop': false,
          'progressBar': false,
          'positionClass': 'toast-bottom-left',
          'preventDuplicates': true,
          'onclick': null,
          'showDuration': '3000',
          'hideDuration': '1000',
          'timeOut': '5000',
          'extendedTimeOut': '1000',
          'showEasing': 'swing',
          'hideEasing': 'linear',
          'showMethod': 'fadeIn',
          'hideMethod': 'fadeOut'
        }
        #{ messages.each do |m| }
          toastr['error']("#{m}");
        #{end}

      </script>
    HTML

    html.html_safe
  end

So, as you can see, I'm trying to iterate over messages array and generate for each message this line of js code: toastr['error']("#{m}");

Could you please help me with implementing that correctly?


Solution

  • You can move the each block outside the HTML tag and simply store results in a string, then append the string inside the script tag.

    str = ""
    messages.each do |m|    
      str += "toastr['error'](" + '"' + m + '"' + '); '
    end
    

    Place the str variable in the block where you want it.

    toastr.options = {
      ...
    }
    #{str}
    ...