【问题标题】:Extending Rails Engine controller method without duplicating it扩展 Rails Engine 控制器方法而不复制它
【发布时间】:2015-03-20 08:39:12
【问题描述】:

如何从 Rails 引擎扩展控制器方法而不必复制整个内容?

尝试扩展https://github.com/radar/forem/blob/rails4/app/controllers/forem/forums_controller.rb -- app/decorators/controllers/forem/forums_controller_decorator.rb:

理想

Forem::ForumsController.class_eval do
  def show
    # A simple `include` here or something?

    # New code goes here...
  end
end

当前

Forem::ForumsController.class_eval do
  def show

    # Repeat ALL the code from:
    # https://github.com/radar/forem/blob/rails4/app/controllers/forem/forums_controller.rb

      authorize! :show, @forum
      register_view

      @topics = if forem_admin_or_moderator?(@forum)
        @forum.topics
      else
        @forum.topics.visible.approved_or_pending_review_for(forem_user)
      end

      @topics = @topics.by_pinned_or_most_recent_post

      # Kaminari allows to configure the method and param used
      @topics = @topics.send(pagination_method, params[pagination_param]).per(Forem.per_page)

      respond_to do |format|
        format.html
        format.atom { render :layout => false }
      end

    # New code goes here...
  end
end

【问题讨论】:

    标签: ruby-on-rails rails-engines


    【解决方案1】:

    我们将此 gem 用于多个应用程序和引擎,以完全满足您的需求:

    https://github.com/EPI-USE-Labs/activesupport-decorators

    【讨论】:

      【解决方案2】:

      我可以从 Rails 引擎扩展控制器方法,而无需使用 alias_method 复制代码

      module ValueSets
        SetsController.class_eval do
          def new_with_authorize
            new_without_authorize
            authorize @value_set
          end
      
          alias_method :new_without_authorize, :new
          alias_method :new, :new_with_authorize
        end
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-16
        • 1970-01-01
        相关资源
        最近更新 更多