Class << designation in modules

I am trying to combine a module into a class, and I want some of the methods to behave like class methods and others to be instance methods.

However, I do not want both modules includeand extend. I would prefer just includehim.

When I wrap methods that I want to be class methods in this notation, it works:

class <<
  # ...
end

However, when I use this notation, it does not work:

class << self
  # ...
end

I suspect that the keyword selfestablishes an explicit binding to the module, not the class into which it is mixed. But I have not seen any documentation that recommends leaving a keyword selfwhen using notation class <<.

Does anyone know what is happening with this?


UPDATE: here is a sample code for clarity:

module M
  class <<
    def class_method
      puts "From inside the class_method"
    end
  end

  def instance_method
    puts "From inside the instance_method"
  end
end

class Object
  include M
end

class C
end


C.class_method

obj = C.new
obj.instance_method
+5
2

class << . class <<; end . , - :

class <<
  def class_method
    puts "From inside the class_method"
  end
end

class << def class_method
    puts "From inside the class_method"
  end
end

temp = def class_method
  puts "From inside the class_method"
end
class << temp
end

def class_method
  puts "From inside the class_method"
end
class << nil
end

def class_method
  puts "From inside the class_method"
end

, . .

+6

, self , included . - :

module Bar
  def self.included(base)
    class << base
      def class_method
        "class_method"
      end
    end
  end
end

class Foo
  include Bar
end


p Foo.class_method # => "class_method"
0

All Articles