Saturday, July 27, 2013

Rails helpers

I have a task to fix a conversion bug in a Rails app (2.12), then I found out that there are copies of the same method in everywhere - that's so bad. So I decided to clean it up by making a common helper that provides common methods for global usage, like below example:

 module UtilsHelper  
  def convertValue(value)  
   return "0" if value.nil?  
   return (value*2).to_s  
  end  
 end  

Google around, finally get it to run:

In the Controller, use helper method to include UtilsHelper to use in the template:
 class HomeController < ApplicationController  
  helper UtilsHelper #include won't work  
 end  

index.rhtml template:
 <%= convertValue(row.value) %>  

But in a class, we must use include method
 class Data  
  include UtilsHelper #require won't work  
  @value = nil  
  def to_s  
   return convertValue(@value)  
  end  
 end  

No comments:

Post a Comment