Created
July 13, 2016 21:34
-
-
Save maxwells/c54b7d01a1b1d2bd9b6c771dcd6a808f to your computer and use it in GitHub Desktop.
~immutable structs
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 ImmutableStruct | |
module PropSetter | |
attr_reader :props | |
def use_struct_props(*props) | |
attr_reader *props | |
@props = props | |
end | |
end | |
def self.build(*fields) | |
Class.new do | |
extend PropSetter | |
use_struct_props *fields | |
def initialize(values) | |
self.class.props.each do |field| | |
instance_variable_set("@#{field}", values.fetch(field)) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment