[MacRuby-devel] re-implemention of attr_accessor and valueForKey:

kyossi kyossi212 at gmail.com
Thu Mar 10 04:59:46 PST 2011


Hi,

I'm plan to  add some functionality to existing attr_accessor.
I've started with re-implement attr_accessor with same functionality,
but when I implement it by define_method, it failed with Segmentation
fault when I call valueForKey(:key).

Am i doing wrong with class Base2??,

The Code is

#utility
class String
  #upcase first char. "foo".upcaseFirstChar => "Foo"
	def upcaseFirstChar
		self[0].upcase + self[-self.size+1, self.size-1]
	end
end

#implement of my_attr_accessor with evaluate string. works fine
class Base
    def self.my_attr_accessor(sym)
      class_eval %{
          def #{sym}
            @#{sym}
          end

          def set#{sym.to_s.upcaseFirstChar}(val)
            @#{sym} = val
          end
      }
    end
end

class MyClass < Base
  my_attr_accessor :foo
end


obj = MyClass.new
obj.setFoo(3)
p obj.foo   #=>3
p obj.valueForKey(:foo) #=>3

#another implement of my_attr_accessor
class Base2
  def self.my_attr_accessor(sym)
        define_method(sym) do
            instance_variable_get("@#{sym}")
        end

        define_method("set#{sym.to_s.upcaseFirstChar}") do |val|
            instance_variable_set("@#{sym}", val)
        end
  end
end

class MyClass2 < Base2
    my_attr_accessor :foo
end

obj2 = MyClass2.new
obj2.setFoo(7)
p obj2.foo               #=>7
p obj2.valueForKey(:foo) #=> Segmentation fault


=====================
$ macruby my_attr_accessor.rb
3
3
7
Segmentation fault


More information about the MacRuby-devel mailing list