Skip to content

Instantly share code, notes, and snippets.

@bolpin
Created November 10, 2020 20:39
Show Gist options
  • Save bolpin/d2fb14f9cc97632aa73cf65bd710d5e0 to your computer and use it in GitHub Desktop.
Save bolpin/d2fb14f9cc97632aa73cf65bd710d5e0 to your computer and use it in GitHub Desktop.
Build object attributes using a hash and a related object to build that hash
require 'active_model'
require 'active_support'
class Dog
include ActiveModel::Model
attr_accessor :name, :age
def self.build(attr_hash)
Dog.new DogBuilder.attributes(attr_hash)
end
end
class DogBuilder
def self.attributes(hash)
{
name: hash[:name],
age: calculate_age(hash)
}
end
def self.calculate_age(hash)
# do a calculation based on hash[:birthday], for example, here
Time.now.year - hash[:birthyear]
end
end
puts (Dog.build({name: "Lucy", birthyear: 2010})).inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment