Search code examples
ruby-on-railsdelayed-jobobserversmerit-gem

Delaying Badge Assignment Using delayed_job and tute/merit


I am using the merit gem to assign badges to users.

In my badge_rules.rb file I have:

  module Merit
    class BadgeRules
      include Merit::BadgeRulesMethods
      include UserHelper

      def initiate
        grant_on 'users#update_badges', :badge => "Badge Name" do |user|
          helper_method(user) == foo
        end
      end

    end
  end

I created a method 'model_method' in the User model that does the same thing as helper_method, so I can do this without problem:

  grant_on 'users#update_badges', :badge => "Badge Name" do |user|
    user.model_method == foo
  end

I want to know if there is some way to run this process in the background with delayed_job since helper_method is pretty heavy. I have already tried the following which runs model_method in the background, but does not award the badge:

  grant_on 'users#update_badges', :badge => "Badge Name" do |user|
    user.delay.model_method == foo
  end

and:

  handle_asynchronously :initialize

  def initialize 
    grant_on 'users#update_badges', :badge => "Badge Name" do |user|
      helper_method(user) == foo
    end
  end

The code in the merit gem that checks whether or not the grant_on block& condition is satisfied is not delayed, so I'm not really sure how to approach this problem. Thanks in advance.


Solution

  • See the checks_on_each_request option, which disables synchronous computation: https://github.com/tute/merit/blob/master/lib/generators/merit/templates/merit.rb#L3-L4.

    You can compute them later in a cron job similar to rank rules: https://github.com/tute/merit#defining-rules-2.