Sunday, 12 March 2017

How to make a class method and callback in ruby module



1) Callback in module -

Let's assume we have two model Provider and Consumer. Both model have same callback of before_create :generate_refresh_token. So, in this case we can make a module.

Let's create a module in models/concerns/token_generator.rb

   
    module TokenGenerator

      extend ActiveSupport::Concern

      included do
        before_create :generate_refresh_token
      end

   
      def generate_token
        SecureRandom.urlsafe_base64
      end           
   
      private

      def generate_refresh_token
        if self.refresh_token.blank?
          begin
        self.refresh_token = generate_token
          end while self.class.exists?(refresh_token: self.refresh_token)
        end
      end

    end


Now, in include above module in models Consumer.rb and Provider.rb

    class Consumer < ApplicationRecord

      #==== Modules ==================
      include TokenGenerator

    end


    class Provider < ApplicationRecord

      #==== Modules ==================
      include TokenGenerator

    end


2) Class method in module

Now, suppose that we have same class method of regenerate_refresh_token in both models. From this method we want to find the object and regenerate refresh token and update the same attribute.


So, in models/concerns/token_generator.rb


      def self.included(resource)
        def resource.regenerate_refresh_token(refresh_token)
          resource = self.where(refresh_token: refresh_token).take
          if resource
        resource.update_attributes(refresh_token: resource.generate_token)
        resource
          end
        end
      end


Now we can call above method as a class method like

        Consumer.regenerate_refresh_token

            OR

        Provider.regenerate_refresh_token           

No comments:

Post a Comment