← Back to Upcase

Using ActiveSupport::Concern


(Jon Seidel) #1

As I understand it, simply extending ActiveSupport::Concern in a module automatically adds as class methods anything that’s in the module ClassMethods.

require 'active_support/concern'
module LibraryUtils

  extend ActiveSupport::Concern

  def add_game(game)
  end

  def remove_game(game)
  end

  module ClassMethods
    def search_by_game_name(name)
    end

    def load_game_list
    end
  end
end

class Game
  include LibraryUtils
end
# Then this works
game = Game.new
game.add_game "NewGame"
Game.load_game_list 

I could also use:

  included do
    load_game_list
  end

and it would add ‘load_game_list’ as a class method. I see that I can used ‘indluded’ to add a method that’s not part of a ClassMethods module; is there any other difference and why would I use one over the other?


(Ben Orenstein) #2

I think you’re misunderstanding what the included block is doing.

Code in the included block is executed when the module is included into a class. That’s it.

So if you wrote

included do
  load_game_list
end

it would not make load_game_list available as a class method. I think it would actually just error out.

The actual use of that block is for when you need to do some setup when a module is included. It can even get an instance of the class you’re mixing into as a param like:

included do |base_class|
  # do stuff to base_class
end

(Jon Seidel) #3

Thanks, Ben… I’ll go back and take a look at that.