[英]Refactoring Rails acts_as_votable gem Into Services
I'm in the process of cleaning up controllers for a rails 5 app and I've created a service to flag posts. 我正在清理Rails 5应用程序的控制器,并且已经创建了一个标记帖子的服务。 Unfortunately, since moving the acts_as_votable helper methods into a service, none of the flags are working. 不幸的是,由于将acts_as_votable帮助器方法移至服务中,因此所有标志均无效。 Any thoughts why this isn't working? 有什么想法为什么不起作用?
app/services/flag_service.rb 应用程序/服务/ flag_service.rb
class FlagService
def initialize(params)
@current_user = params[:current_user]
@post = params[:post]
end
def process
if previous_vote?
@post.vote_by :voter => @current_user, :vote_scope => 'flag'
elsif !previous_vote?
@post.unvote_by @current_user, :vote_scope => 'flag'
else
nil
end
end
private
def previous_vote?
@current_user.voted_for? @post, vote_scope: 'flag'
end
end
app/controllers/bursts_controller.rb 应用程序/控制器/ bursts_controller.rb
...
def flag
if FlagService.new({current_user: current_user, post: @post}).process
render(status: 201, json: @category.as_json({:only => [:id, :status, :name, :description, :slug, :title] }))
else
render(status: 400, json: @category.errors)
end
end
...
class User < ApplicationRecord
# ...
def flagged?(post)
voted_for? post, vote_scope: 'flag'
end
end
class FlagService
def initialize(user:, post:)
@user= user
@post = post
end
def process
if @user.flagged?(@post)
@post.unvote_by @user, vote_scope: 'flag'
else
@post.vote_by voter: @user, vote_scope: 'flag'
end
end
end
Given how little actual code is involved I would question why this should be extracted to a service since it adds an additional level of abstraction. 考虑到只涉及很少的实际代码,我会质疑为什么应将其提取到服务中,因为它增加了附加的抽象级别。 Instead you may want to create seperate routes to flag/unflag that respond to POST
and DELETE
. 相反,您可能想创建单独的路由来标记/取消标记以响应POST
和DELETE
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.