1

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.

1
  • Perhaps a module would be the way to go. Commented Nov 21, 2013 at 17:36

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I just read documentation of the gem and was using it. It is nice. But it does has limitation, for example it does not support strong parameters in Rails 4. There are workarounds but, what I really would like is to know how to implement a class which will make what I described, in this way it would be fully customizable.
@DavidDíazClavijo: well, read source code of inherited_resources. It's all there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.