I'm trying to write a method that will both initialize (.new(...
) and call a .run
method on a class found from a string that will replace lots of duplicate code. This is the old, working method (there are lots of them similar):
def facebook
@share = params[:share_document]
::Documents::SendToFacebook.new(@document, @share).run
end
The new "meta-" method looks like this:
def send_to_provider
provider = params[:provider]
@share = params[:share_document] || nil
klass = "send_to_#{provider}".classify
p = class_send(klass, :new, @document, @share)
return true if p.run
end
And the class_send
(inspired by this) looks like this:
def class_send(class_name, method, *args)
return nil unless Object.const_defined?(class_name)
c = Object.const_get(class_name)
c.send(method, *args)
c
end
I can't seem to be able to access the c
object from the send_to_provider
method, i.e., either p.run
can't be found of the class isn't returned properly with c
. I have to call :new
instead of :run
in the send_to_provider
method to initialize the object.
How can I both initialize and call :run
on the object from the send_to_provider
method?
EDIT
The current code gives me this error:
Completed 500 Internal Server Error in 574.9ms
NoMethodError (undefined method `run' for nil:NilClass):
app/controllers/documents_controller.rb:98:in `send_to_provider'