【问题标题】:How to use the same method in 2 controllers?如何在 2 个控制器中使用相同的方法?
【发布时间】:2015-03-06 11:39:47
【问题描述】:

我有一个带有 API 的 Rails 2 应用程序。我对控制器进行了版本化和优化,但有重复的方法。目标是只在一个地方拥有公共信息。所以我探索了以下选项:

  1. 从路由重定向非 API 控制器,但每个控制器都需要其特定的钩子

  2. 模块包含。这是我最喜欢的,但是有很多错误被抛出并且修复的时间非常有限。

  3. 评估。将所有代码放在一个文件中,并在两个地方对其进行评估。这样做,它可以工作,但我对这个解决方法不满意。

最好的办法是什么?

【问题讨论】:

  • 第二项,或者只是创建一个具有通用逻辑的类(将其放入lib 目录)并在您的控制器中使用它。也请看Service Objects
  • 这可以通过多种方式实现。没有更多细节,很难提供有意义的帮助。即使这些细节,“最佳”答案也值得商榷。

标签: ruby-on-rails ruby-on-rails-2


【解决方案1】:

这里可能有一些错别字,但是:

class GenericController < ApplicationController
  def index
    @objects = params[:controller].singularize.camelcase.constantize.all()
  end

  def show
    @object = params[:controller].singularize.camelcase.constantize.find(params[:id])
  end

  def new
    @object = params[:controller].singularize.camelcase.constantize.new
  end

  def edit
    @object = params[:controller].singularize.camelcase.constantize.find(params[:id])
  end

  def create
    model = params[:controller].singularize.downcase
    @object = params[:controller].singularize.camelcase.constantize.new(params[model])
    if @object.save
      redirect_to '/'+params[:controller]
    else
      render :action => 'new'
    end
  end

  def update
    model = params[:controller].singularize.downcase
    @object = params[:controller].singularize.camelcase.constantize.find(params[:id])
    if @object.update_attributes(params[model])
      redirect_to :controller => params[:controller], :action => 'index'
    else
      render :action => 'edit'
    end
  end

  def destroy
    if @object = params[:controller].singularize.camelcase.constantize.find(params[:id])
      @object.destroy
    end
    redirect_to :controller => params[:controller], :action => 'index'
  end

end

特定控制器可以根据需要覆盖这些实现,但是:

class ProjectsController < GenericController
  # done!
end

class ScenariosController < GenericController
  # done!
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 2015-04-13
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    相关资源
    最近更新 更多