简体   繁体   中英

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. Unfortunately, since moving the acts_as_votable helper methods into a service, none of the flags are working. Any thoughts why this isn't working?

app/services/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

...
  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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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