Module functions as class and instance methods

Consider you have a module and a class.

module Mymod and a class Myclass.

The situation in hand is such that certain functions in the module need to end up being instance methods of the class Myclass and certain functions need to be Class methods.  You could very well imagine of such situations. Consider you are using ActiveRecord and have a sub class Subscription in correspondence with a DB table. You want to insert logic, within the module, that would work in each of the following case.

1) When a subscription fails or succeeds.

2) When an unsubscription fails or succeeds

You do this.

module SubscriptionLogic

   def  after_sub

      ….

   end

   def  after_unsub

     ….

   end

   def  after_sub_fail

     ….

   end

   def  after_unsub_fail

      ….

    end

end

class Subscription

   include SubscriptionLogic

   …..

end

You insert the logic as functions of a module, say SubscriptionLogic. Ideally you want the methods containing the logic to be instance methods of the class Subscription. You include the module SubscriptionLogic in the class and you avail all the functions in the module as Instance methods. Now you consider the case when an unsubscription fails – i.e, there is no existing subscription so that an unsub could take place.  No way is it possible that you could have a function ‘logic_after_unsub_fail’  in the module SubscriptionLogic and use it as an instance method, simply because there is no instance available.  You think and decide to use the function as your class method, but you have ‘included’  the  module in your class and hence its not possible to use it as your class method. You cannot extend the entire module coz , ideally you want the logic to be instance methods.

So you could get this solved up by a simple piece of extra coding.

module SubscriptionLogic

  def  after_sub

      ….

  end

  def  after_unsub

      ….

  end

  def  after_sub_fail

      ….

  end

  module ClassMethods

      def after_unsub_fail

           ….

      end

      def self.included(base)

          base.extend(ClassMethods)    # base pertains to the class within which you include the module.

      end

   end

end

Now within the class insert this line.

class Subscription

   include SubscriptionLogic

   extend SubscriptionLogic::ClassMethods

   …..

end

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s