我如何在rails控制器中重构类似的代码片段?
app/控制器/相册_控制器.…:58…62 <>
def set_album
if current_user.admin?
@album = User.find(params[:user_id]).albums.find(params[:id])
else
@album = current_user.albums.find(params[:id])
end
end
app/控制器/文章_Controller.rb:45…49 <>
def set_article
if current_user.admin?
@article = User.find(params[:user_id]).articles.find(params[:id])
else
@article = current_user.articles.find(params[:id])
end
end
app/控制器/照片_控制器.…:55…59 <>
def set_photo
if current_user.admin?
@photo = User.find(params[:user_id]).photos.find(params[:id])
else
@photo = current_user.photos.find(params[:id])
end
end
发布于 2014-11-01 20:30:02
控制器/关注点/user_Resource.rb
module UserResource
extend ActiveSupport::Concern
included do
before_action :set_resource , only: [:edit, :update, :destroy]
before_action :signed_in_user, only: [:new, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update, :destroy]
end
def set_resource
association = controller_name.classify.downcase
resource = current_user.admin? ? User.find(params[:user_id]) : current_user
resource = resource.send(association.to_s.pluralize).find(params[:id])
instance_variable_set("@#{association}", resource)
end
def correct_user
association = controller_name.classify.downcase
redirect_to root_path unless admin_or_current?(instance_variable_get("@#{association}").user)
end
end
然后,在{照片、相册、文章}_controller.rb中
include UserResource
发布于 2014-11-01 20:11:39
一种方法是创建一个新的控制器:
class ResourceController < ApplicationController
before_filter :set_resource, only: [:show, :edit, :update, :destroy]
private
def set_resource
user = current_user.admin? ? User.find(params[:user_id]) : current_user
resource = user.send(controller_name.to_sym).find(params[:id])
instance_variable_set("@#{controller_name.singularize}", resource)
end
end
然后你的albums_controller.rb:
class AlbumsController < ResourceController
# use @album in show, edit, update, and destroy
end
articles_controller.rb:
class ArticlesController < ResourceController
# use @article in show, edit, update, and destroy
end
photos_controller.rb:
class PhotosController < ResourceController
# use @photo in show, edit, update, and destroy
end
发布于 2014-11-01 19:04:33
在这里使用元编程是个好主意,我的意思是:
def set_resource(association_singular) # e.g. :photo
resource = current_user.admin? ? User.find(params[:user_id]) : current_user
resource = resource.send(association.to_s.pluralize).find(params[:id]) )
instance_variable_set("@#{association}", resource)
end
然后,在控制器( before_filter only: [:action]
或
def action
# ...
set_resource(:photo)
# ...
end
https://stackoverflow.com/questions/26691748
复制相似问题