Search code examples
rubyruby-on-rails-4ruby-on-rails-3.2link-to

How to interpolate link_to as a block


I'm trying to make a link_to block (link_to with do) within an interpolation for a helper that will be called many times, so i only want to have this code once in my project. But when i try to execute the code below i get the error "Unexpected keyword class, expecting keyword_do or '{' or '('" so i don't know how to do this or if it's possible. The link_to block is between some html code and it's concatenated with it, that's why i need the html_safe at the bottom.

def example_helper_method()
  example_string = ""
  example_string += "SOME HTML ..."
  example_string += "#{ link_to edit_foo_url(param1, param2, param3: 1) do }"
  example_string += "<button class='btn btn-small #{foo_method(1)}' type='button'>Example</button>"
  example_string += "#{end}"
  example_string += "SOME HTML ..."
  return example_string.html_safe
end

Here is where i am calling this method in the view

<%= example_helper_method() %>

Thanks :D


Solution

  • link_to returns a string so why do you need all the interpolation? You'd want to turn the second string inside-out and move the html_safe call but something like this should do the trick:

    def example_helper_method()
      example_string  = ''
      example_string += "SOME HTML ..."
      example_string += link_to edit_foo_url(param1, param2, param3: 1) do
        "<button class='btn btn-small #{foo_method(1)}' type='button'>Example</button>".html_safe
      end
      example_string + "SOME HTML..."
    end
    

    link_to should be returning something that is HTML-safe already so you don't need to html_safe what it returns. You do want an html_safe call inside the block as you're building HTML in a string. You may or may not need html_safe calls on the SOME HTML string depending on what's really there.