Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

ruby - Self shorthand doesn't behave the same way than class << self rails

I would like to understand why in this scenario, subclasses of A won't heritate from sequence_name.

class A < ApplicationRecord
  self.abstract_class = true
  self.sequence_name = "my_seq"
end

And why when defined as follow they will.

class A < ApplicationRecord
  self.abstract_class = true
 
  class << self
    def sequence_name
      "my_seq"
    end
  end
end

I thought that self.method was equivalent to:

class << self
  def method; end
end
question from:https://stackoverflow.com/questions/65951588/self-shorthand-doesnt-behave-the-same-way-than-class-self-rails

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I thought that self.method was equivalent to:

class << self
  def method; end
end

Not quite.

You can create a class method by defining an instance method in the class' singleton class: (that's what class methods really are)

class A
  class << self
    def method; end
  end
end

Or by using the def self. syntax: (equivalent to the above)

class A
  def self.method; end
end

To call the method from within the class, you'd use:

class A
  method
end

And if your method is a setter, you have to add an explicit receiver, e.g.:

class A
  self.method = 123
end

That looks a bit like the def self. syntax for defining a class method, but note that there's no def in here.


You can rewrite your working code as:

class A < ApplicationRecord
  self.abstract_class = true
 
  def self.sequence_name
    "my_seq"
  end
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...