S
Sebastian
I'm trying to find a way to declare class variables in a module that
can be mixed into class methods and retain scope for only that
particular class instead of being defacto module-variables.
Here's a simplified example (albeit somewhat silly) of what i'm trying to do:
module Foo
module Bar
#...some instance methods
def self.included(klass)
klass.extend(BarClassMethods)
end
end
module BarClassMethods
def greeting
@@greeting ||= self.determine_greeting
end
def determine_greeting
hello
end
end
end
class A
include Foo::Bar
def self.hello
"hello from A"
end
end
class B
include Foo::Bar
def self.hello
"hello from B"
end
end
puts A.greeting
#=> 'hello from A'
puts B.greeting
#=> 'hello from A'
The result i would hope for is "hello from A" and "hello from B"
respectively. But since @@greeting is really scoped module-wide it is
only intialized once. How can i force the class variable to pertain
only to the singelton class that mixes it in?
can be mixed into class methods and retain scope for only that
particular class instead of being defacto module-variables.
Here's a simplified example (albeit somewhat silly) of what i'm trying to do:
module Foo
module Bar
#...some instance methods
def self.included(klass)
klass.extend(BarClassMethods)
end
end
module BarClassMethods
def greeting
@@greeting ||= self.determine_greeting
end
def determine_greeting
hello
end
end
end
class A
include Foo::Bar
def self.hello
"hello from A"
end
end
class B
include Foo::Bar
def self.hello
"hello from B"
end
end
puts A.greeting
#=> 'hello from A'
puts B.greeting
#=> 'hello from A'
The result i would hope for is "hello from A" and "hello from B"
respectively. But since @@greeting is really scoped module-wide it is
only intialized once. How can i force the class variable to pertain
only to the singelton class that mixes it in?