2017-05-28 3 views
0

私はレール5のアプリケーションのコントローラをクリーンアップする途中にあり、私は投稿にフラグを付けるサービスを作成しました。残念ながら、acts_as_votableヘルパーメソッドをサービスに移動して以来、フラグは動作していません。これがうまくいかない理由は何ですか?Refactoring Rails acts_as_votable gemサービスに

アプリ/サービス/ 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 
... 
+0

は投票済みですか?コントローラーで直接呼び出すと作業しますか?それを試すことができますか? – Niklas

+0

'FlagService'を別にテストするユニットテストを書いてください。また、サービスがそれらなしでは機能しないので、引数は、def'en initialize(user、flaggable)またはrequire args 'def initialize(user:、flaggable:)'のいずれかに変更する必要があります。 @ Niklas yep; – max

+0

;コントローラーで動作するまた、サービスで動作するように見えますが、投票に対する更新は永続化されません。 – lgants

答えて

0
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に応答するフラグを付ける/解除する別々のルートを作成することができます。