Created
February 17, 2015 21:55
-
-
Save stefanoc/c3ebb922465ee69c89e2 to your computer and use it in GitHub Desktop.
Computed attributes
This file contains hidden or 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
module ComputedAttributes | |
module ClassMethods | |
def compute(name, components, &block) | |
getter = -> do | |
value = instance_variable_get("@_#{name}") | |
unless value | |
value = instance_exec(&block) | |
instance_variable_set("@_#{name}", value) | |
end | |
value | |
end | |
define_method(name, &getter) | |
components.each do |attribute| | |
setter = ->(value) do | |
instance_variable_set("@_#{name}", nil) | |
super(value) | |
end | |
define_method("#{attribute}=", &setter) | |
end | |
end | |
end | |
end | |
class Person < Struct.new(:first_name, :last_name) | |
extend ComputedAttributes::ClassMethods | |
compute :full_name, [:first_name, :last_name] { "#{first_name} #{last_name}" } | |
end | |
me = Person.new('John', 'Doe') | |
puts me.full_name | |
me.first_name = 'Jane' | |
puts me.full_name | |
me.last_name = 'Smith' | |
puts me.full_name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment