使用选项覆盖默认访问者

时间:2014-03-06 17:43:42

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

我正在使用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..."

也许这比Ruby更多Ruby,但是调用@article.title方法的title(options => {})会调用访问相关数据库表列值的Rails属性访问器吗?


更新(评论后)

由于在上面的代码中似乎默认访问者被覆盖,有没有办法为这些访问者提供选项以达到我想要的目的?如果是这样,怎么样?

2 个答案:

答案 0 :(得分:0)

@article.title #=> will call your method
@article.title(:parse => true) #=> will call your method

如果你正在寻找的话,红宝石中没有方法重载。

答案 1 :(得分:0)

仔细查看官方文档,我会看到代码分歧的地方。 定义方法时忘了“=”。

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

Foo.bar = 3 #=> 3

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

相关问题