Reputation: 387
I am trying to create a generic controller in Rails, to approach a similar functionality than the one offered in class-based views in Django. It would mean that just by making a subclass of this controller you would acquired all the methods generated by default with scaffold.
The code generated by scaffold in Rails is equal except for the name of the resource. Given an small example and based on the code generated by scaffold:
class ResourceController < ApplicationController
before_action :set_#{resource_under_scored}, only: [:show, :edit, :update, :destroy]
def index
@#{resource_under_score_pluralized} = #{resource_model}.all
end
...
Given that definition I could write the following controller for resource big shoe:
class BigShoesController < ResourceController
end
Which would imply in the following code auto generated at runtime:
class BigShoesController < ApplicationController
before_action :set_big_shoe, only: [:show, :edit, :update, :destroy]
def index
@big_shoes = BigShoe.all
end
I still need to learn a lot of metaprogramming to achieve this but I though that there are more people who has wanted to acquired the same result. But I have not found the proper question.
How would you accomplish this ? I am looking for a way to implement the class, to see how it would be made to generated code based on variables. It is preferred this answer than a gem which will make the work.
Upvotes: 1
Views: 371
Reputation: 230336
It seems that you want InheritedResources: https://github.com/josevalim/inherited_resources.
It implements all the basic CRUD stuff. Example:
class ProjectsController < InheritedResources::Base
end
This controller has index
, show
, create
, update
and other methods, implemented in a standard manner. There are some possibilities for customization, see the readme file.
Upvotes: 2