From: Daniel Waite Date: 2008-05-02T09:55:45+09:00 Subject: Re: DSL - class-level methods that affect instances Ken Bloom wrote: > On Thu, 01 May 2008 18:07:11 -0500, Daniel Waite wrote: > >> class C >> >> I have no idea how to break the barrier between class and instance. :( > > Use class variables (the @@ variety). > > class Translator::Base > def self.translate word, params > @@translations ||= {} > @@translations[word]=params[:to] > end > def translations > @@translations ||= {} > end > end > > class C < Translator::Base > translate 'a', :to => 'b' > translate 'c', :to => 'd' > end > > C.new.translations #=> {"a"=>"b", "c"=>"d"} That works! Except it shares translations across all subclasses. module Translator class Base def self.translate word, params @@translations ||= {} @@translations[word]=params[:to] end def translations @@translations ||= {} end end end class C < Translator::Base translate 'a', :to => 'b' translate 'c', :to => 'd' end class D < Translator::Base translate 'this', :to => 'that' end irb(main):028:0> c = C.new => # irb(main):029:0> c.translations => {"a"=>"b", "c"=>"d", "this"=>"that"} While I understand the behavior, its undesirable. I'm going to dust off Ruby for Rails... -- Posted via http://www.ruby-forum.com/.