Skip to content

Instantly share code, notes, and snippets.

@fhwang
Created February 23, 2010 16:03

Revisions

  1. fhwang created this gist Feb 23, 2010.
    18 changes: 18 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    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'