Set an instance variable to main after turning on the module?

Here is my module that is trying to set the instance variable. I try to initialize and enable self.included, but none of them work when I do include in the outermost area ( main):

module Asd
  def initialize
    @asd = 0
  end
  def self.included(base)
    @asd = 0
  end
  attr_reader :asd
end

Including this in the class works, and I can read the instance variable:

class Bsd
  include Asd
end
Bsd.new.asd
# => 0

But doing this globally does not work:

include Asd
@asd
# => nil
asd 
# => nil

I often know that people will question the motivation to host their code globally. In this case, I just want to see how this is done.

+4
source share
2 answers

@EricDulusil , . : , .

module Asd
  def self.extended(base)
    base.instance_variable_set(:@asd, "Another @asd")
  end

  attr_reader :asd
end

@asd # => nil # !> instance variable @asd not initialized

extend Asd # extend, not include.

@asd # => "Another @asd"
asd # => "Another @asd"
+2

, :

module Asd
  def initialize
    puts "# Initializing"
    @asd = "One @asd"
  end

  def self.included(base)
    puts "# Importing into #{base}"
    @asd = "Another @asd"
  end
  attr_reader :asd
end

class Bsd
  include Asd
  # => # Importing into Bsd
end

puts Bsd.new.asd
# =>
# Initializing
# One @asd

puts Asd.instance_variable_get(:@asd)
# => Another @asd

include Asd
# => # Importing into Object

puts self.asd.inspect # Method is defined for main, @asd hasn't been initialized because main was instantiated before the script was launched
# => nil

puts Object.new.asd
# =>
# Initializing
# One @asd

, main. script, initialize .

+3

Source: https://habr.com/ru/post/1662793/


All Articles