Search code examples
ruby-on-railsrubyactiverecordsuperactivesupport-concern

In Rails, how to call same methods on every concern and in model?


I have a model and quite a few concerns, I want to call the same method from every concern and from the model itself, and I was wondering if this is possible.

So let’s say I have a model like this, it has three concerns and a setup_defaults method.

class Item < ApplicationRecord
    include ConcernOne
    include ConcernTwo
    include ConcernThree

    def setup_defaults
        # model code here
    end
end

I want to have a setup_defaults in each concern that runs as well as in the one in the model so it looks like this:

module ConcernOne
    extend ActiveSupport::Concern
    def setup_defaults
        # concern one code
    end
end

module ConcernTwo
    extend ActiveSupport::Concern
    def setup_defaults
        # concern two code
    end
end

module ConcernThree
    extend ActiveSupport::Concern
    def setup_defaults
        # concern three code
    end
end

So I want concern one code, then concern two code then concern one code and then finally model code here to run in that order.

I’ve tried using super like this but it only runs the last concern code and then the model code:

class Item < ApplicationRecord
    include ConcernOne
    include ConcernTwo
    include ConcernThree

    def setup_defaults
        super
        # model code here
    end
end

Can I run all 3 concerns setup_defaults and then the model’s setup_defaults? Is this possible?

Thanks.


Solution

  • Can I run all 3 concerns setup_defaults and then the model’s setup_defaults? Is this possible?

    Yes, and you already have it. The only bit you're missing is invoking your concerns from each other.

    module ConcernOne
      extend ActiveSupport::Concern
      def setup_defaults
        super if defined?(super) # do the same for other concerns and the model
        puts 'one'
      end
    end
    

    Output:

    Item.new.setup_defaults
    # >> one
    # >> two
    # >> three
    # >> main