thiebo
thiebo

Reputation: 1435

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 %>

Upvotes: 1

Views: 59

Answers (2)

Bryan Ash
Bryan Ash

Reputation: 4479

Monkey patching String is not the only way. Adding methods to a core class like String is a slippery slope. You may decide one day that you want Books to have a nicename too, only with some different formatting for presentation.

You could wrap the object in a presenter class for use in the view, something like:

class AuthorController
  def show
    @author = AuthorPresenter.new(author_from_params)
  end
end

class AuthorPresenter
  def initialize(author)
    @author = author
  end

  def firstname
    nice(@author.firstname)
  end

  def nice(name)
    name.gsub ...
  end
end

Then in your view, you would use the @author

@author.firstname

This way you keep the presentation logic out of your model, and don't have to globally add methods to String.

Of course, if you really want to use author.firstname.nicename you could wrap the AuthorPresenter#firstname in a presenter:

class AuthorPresenter
  def initialize(author)
    @author = author
  end

  def firstname
    NamePresenter.new(@author.firstname)
  end
end

class NamePresenter
  def initialize(name)
    @name = name
  end

  def nicename
    @name.gsub ...
  end
end

Upvotes: 1

Mikhail Nikalyukin
Mikhail Nikalyukin

Reputation: 11967

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.

Upvotes: 2

Related Questions