Skip to content

Instantly share code, notes, and snippets.

@mattdenner
Created April 5, 2010 13:57
Show Gist options
  • Save mattdenner/356359 to your computer and use it in GitHub Desktop.
Save mattdenner/356359 to your computer and use it in GitHub Desktop.
Immutable after construction pattern
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
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