Skip to content

Instantly share code, notes, and snippets.

@fhwang
Created February 23, 2010 16:03
Show Gist options
  • Save fhwang/312337 to your computer and use it in GitHub Desktop.
Save fhwang/312337 to your computer and use it in GitHub Desktop.
def read_only_struct(*attrs)
c = Class.new
eval_me = <<-CLASS_EVAL_OH_NOES
def initialize(#{attrs.map { |sym| sym.to_s }.join(', ')})
#{attrs.map { |attr| "@#{attr} = #{attr}" }.join("\n")}
end
attr_reader #{attrs.map { |sym| ":#{sym.to_s}" }.join(', ')}
CLASS_EVAL_OH_NOES
c.class_eval eval_me
c
end
Foo = read_only_struct :bar
f = Foo.new 'BAR'
puts "Getter says: #{f.bar}"
puts "Setter should raise an exception:"
f.bar = 'BAZ'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment