装饰在轨属性

装饰在轨属性

问题描述:

我有一个模式,每次我访问时间名称属性名称属性,我希望 name.capitalize 被返回。

I have a name attribute on a Person model and every time I access the name attribute, I want name.capitalize to be returned.

执行以下操作里面的模式是行不通的,

Doing the following inside the model won't work,

def name
  name.capitalize
end

那么,什么是另类?

so what is the alternative?

我建议你创建你的自定义格式的辅助方法。

I suggest you to create a secondary method with your custom formatters.

class Person

  def formatted_name
    name.capitalize
  end

end

这是一个更好的解决方案,覆盖默认实现,因为setter和getter方法​​可以保存记录到数据库中名为更新时/写/比较。 我记得有一次,当我改写的属性和记录保存每次的默认实现,该属性进行了更新与格式化的值。

This is a better solution compared with overwriting the default implementation because setter and getters might called when updating/writing/saving the record to the database. I remember once when I overwrote the default implementation of an attribute and each time a record was saved, the attribute was updated with the formatted value.

如果你想跟随这种方式,您可以使用 alias_method_chain 或采取继承的优势,包括外部模块。

If you want to follow this way you can use alias_method_chain or take advantage of inheritance including an external module.

class Person

  def name_with_formatter
    name_without_formatter.capitalize
  end
  alias_method_chain :name, :formatter

end

你也可以覆盖的名字,并呼吁 read_attribute(:名称)。从您的自定义方法中

Also you can overwrite name and call read_attribute(:name) from within your custom method.

def name
  read_attribute(:name).capitalize
end

def name
  self[:name].capitalize
end

此外,不这样做。来吧,创建一个自定义的方法。

Again, don't do this. Go ahead and create a custom method.