如何为Ruby中的实例的属性定义方法?将方法添加到Ruby中的属性
假设我们有一个名为HtmlSnippet
的类,它扩展了ActiveRecord :: Base of Rails,并且有一个属性content
。而且,我想为它定义一个方法replace_url_to_anchor_tag!
,并按以下方式调用它:
html_snippet = HtmlSnippet.find(1)
html_snippet.content = "Link to http://stackoverflow.com"
html_snippet.content.replace_url_to_anchor_tag!
# => "Link to <a href='http://stackoverflow.com'>http://stackoverflow.com</a>"
# app/models/html_snippet.rb
class HtmlSnippet < ActiveRecord::Base
# I expected this bit to do what I want but not
class << @content
def replace_url_to_anchor_tag!
matching = self.match(/(https?:\/\/[\S]+)/)
"<a href='#{matching[0]}'/>#{matching[0]}</a>"
end
end
end
由于content
是String类的一个实例,所以重新定义String类是一个选项。但我不喜欢这样做,因为它覆盖了所有String实例的行为;
class HtmlSnippet < ActiveRecord::Base
class String
def replace_url_to_anchor_tag!
...
end
end
end
有什么建议吗?
单身是你想要的。 – oldergod
哎呀,我总是说评论谢谢你,但不是在Stackoverflow中的任何操作。我会这样做 – suzukimilanpaak
@oldergod你能给我一个样本吗? – suzukimilanpaak