开发者

Cleanup ActiveRecord field

开发者 https://www.devze.com 2022-12-25 23:31 出处:网络
I have model Article it has field title with some text that may contain some \"magic\" patterns. In some cases i need to process text in title and other cases i don\'t, but in last case i need to get

I have model Article it has field title with some text that may contain some "magic" patterns. In some cases i need to process text in title and other cases i don't, but in last case i need to get string w/o that patterns.

For example i have title value like "Something **very** interesting" and when i call @article.title i n开发者_如何学Goeed to get cleaned up string like "Something very interesting", but when i call @article.title_raw i need get original string.

The problem also is that i have working application and i cannt do "revolution" but what way to go...

--

Excuse me for my bad English.


you can use regexp

@article.title.gsub(/pattern1|pattern2|pattern3|.../, '')

IE

@article.title
#=> "Some _cool_ **text**"
@article.title.gsub(/**|_/, "")
#=> "Some cool text"


I would have defined methods on the Article model called "title_raw" and "title" and in those methods do the alterations needed to the value and return them in those functions. Something like this:

def title title.gsub(/**|_/, "") end

def title_raw self.title end

0

精彩评论

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