Search code examples
crystal-lang

Mix class and instance variables in module


From github issue #4820 by @TPei.

Hey, I was just wondering if it is possible to mix class and instance variables in a module like in ruby, by using the self.included(base) hook or something similar. Is there any construct that supports this or is anything planned for the future?

To clarify: In ruby it is possible to define a module (MyFirstModule) and then in another module (MySecondModule) do

def self.included(base)
  base.extend(MyFirstModule)
end

This then causes the methods in MyFirstModule to become class methods in MySecondModule, thus enabling me to add both class and instance methods when a user includes MySecondModule


Solution

  • Answer by @straight-shoota

    This can be accomplished with the included macro hook: reference

    macro included
      extend MyFirstModule
    end