Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...