Created
April 5, 2010 13:57
-
-
Save mattdenner/356359 to your computer and use it in GitHub Desktop.
Immutable after construction pattern
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
class ConstructorHelper | |
class << self | |
def construct(target, writers_for = target.instance_variables, &block) | |
self.new(target, writers_for).instance_eval(&block) if block_given? | |
end | |
end | |
def initialize(target, writers_for = target.instance_variables) | |
writers_for.each do |variable| | |
self.class.send(:define_method, :"#{ variable.to_s.sub(/^:?@/, '') }=") do |v| | |
target.instance_variable_set(variable, v) | |
end | |
end | |
end | |
end |
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
class ImmutableAfterConstruction | |
attr_reader :variable1 | |
attr_reader :variable2 | |
def initialize(&block) | |
@variable1, @variable2 = 'foo', 'bar' | |
ConstructorHelper.construct(self) | |
end | |
end | |
value = ImmutableAfterConstruction.new do | |
self.variable1 = 'Hello' | |
self.variable2 = 'World!' | |
end | |
puts value.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment