24

I'm writing a ruby-on-rails library module:

module Facets

  class Facet
    attr_accessor :name, :display_name, :category, :group, :special

    ...

    URI = {:controller => 'wiki', :action => 'plants'}
    SEARCH = {:status => WikiLink::CURRENT}

    #Parameters is an hash of {:field => "1"} values
    def render_for_search(parameters)
    result = link_to(display_name, URI.merge(parameters).merge({name => "1"}))
    count = WikiPlant.count(:conditions => (SEARCH.merge(parameters.merge({name => "1"}))))
    result << "(#{count})"
    end
  end

  ...

end

when I call render_for_search I get the error

undefined method 'link_to'

I've tried requiring url_helper directly but can't figure out what's going wrong.

Mike Sutton
  • 4,191
  • 4
  • 29
  • 42

3 Answers3

29

Try this:

ActionController::Base.helpers.link_to
khelll
  • 23,590
  • 15
  • 91
  • 109
25

This is because, ActionView urlhelpers are only available to the Views, not in your lib directory.

the link_to method is found in the ActionView::Helpers::UrlHelper module, plus you wou

so try this.

 class Facet
   include ActionView::Helpers::UrlHelper
...
end
Rishav Rastogi
  • 15,484
  • 3
  • 42
  • 47
  • I can't say for sure, but my view seemed to break when I do this. Not sure why, but I suspect that this causes some tricky things to happen. – bchurchill Jan 31 '13 at 08:07
  • 2
    in Rails 3.2, this doesn't work. This one does: ActionController::Base.helpers.link_to – GregT Feb 08 '13 at 06:57
  • I answered this in 2009, I don't think there was a stable version of Rails 3 ( no 3.1, no 3.2 ) out at the time. – Rishav Rastogi Feb 11 '13 at 06:16
5

Simply including the helper doesn't get you much further. The helpers assume that they are in the context of a request, so that they can read out the domain name and so on.

Do it the other way around; include your modules in the application helper, or something like that.

# lib/my_custom_helper.rb
module MyCustomHelper
  def do_stuff
    # use link_to and so on
  end
end

# app/helpers/application_helper.rb
module ApplicationHelper
  include MyCustomHelper
end
August Lilleaas
  • 54,010
  • 13
  • 102
  • 111