Created
November 10, 2020 20:39
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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