mercredi 5 août 2015

DRYing up Inherited Methods in Rails Controllers

I have a base set of controllers with a pretty standard set of RESTful methods. I then have a second set of controllers for managing client micro-sites. The second set of controllers are almost identical to the base set, except that each method that responds with HTML needs an additional instance variable representing the micro-site's id (which is not available to the base controllers) to be defined.

This means I'm repeating my code twice in my app and that's not very maintainable, especially for a large app with many controllers. Is there a way to tell a controller to inherit a method, but to then insert an additional variable or other logic into the inherited method?

For example, if I have a UsersController below:

class UsersController < ApplicationController
    def index
    end
end

And then I have Clients::UsersController << UsersController below:

class Clients::UsersController < UsersController
    def index
        @client_id = params[:id]
    end
end

How can I DRY up Clients::UsersController?

Aucun commentaire:

Enregistrer un commentaire