Over a million developers have joined DZone.

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

·
// 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.
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}