Created
February 23, 2010 16:03
-
-
Save fhwang/312337 to your computer and use it in GitHub Desktop.
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
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