learning_to_swim
learning_to_swim

Reputation: 361

Ruby: Reusing code in instance and class methods

I am working on a project using Rails and have a need to call a certain piece of code from both class and instance methods. I am doing the following now with redundant code in both the class/instance methods. Is there a better way to write this -

module OrderHelper

  extend ActiveSupport::Concern

  def min_days_to_ship
    #to keep it simple, but has other code/logic
    3
  end

  module ClassMethods
      def self.min_days_to_ship
        #to keep it simple, but has other code/logic
        3
      end
  end
end


class Order < ActiveRecord::Base

  include OrderHelper

  self.earliest_available
    Date.today + OrderHelper::ClassMethods.min_days_to_ship
  end


  delivery_after_date
    self.ordered_date + min_days_to_ship
  end

end

Thanks!

Upvotes: 0

Views: 621

Answers (1)

Cary Swoveland
Cary Swoveland

Reputation: 110665

If the instance and class methods min_days_to_ship are identical, just delete the ClassMethods module and add

extend OrderHelper

after

include OrderHelper.

See Object#extend.

If you want min_days_to_ship to be both an instance and class method whenever the module is included, replace the module ClassMethods with

def self.included(klass)
  klass.extend self
end

which uses the hook Module#included. In this case there is no need for extend OrderHelper in class Order.

Upvotes: 1

Related Questions