在rails中,默认的getter和setter会是什么样子?

我知道我可以编写attr_accessor:tag_list来为Rails中的对象创建一个虚拟属性tag_list。 这允许在对象的表单中存在tag_list属性。

如果我使用attr_accessor:tag_list,我可以在模型中对tag_list执行操作以从表单中提取和操作数据。

我想知道的是,如何编写一个完全复制attr_accessor默认function的getter和setter,而不是编写attr_accessor。 例如:

def tag_list #what goes here end 

仅供参考我尝试过

  def tag_list @tag_list end 

这不起作用。

attr_accessor是一个内置的Ruby方法,在ActiveRecord上下文中没有特殊含义。 attr_accessor :tag_list基本上等同于这段代码:

 # getter def tag_list @tag_list end # setter def tag_list=(val) @tag_list = val end 

但是,在ActiveRecord模型中,可能需要这样的东西:

 def tag_list self[:tag_list] end def tag_list=(val) self[:tag_list] = val end 

稍有不同:使用第一种方法, obj[:tag_list]不会使用与getter和setter相同的存储空间。 对于后者,它确实如此。

getter / setter概念的解释

在Ruby中,以下两行代码是等效的

 thing.blabla thing.blabla() 

两者都调用对象的方法blabla并计算到该方法中计算的最后一个表达式。 这意味着,在上述getter方法的情况下,您也不需要return语句,因为该方法只返回方法中的最后一个表达式( @tag_list ,实例变量的值)。

此外,这两行代码是等效的:

 thing.blabla=("abc") thing.blabla = "abc" 

两者都调用对象的方法blabla= 。 带有=字符的特殊名称可以像任何其他方法名称一样使用。

事实上, 属性 (有时称为属性)实际上是普通方法,您还可以在返回或接受它们之前使用某些特殊逻辑转换为值。 例:

 def price_in_dollar @price_in_euro * 0.78597815 end def price_in_dollar=(val) @price_in_euro = val / 0.78597815 end 

使用ActiveRecord时,这是等效的getter和setter版本:

 def tag_list read_attribute(:tag_list) end def tag_list=(val) write_attribute(:tag_list, val) end 

这是你在寻找什么?

 Notice the code below is in the [Helpers] path. Helpers are now included for all [Controllers] to work from when instantiated. module SettergettersHelper #TODO Wayne mattr_accessor :nameport #TODO Wayne Mattingly the code below was replaced BY ABOVE #TODO and not depricatable RAILS 4.2.3 # def nameport # @nameport # end # def nameport=(nameport) # @nameport = nameport #end end *Getter from Accounts Controller:* def index @portfolio_name = nameport end *Setter from Portfolio Controller:* def show @portfolio_name = @portfolio_name.portfolio_name #from database call SettergettersHelper.nameport = @portfolio_name # set attribute end