On 1/20/06, dblack / wobblini.net <dblack / wobblini.net> wrote:
> Hi --
>
> On Sat, 21 Jan 2006, James Hughes wrote:
>
> > On 1/19/06, Paul Brannan <pbrannan / atdesk.com> wrote:
> >>
> >> You can also create a mixin and extend Foo::Bar with the mixin.  If you
> >> do this, instance methods in the mixin will be available as class
> >> methods in Foo::Bar and derived classes.
> >
> > Ok, I'm doing something like the following:
> >
> > module FooBarHelper
> >
> >  class << Foo::Bar
> >     # some instance methods, which reference class vars from Foo::Bar
> >  end
> > end
> >
> > Then, in classes A and B I do "include FooBarHelper".  When I run this
> > I get "uninitialized class variable" errors for the Foo::Bar's class
> > vars.
> >
> > So, to state my question again, how can I extend the functionality of
> > the Foo::Bar library (short of hacking it's source directly), while
> > still maintaining access to the class variables defined in Foo::Bar?
> > Is this even possible?
>
> Does this help at all?
>
>    module Foo
>      class Bar
>        def self.meth
>          puts "Class method of Foo::Bar"
>        end
>        X = "Constant of Foo::Bar"
>      end
>    end
>
>    module Needed
>      def self.const_missing(c)
>        Foo::Bar.const_get(c)
>      end
>      def needed_method
>        puts "This is a needed method"
>        puts X
>      end
>    end
>
>    class A < Foo::Bar
>      extend Needed
>    end
>
>    puts A::X
>    A.meth
>    A.needed_method

Hmm. Not sure yet. While I try to wrap my head around what's going on
with the const_missing and const_get magic above, here is the short
script I wrote to try and simulate the real-world problem I'm trying
to solve. Note that the derived class  (A) is trying to access a class
variable and not a constant as in your example.

module Foo
  class Bar
    @@classvar = "Boo!"
  end
end

module FooBarHelper
  class << Foo::Bar
    def amethod
      puts  @@classvar
    end
  end
end

class A < Foo::Bar
  include FooBarHelper
  extend FooBarHelper
end

A.amethod

**end script**

This prints
./foo.rb:12:in `amethod': uninitialized class variable @@classvar in
FooBarHelper (NameError)
	from ./foo.rb:22

--
James Hughes
Web application developer
Centre for Health Services and Policy Research
Vancouver, BC