Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails view Helper function and the link_to function

I am trying to create a helper function (eg in application_helper.rb) that generates a link_to based on parameters passed in to the helper function. If I were putting the link in an ERB file it would be of the format:

<%= link_to 'Some Text', { :controller => 'a_controller', :action => 'an_action' } %>

In the helper function, the Text, Controller and Action are all passed in or calculated. The code in the helper function is:

params = "{ :controller => '#{controller}', :action => '#{action_to_take}'}"
html   = "#{link_to some_text, params }<p />"
return html

The link that is generated has the correct text, however the parameters are literally the contents of the params string.

How can I get the params string to be evaluated (as it is in an ERB file)?

like image 671
Paul Avatar asked Dec 28 '22 02:12

Paul


1 Answers

I think you have things overcomplicated in your head. Unless you're trying to do something very odd (and inadvisable) this would work:

def link_helper text, controller, action
  link_to text, :controller => controller, :action => action
end

Although, as you can see it's not worth making it a helper - it's barely any more simple than the functionality it's wrapping, and much less flexible.

The link_to helper returns a string, so it's very simple to use in the way you want:

def link_helper text
  # some helper logic:
  controller = @controller || "pages"
  action     = @action     || "index"

  # create the html string:
  html = "A link to the #{controller}##{action} action:"
  html << link_to(text, :controller => controller, :action => action)
  html # ruby does not require explicit returns
end
like image 175
gunn Avatar answered Jan 12 '23 12:01

gunn