这是我想要做的一个简化的例子。
假设我有一个对象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)但是,不允许将不是Person对象实际属性的值传递给make。有没有一种方法可以将任意对象传递给蓝图?
发布于 2011-10-22 05:40:42
您可以为birthdate创建一个attr_accessor,但这似乎有点傻。您可能只需要定义一个单独的方法:
def Person.make_from_birthdate(attributes)
birthdate = attributes.delete :birthdate
Person.make attributes.merge(:age => Time.now - birthdate)
end然而,存储年龄通常是一种糟糕的做法。由于年龄随时间变化,而出生日期不随时间变化,您通常希望将生日存储在数据库中,并根据需要计算年龄(基于今天的日期)。
https://stackoverflow.com/questions/7855435
复制相似问题