在Rails控制器中干燥继承的方法

时间:2015-08-05 17:50:06

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 inheritance model-view-controller

我有一组基本控制器,带有一套非常标准的RESTful方法。然后我有第二组控制器来管理客户端微站点。第二组控制器几乎与基本集相同,除了用HTML响应的每个方法都需要一个额外的实例变量来表示要定义的微站点的id(基本控制器不可用)。

这意味着我在我的应用中重复了两次我的代码并且这不是很难维护,特别是对于有许多控制器的大型应用程序。有没有办法告诉控制器继承一个方法,但是然后在继承的方法中插入一个额外的变量或其他逻辑?

例如,如果我在下面有一个UsersController:

class UsersController < ApplicationController
    def index
    end
end

然后我有Clients :: UsersController&lt;&lt; UsersController如下:

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

如何干掉客户端:: UsersController?

1 个答案:

答案 0 :(得分:2)

你可能在concern之后:

# app/controllers/concerns/do_something.rb

module DoSomething
  include ActiveSupport::Concern

  def something
    # Shared code goes here
  end
end

在您的控制器中......

class UsersController < ApplicationController
    include DoSomething

    def index
      # Invoke shared code
      something
    end
end

class Clients::UsersController < UsersController
    include DoSomething

    def index
      @client_id = params[:id]

      # Invoke shared code
      something
    end
end
相关问题