Shauna wrote:
Adam wrote:
The standard way of doing what you want is to put the funcionality (i.e.
the code) into a module defined in /lib. You then use include
, and
voila, problem solved! You have the method you defined in said module
available on any controller that includes that module.
Thanks for your quick reply, Adam.I’m tripping over the exact usage
here.
If the file is called /lib/post_payment_module.rb and its contents start
with the line “module PostPayment”, what should the include command in
the payments_controller.rb file say and where does it go?
First of all, in Ruby there’s no necessary relation between the filename
containing a piece of code, and its contents. I.e. an .rb file may
contain one module, or several, or none at all. So it doesn’t make any
sense to postfix the filename with _module. What if you want to add
another module there, or even a class?
Use a functional name, like maybe post_payment.rb
in your case.
If I use…
def create
include post_payment_module
end
I get the NameError “undefined local variable or method
`post_payment_module’ for #PaymentsController:0x644d758”.
Sure, because post_payment_module is not escaped there in any way, so it
is assumed to be a name (i.e. var or method), which is sought after by
the interpreter but doesn’t exist, hence the error.
If I use…
def create
include PostPayment
end
I get the NameError “uninitialized constant PostPayment”.
Yes, because you haven’t require
d /lib/post_payment_module.rb. The
file wasn’t evaluated, so PostPayment isn’t among the constants at your
disposal.
You should require_dependency 'post_payment_module'
in
conf/environment.rb or in application_controller.rb or the controller
you need the functionality in. Then you’ll have PostPayment at your
disposal, and can do include PostPayment
.
If I have to put the “def create” in the module itself, I’m back to the
problem of having to pass it the session, flash, and params variables
and figure out how to pass them back to payments_controller when they
are changed within the module.
Shauna
I recommend a good, thorough Ruby tutorial (e.g. the PickAxe2), followed
by a good Rails tutorial.
-Adam