简体   繁体   English

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

[英]DRYing up Inherited Methods in Rails Controllers

I have a base set of controllers with a pretty standard set of RESTful methods. 我有一组基本的控制器,带有一组相当标准的RESTful方法。 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. 第二组控制器几乎与基本组完全相同,不同的是,每个响应HTML的方法都需要定义一个附加实例变量,该变量代表微站点的ID(基本控制器不可用)。

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: 例如,如果我下面有一个UsersController:

class UsersController < ApplicationController
    def index
    end
end

And then I have Clients::UsersController << UsersController below: 然后我有Clients :: UsersController << UsersController在下面:

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

How can I DRY up Clients::UsersController? 如何干燥Clients :: UsersController?

You're probably after a concern : 您可能会担心

# app/controllers/concerns/do_something.rb

module DoSomething
  include ActiveSupport::Concern

  def something
    # Shared code goes here
  end
end

In your controllers... 在您的控制器中...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM