thiebo thiebo - 4 years ago 70
Ruby Question

Formatting helper_methods for use in view

I have this in ApplicationController:

class ApplicationController < ActionController::Base

helper_method :nicename

def nicename(name)
# all entries in the DB are in lower case and need to be formated
# for dislay in views:
name.gsub(/[\s]/,'-').split("-").map {|m|m.capitalize}.join('-')
end
end


In my view I invoke the method nicename like so:

<% l.authors.each do |m| %>
<%= nicename(m.firstname) %>


How should I write the method so I can do this in the view:

<%= m.firstname.nicename %>

Answer Source

The only way to do it as you want, without passing an argument, would require extension on the String class. That's assuming you are always calling method on strings. Judging from your code it holds true. Here is an example for you:

lib/core_ext/string.rb

class String
  def nicename
    # all entries in the DB are in lower case and need to be formated
    # for dislay in views:
    self.gsub(/[\s]/,'-').split("-").map {|m|m.capitalize}.join('-')
  end
end

Make sure to reload your server and check that class is loaded. Hope it fit your needs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download