Helper Methods (MVC Frameworks)
From Dev411: The Code Wiki
Often times you'll want to have app-specific helper/utility methods that don't fit neatly in M V or C. The frameworks have various ways of helping you with this:
Examples By Framework
Catalyst
Catalyst can load helper methods in the Controller's auto method. Simply use the Root controller for app-wide methods and the specific Controller for controller-specific methods.
In the app-wide controller: myapp/lib/MyApp/Controller/Root.pm
package MyApp::Controller::Root;
sub auto : Private {
my ($self, $c) = @_;
$c->stash->{fmt_currency} = sub { sprintf('%s%0.2f', @_); }
}
1;
In the template: myapp/templates/products.tt
[%- FOREACH product=products -%]
<tr>
<td>[% product.name %]</td>
<td>[% fmt_currency('$',product.unit_price) %]</td>
</tr>
[%- END -%]
Ruby on Rails
Rails has the concept of a helper module to store these methods. Simply create a module under app/helpers. When the right name is used, the module is automatically loaded and the methods are globally available in your view. For controller-specific methods, use app/helpers/<controller_name>_helper.rb and for app-wide helpers use app/helpers/application_helper.rb.
In the app-wide helper: app/helpers/application_helper.rb
module ApplicationHelper
def fmt_currency(symbol, amt)
sprintf("%s%0.2f", symbol, amt)
end
end
In the template: app/view/products.rhtml
<% for product in @products -%>
<tr>
<td><%= product.name %></td>
<td><%= fmt_currency('$',product.unit_price)</td>
</tr>
<% end -%>
