开发者

how to use strip_tags and truncate inside my Model.rb?

strip_tag开发者_如何学Cs works for me in my view page, but not in my model (i'm using it in a before_save function)


You can also access helpers in your models like this:

ActionController::Base.helpers.strip_tags(text)


ActionView::Base.full_sanitizer.sanitize(your_html_string)

This will work for you. Or you can define a helper like:

def strip_html_tags(string)
    ActionView::Base.full_sanitizer.sanitize(string)
end

And then use this like:

strip_html_tags(your_html_string)

To remove some specific tags pass additional parameters. Source: Sanitize Rails API Dock


So, I didn't like any of these solutions as i'd rather keep view functionality out of my models. So instead I used a decorator (like https://github.com/drapergem/draper) and was then able to use the helper method short cut h.strip_tags.


The poor man's truncator:

my_string[0, 145] 

It will work in a model without having to call helper methods from ActionController::Base. It won't add the elipsis for you, but that's probably easy to fix...


strip_tags is a helper method and helpers aren't available inside models as a rule.

You might want to look at using something like the sanitize gem instead

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜