From: "David A. Black" Date: 2008-05-02T10:44:16+09:00 Subject: Re: DSL - class-level methods that affect instances Hi -- On Fri, 2 May 2008, Daniel Waite wrote: > I'm having a problem of design. I've tried a few configurations of class > collaboration and responsibility, but they all end up feeling messy. > > I'm looking at these (either or, my original attempt was with a module, > but attr_accessor *looks* like it does what I want): > > class C < Translator::Base > translate 'this', :to => 'that' > end > > class C > include Translator > translate 'this', :to => 'that' > end > > With the expectation that... > > c = C.new > c.translations > > Would yield a hash of the from and to values. > > I have no idea how to break the barrier between class and instance. :( I'd say: don't think of it as any more of a barrier than exists between any other two objects. Every object, including a class object, has the right to maintain state, and to decide what it will and will not expose. There's no privileged relationship between c and i just because i is an instance of c. (I know that sounds kind of doctrinaire, but I like to lay it on thick since it usually takes some doing to chip away at the presumptive class/instance special relationship :-) As Ken suggested, class variables break through the class/instance boundaries. That's one of the reasons I don't like them :-) You can certainly do it that way; I'll also show you another possibility, based on engineering all the objects concerned so that they query each other where necessary: module Translator attr_reader :translations def translate(target, actions) @translations ||= [] @translations.push("Translating #{target} to #{actions[:to]}") end end class C extend Translator def translations self.class.translations end translate "this", :to => "that" end p C.new.translations # ["Translating this to that"] David -- Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin INTRO TO RAILS June 24-27 London (Skills Matter) See http://www.rubypal.com for details and updates!