[英]Refactoring Rails acts_as_votable gem Into Services
我正在清理Rails 5應用程序的控制器,並且已經創建了一個標記帖子的服務。 不幸的是,由於將acts_as_votable幫助器方法移至服務中,因此所有標志均無效。 有什么想法為什么不起作用?
應用程序/服務/ 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
應用程序/控制器/ 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
考慮到只涉及很少的實際代碼,我會質疑為什么應將其提取到服務中,因為它增加了附加的抽象級別。 相反,您可能想創建單獨的路由來標記/取消標記以響應POST
和DELETE
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.