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

Thibault Martin-Lagardette thibault.ml at gmail.com
Thu Mar 10 13:40:11 PST 2011


Hi,

After fiddling a little bit with the code, I could not find the exact issue, but could reduce the code a lot.
For the sake of it, I opened a Trac ticket with the reduced code: https://www.macruby.org/trac/ticket/1188

Cheers,
-- 
Thibault Martin-Lagardette

On Thursday, March 10, 2011 at 13:59, kyossi wrote: 
> 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
> _______________________________________________
> MacRuby-devel mailing list
> MacRuby-devel at lists.macosforge.org
> http://lists.macosforge.org/mailman/listinfo.cgi/macruby-devel
> 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.macosforge.org/pipermail/macruby-devel/attachments/20110310/921b5dd1/attachment-0001.html>


More information about the MacRuby-devel mailing list