Friday, May 6, 2011

Rails using named routes within helper (but with class methods)

Trying to use this method (gist of which is use self.method_name in the FunnyHelper, then call it as FunnyHelper.method_name in the view).

However this causes at least a couple of problems - view methods like h() and named routes get broken (they're ok with the module method def method_name but not within any class method def self.method_name).

Obviously I can avoid this by dropping the def self.method_name back to def method_name; anyone with any suggestions for how I can have my cake and eat it too?

From stackoverflow
  • If you really want to do this, you can use

    include ActionController::UrlWriter
    

    to get access to your named routes and

    # h is a private method 
    ActionController::Base.helpers.send :h, "<"
    

    for other view helpers. But I would not recommend it. In my opinion the design pattern that thoughtobt is suggesting here sucks and I would just use helper :blogs despite their complaint that it isn't explicit. That is true, sort of... but Rails in general and this part of Rails in particular is architected in a completely "non-explicit" way so trying to fight against that is going to be more trouble than it's worth, as you are discovering.

0 comments:

Post a Comment