I need to create pathed copy of the class, where calls to one module method are replaced to another module method calls:
module Foo
def self.check
"foo"
end
end
module Bar
def self.check
"bar"
end
end
class Bark
def call
puts Foo.check
end
end
Bark.new.call => "foo"
Meouw = Bark.dup
...
???
Meouw.new.call => "bar"
Any ideas how would i achieve that?
CodePudding user response:
Not an answer to the question as it was asked, but in my opinion you are trying to solve an XY problem and this is not the way to go.
What you need to do is to inject the dependency instead of hardcoding it.
module Foo
def self.check
"foo"
end
end
module Bar
def self.check
"bar"
end
end
class Bark
def initialize(checker)
@checker = checker
end
def call
puts @checker.check
end
end
and then just instantiate the Bark
class with the module you need to get an object with the desired behavior:
Bark.new(Foo).call #=> "foo"
Bark.new(Bar).call #=> "bar"
CodePudding user response:
Odd problems require odd solutions. You could define Meouw::Foo
and make it refer to Bar
:
Meouw = Bark.dup
Meouw::Foo = Bar
This way, Foo
within Meouw
will resolve to Meouw::Foo
(which is actually ::Bar
) instead of the global ::Foo
:
Meouw.new.call
# prints "bar"
CodePudding user response:
Why can't you keep it simple and inherit from Bark
and override the call
method?
class Meow < Bark
def call
puts Bar.check
end
end
Meouw.new.call
# prints "bar"
If you want something more meta, you can use Class.new
as well