Help with facade pattern

D

Daniel Berger

Hi all,

Well, I *think* it's the facade pattern. Anyway, I'm trying to do
something like this:

class Foo < String
def method_a
Bar.method_a(self)
end
def method_b
Bar.method_b(self)
end
end

This is easy enough to do by hand for a few methods, but what if I have
many methods from Bar I want to use?

I thought maybe there was a trick with Forwardable I could use, but I
don't see how. Any ideas on how to shortcut this?

Regards,

Dan
 
E

ES

Daniel said:
Hi all,

Well, I *think* it's the facade pattern. Anyway, I'm trying to do
something like this:

class Foo < String
def method_a
Bar.method_a(self)
end
def method_b
Bar.method_b(self)
end
end

This is easy enough to do by hand for a few methods, but what if I have
many methods from Bar I want to use?

I thought maybe there was a trick with Forwardable I could use, but I
don't see how. Any ideas on how to shortcut this?

You left too quick :) You are looking at something like this:

class Class
def forward(mod, *methods)
methods.each do |method|
# Substitute mod with const_get(mod) if you want to use :ModName
define_method(method) {|| mod.send(method, self)}
end
end
end

class A
def A.foo(x)
puts "A.foo: #{x}"
end
end

class B
forward A, :foo
end

B.new.foo # => A.foo
Regards,

Dan

E
 
D

Daniel Berger

ES said:
You left too quick :) You are looking at something like this:

class Class
def forward(mod, *methods)
methods.each do |method|
# Substitute mod with const_get(mod) if you want to use :ModName
define_method(method) {|| mod.send(method, self)}
end
end
end

class A
def A.foo(x)
puts "A.foo: #{x}"
end
end

class B
forward A, :foo
end

B.new.foo # => A.foo


E


Thank you - that will work beautfully. :)

Regards,

Dan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top