【发布时间】:2014-04-09 12:49:46
【问题描述】:
我正在使用 Ruby on Rails 4,我想知道当我覆盖默认访问器时可能会遇到哪些陷阱。 Rails 的Official Documentation 说(在最初的几行中):
将给定的 Active Record 类绑定到某个特定的映射 数据库表会在最常见的情况下自动发生,但可以 被不常见的覆盖。
更多,在该文档中有“覆盖默认访问器”部分,这让我认为我可以毫无问题地做到这一点。你怎么看?
就我而言,我想覆盖属性访问器以提供一些选项,如下所示:
# Given my Article model has :title and :content attributes
# Then I would like to overwrite accessors providing options this way:
class Article < ActiveRecord::Base
def title(options = {})
# Some logic...
end
def content(options = {})
# Some logic...
end
end
# So that I can run
@article.title # => "Sample Title"
@article.title(:parse => true) # => "Sample *Title*"
@article.content # => "Sample description very long text"
@article.content(:length => :short) # => "Sample description..."
也许这比 Rails 更 Ruby,但会是 @article.title 调用 title(options => {}) 方法,或者它会调用 Rails 属性访问器来访问相关的数据库表列值?
更新(评论后)
由于似乎在上面的代码中默认访问器没有被覆盖,有没有办法为这些访问器提供选项以便达到我正在寻找的东西?如果有,怎么做?
【问题讨论】:
-
可以根据条件选项格式化返回的模型。
-
您这样做不会覆盖 attr 访问器。
-
@wurde 你能指出一些我可以了解更多信息的资源吗?
-
@wurde 你能告诉我一些我可以了解更多的资源吗?我也更新了问题。
-
示例架构是什么样的?
标签: ruby-on-rails ruby methods overwrite accessor