---
title: "如何在model里使用view helper"
author: "夜鸣猪"
date: "2012-03-28T07:58:43Z"
tags: []
categories: ["编程语言"]
slug: "model-view-helper"
draft: false
lastmod: "2012-03-28T07:58:43Z"
id: 1465585
url: "https://hlee.iteye.com/blog/1465585"
---

```ruby

class Glosentry < ActiveRecord::Base
  include ActionView::Helpers::TextHelper
  
  def short_explanation(len=20) 
    truncate(self.explanation, len)
  end
end

```

上面的方法虽然可以用但，逻辑上并不好，因为Model不是helper，所以可以用下面的方法


```ruby

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

```



```ruby

  def method_missing(*args, &block)
    @h.send(*args, &block)
  end

```