1

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?

1 Answer 1

1

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}
...
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the idea. For some reason I didn't even think about doing it that way ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.