【发布时间】:2012-09-12 08:03:08
【问题描述】:
如何在 Ruby 中为实例的属性定义方法?
假设我们有一个名为 HtmlSnippet 的类,它扩展了 Rails 的 ActiveRecord::Base 并有一个属性 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
有什么建议吗?
【问题讨论】:
-
哎呀,我总是通过评论说谢谢,而不是通过 Stackoverflow 中的任何操作。这次我会做的
-
@oldergod 你能给我一个样品吗?
标签: ruby-on-rails ruby methods metaprogramming