Passing in non-attribute values to Machinist blueprint

261 Views Asked by At

This is a simplified example of what I'm trying to do...

Suppose I had an object Person:

Person.blueprint do
  name
  age
end

I want to be able to do something like this:

Person.blueprint(:from_birthdate) do
  name
  age { Time.now - birthdate }
end

Person.make(:from_birthdate, :birthdate => 5.years.ago)

However, I'm not allowed to pass values into make that aren't actual attributes of the Person object. Is there a way to pass in an arbitrary object to the blueprint?

1

There are 1 best solutions below

2
On

You could make an attr_accessor for birthdate, but that seems a little silly. You might need to just define a separate method:

def Person.make_from_birthdate(attributes)
  birthdate = attributes.delete :birthdate
  Person.make attributes.merge(:age => Time.now - birthdate)
end

However, storing age is generally a bad practice. Since age changes with time and birthdate doesn't, you'd normally want to store the birthdate in the DB and calculate age (based on today's date) as necessary.