首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >rails设计模式

rails设计模式
EN

Stack Overflow用户
提问于 2014-08-08 12:50:55
回答 1查看 1.8K关注 0票数 4

很抱歉给你留了这么长的邮筒。我在Rails中工作了大约6个月,我发现自己正在尝试将设计模式从java/C#应用到RoR中的问题。我觉得在RoR中有更好的方法来做同样的事情,但遗憾的是,我只是个菜鸟。因此,这里有一个基本问题,我正试图找到一个面向Ruby的设计模式。如有任何指导,将不胜感激。

在我的应用程序控制器中,有很多“共享”行为。在许多情况下,存在特定于控制器的初始化(即将对象的user_id属性设置为当前用户,筛选出写一次属性)和基于对象实例和当前用户的授权操作。因此,许多模型和控制器看起来都与此类似:

代码语言:javascript
复制
class Object < ActiveRecord::Base

  ...

  def authorize_action(user, action)
    [:show,:create].include?(action) || self.created_by_user_id == user.id # only the user who created can update/delete
  end

  def init_new(signed_in_user)
    self.created_by_user_id = signed_in_user.id
    if self.location_id.nil?
      self.location_id = signed_in_user.default_location_id
    end
  end

end


ObjectController < ApplicationController

  before_action :set_object, only: [:show, :edit, :update, :destroy]
  before_action :authorize_action, only: [:show, :edit, :update, :destroy]
  ...

  def new
    @object = Object.new
    @object.parent_id = params[:parent_id] # nested resource, assign parent_id from request url
    @object.created_by_user_id = current_user.id
  end

  def edit
  end

  def create
    @object  = Object.new(object_create_params)
    @object.parent_id = params[:parent_id] # nested resource, assign parent_id from request url
    @object.created_by_user_id = current_user.id
    @object.save
  end

  def update
    @hunting_plot_user_access.update(object_update_params)
  end

  def destroy
    @object.destroy
  end

  private

  set_object
    @object = Object.find(params[:id])
  end

  def object_create_params
    params.require(:object).permit(:location_id, :attribute_1, :attribute_2)
  end

  def object_update_params
    params.require(:object).permit(:attribute_1, :attribute_2)
  end

  def authorize_action
    raise Exceptions::NotAuthorized unless @object.authorize_action?(current_user, action_name)        
  end

end

我想将每个公共操作的一般“流程”转换为共享逻辑。例如,要创建任何给定对象的新实例,控制器应该创建实例、调用实例上的init_new方法(所有模型都有此方法)、潜在地应用特定于控制器的更改、授权操作和保存对象实例。

我认为这是一个很常见的设计问题。我一直在寻找解决方案,这些解决方案使用的是向ApplicationController类添加“虚拟”方法和自定义回调的组合,但感觉好像我正试图在圆孔中安装一个正方形钉。

有谁有任何建议文章,博客帖子,等等,可能会解决同样的问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-08 12:57:48

继承是一种方法:

代码语言:javascript
复制
class BaseController < ApplicationController

  before_filter :some_common_thing

  def some_common_thing
    # common code
  end

end

class ObjectController < BaseController

  # just the code that is unique to this controller

end

...with --注意不要走太远--这里有一篇关于红宝石的继承的好文章(尽管它适用于任何OO语言)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25203978

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档