我正在使用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更紅寶石,但將是@article.title
調用title(options => {})
方法或它會調用訪問相關數據庫表列值的Rails屬性訪問器?
更新(後評論)
因爲它似乎在上面的代碼中默認的訪問器是不覆蓋,有沒有爲那些訪問器選項,以便達到我有什麼辦法尋找?如果是這樣,怎麼樣?
格式化根據條件選擇你返回模型是可能的。 – wurde
您不覆蓋attr訪問器這樣做。 – wurde
@wurde你能否指點我可以瞭解更多的資源? – user502052