扩展Rails引擎控制器方法而不重复它

时间:2015-03-20 08:39:13

标签: ruby-on-rails rails-engines

如何从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

2 个答案:

答案 0 :(得分:0)

我们将这个gem用于多个应用程序和引擎,以完全按照您的意愿执行:

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

答案 1 :(得分:0)

我可以从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