Duplicted Code (DRY)

Hi everyone

I’ve a problem. I’d like to refactoring code. I generate two controllers
with scaffold (student_controller, customer_controller). Actually, I
have some duplicated code.

How can I simplify the code of the controllers? Can I make a new
controller (human_controller) and move the duplicated code into these?

CustomerController < HumanController
StudentController < HumanController
HumanController < ApplicationController

Does it give any other solutions and how can I do this?

Thanks for your help!

M. R. wrote:

Hi everyone

I’ve a problem. I’d like to refactoring code. I generate two controllers
with scaffold (student_controller, customer_controller). Actually, I
have some duplicated code.

How can I simplify the code of the controllers? Can I make a new
controller (human_controller) and move the duplicated code into these?

CustomerController < HumanController
StudentController < HumanController
HumanController < ApplicationController

That will work, and inheritance is one of two commonly used techniques
for removing duplication. The other is aggregation.

See: Extract Superclass
and
Extract Class

Alan

Alan wrote:

M. R. wrote:

Hi everyone

I’ve a problem. I’d like to refactoring code. I generate two controllers
with scaffold (student_controller, customer_controller). Actually, I
have some duplicated code.

How can I simplify the code of the controllers? Can I make a new
controller (human_controller) and move the duplicated code into these?

CustomerController < HumanController
StudentController < HumanController
HumanController < ApplicationController

That will work, and inheritance is one of two commonly used techniques
for removing duplication. The other is aggregation.

See: Extract Superclass
and
Extract Class

Alan

Thank you for your anwser! Both controllers has the same method
“update”. But I have the problem with the model. How can I diffentiate
the models Student and Customer in the HumanController, when I will find
a person (a student or customer):

class HumanController < ApplicationController
def update
#!!! Here is my problem !!!
@student = Student.find(params[:id])
if @student.update_attributes(params[:student])
flash[:notice] = ‘Student was successfully updated.’
redirect_to :action => ‘show’, :id => @student
else
render :action => ‘edit’
end
end
end

Many thanks…

On Friday 24 November 2006 09:12, M. R. wrote:

Does it give any other solutions and how can I do this?

You can use mixins:

module A
def foo

body

end

def bar

body

end
end

class AA
include A
end

class BB
include AA
end

aa = AA.new
bb = BB.new

aa.foo # works!
bb.foo # works!

Enjoy,
Jim P.