这是我正在尝试做的一个简化示例......
假设我有一个对象Person
:
Person.blueprint do
name
age
end
我希望能够做到这样的事情:
Person.blueprint(:from_birthdate) do
name
age { Time.now - birthdate }
end
Person.make(:from_birthdate, :birthdate => 5.years.ago)
但是,我不允许将值传递给make
,而不是Person
对象的实际属性。有没有办法将任意对象传递给蓝图?
答案 0 :(得分:0)
您可以为attr_accessor
制作birthdate
,但这看起来有点傻。您可能只需要定义一个单独的方法:
def Person.make_from_birthdate(attributes)
birthdate = attributes.delete :birthdate
Person.make attributes.merge(:age => Time.now - birthdate)
end
但是,存储年龄通常是一种不好的做法。由于年龄随时间变化而生日变化没有,您通常希望将出生日期存储在数据库中并根据需要计算年龄(根据今天的日期)。