Access To View-helpers In Model (with Inner Class)
Join the DZone community and get the full member experience.Join For Free
// 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.
Opinions expressed by DZone contributors are their own.