繁体   English   中英

将Rails act_as_votable gem重构到服务中

[英]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

考虑到只涉及很少的实际代码,我会质疑为什么应将其提取到服务中,因为它增加了附加的抽象级别。 相反,您可能想创建单独的路由来标记/取消标记以响应POSTDELETE

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM