重构Rails acts_as_votable gem into Services

时间:2017-05-28 21:51:29

标签: ruby-on-rails ruby service acts-as-votable

我正在为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
...

1 个答案:

答案 0 :(得分:0)

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

鉴于涉及的实际代码很少,我会质疑为什么要将其提取到服务中,因为它增加了额外的抽象级别。相反,您可能希望创建单独的路由以标记/取消标记,以响应DELETEDeclare @YourTable table (ID int,JSON_String varchar(max)) Insert Into @YourTable values (1,'{"setting1":"A","setting2":"B","setting3":"C"}') Select A.ID ,C.* From @YourTable A Cross Apply (values (try_convert(xml,replace(replace(replace(replace(replace(JSON_String,'"',''),'{','<row '),'}','"/>'),':','="'),',','" '))) ) B (XMLData) Cross Apply ( Select Name = attr.value('local-name(.)','varchar(100)') ,Value = attr.value('.','varchar(max)') From B.XMLData.nodes('/row') as C1(r) Cross Apply C1.r.nodes('./@*') as C2(attr) ) C