Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

regex - Remove all html tags from attributes in rails

I have a Project model and it has some text attributes, one is summary. I have some projects that have html tags in the summary and I want to convert that to plain text. I have this method that has a regex that will remove all html tags.

def strip_html_comments_on_data
  self.attributes.each{|key,value| value.to_s.gsub!(/(<[^>]+>|&nbsp;|
|
)/,"")}
end

I also have a before_save filter

before_save :strip_html_comments_on_data

The problem is that the html tags are still there after saving the project. What am I missing?

And, is there a really easy way to have that method called in all the models?

Thanks,

Nicolás Hock Isaza

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

untested

include ActionView::Helpers::SanitizeHelper

def foo
  sanitized_output = sanitize(html_input)
end

where html_input is a string containing HTML tags.

EDIT

You can strip all tags by passing :tags=>[] as an option:

plain_text = sanitize(html_input, :tags=>[])

Although reading the docs I see there is a better method:

plain_text = strip_tags(html_input)

Then make it into a before filter per smotchkiss and you're good to go.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...