0

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!

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.