Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller Inheritance how to implement an abstract controller

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.

like image 244
jethroo Avatar asked Oct 21 '22 02:10

jethroo


1 Answers

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

like image 60
lateralus23 Avatar answered Oct 23 '22 02:10

lateralus23