Given I have a class A which is kind of abstract and encapsulates logic which is needed in decendants B and C.
class A
end
class B < A
end
class C < A
end
Furthermore if have resourceful routing which provides routes for B and C and are therefore handled by the respective controllers.
To dry up things I moved shared code of both conntrollers into an "abstract" controller (never to be instantiated and no routes to its actions):
class AController < ApplicationController
def new(additional_opts)
render locals: {base: "stuff"}.merge(additional_opts)
end
end
class BController < AController
def new
super(foo: 1)
end
end
class CController < AController
def new
super(bar: 1)
end
end
A controller action usally has no parameters. But since the AController is intended to be abstract this approach may be valid, or is it better to rely on instance variables and simply call super and then pulling the needed information from the variables instead?
Any insights welcome.
Edit 1:
Thankfully Lateralu42 suggested Concerns which gets me thinking about; ok what is my real question here i want to have an anwser for? (Like in hitch hikers guide). So it is also about then to use which method of code reuse?
Found a nice blog post here.
Actually, I think your problem could be solved using the concerns pattern (module shared between controllers or models) : How to use concerns in Rails 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With