【问题标题】:Overwriting default accessors with options使用选项覆盖默认访问器
【发布时间】: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 =&gt; {}) 方法,或者它会调用 Rails 属性访问器来访问相关的数据库表列值?


更新(评论后)

由于似乎在上面的代码中默认访问器没有被覆盖,有没有办法为这些访问器提供选项以便达到我正在寻找的东西?如果有,怎么做?

【问题讨论】:

  • 可以根据条件选项格式化返回的模型。
  • 您这样做不会覆盖 attr 访问器。
  • @wurde 你能指出一些我可以了解更多信息的资源吗?
  • @wurde 你能告诉我一些我可以了解更多的资源吗?我也更新了问题。
  • 示例架构是什么样的?

标签: ruby-on-rails ruby methods overwrite accessor


【解决方案1】:

仔细查看官方文档,我发现您的代码存在分歧。 您在定义方法时忘记了“=”。

class Foo < ActiveRecord::Base
  def self.bar=(value)
    @foo = value
    return 'OK'
  end
end

Foo.bar = 3 #=> 3

警告:永远不要依赖赋值方法中发生的任何事情, (例如,在上面示例中的条件语句中)

【讨论】:

【解决方案2】:
@article.title #=> will call your method
@article.title(:parse => true) #=> will call your method

如果您正在寻找,ruby 中没有方法重载。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-22
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多