DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Access To View-helpers In Model (with Inner Class)

06.22.2009
| 10849 views |
  • submit to reddit
        // access to view-helpers in model code can be accomplished by a simple include
// example: get accesss to ActionView::Helpers::TextHelper.truncate in a model
class Glosentry < ActiveRecord::Base
  include ActionView::Helpers::TextHelper
  
  def short_explanation(len=20) 
    truncate(self.explanation, len)
  end
end

// but the semantic is wrong becaus the model is not a helper object.
// it only should have access to the helper
// so using a helper object and moving the include to an inner class is cleaner 
class Glosentry < ActiveRecord::Base
  class GlosentryHelper
    include ActionView::Helpers::TextHelper
  end
  
  def helper
    @h ||= GlosentryHelper.new
  end
  
  def short_explanation(len=20) 
    helper.truncate(self.explanation, len)
  end
end

// with method_missing the need to explicitly call the helper object could be eliminated.
  ..
  def method_missing(*args, &block)
    @h.send(*args, &block)
  end

// But then the the helper object would be obscured. That's why I prefer to keep the code as it is.