Question regarding rails framework code

I noticed that the code in the rails structure uses the following convention universally:

class SomeClass
  class << self
     def some function
     end
  end
end

but not

class SomeClass
end

def SomeClass.function
end

and

class SomeClass
  def self.somefunction
  end
end

What is the reason for this design choice? They all seem to be doing the same thing.

+3
source share
3 answers

Dave Thomas has a wonderful screencast metaprogramming series that goes into these advanced topics. I find that episode II speaks of class <on my own. Scripts can be found at http://www.pragprog.com/screencasts/v-dtrubyom/the-ruby-object-model-and-metaprogramming

+1
source

class << self , :

class SomeClass
  class << self
    def a_public_method
      "This is a public class method"
    end

    private
    def a_private_method
      "This is a private class method"
    end
  end
end

private_class_method, :

class SomeClass
  def self.a_public_method
    "This is a public class method"
  end

  def self.a_private_method
    "This will be a private class method"
  end
  private_class_method :a_private_method
end
+1

They are actually different. The declaration of the inner class in your first example actually refers to SomeClass eigenclass. Eigenclass allows you to define instance-specific behavior for your classes. Therefore, the somefunction method does not actually belong to the class, but refers to instances of the class.

Regarding the use of this method, I could consider it useful if you want to expand the capabilities of an existing class without polluting its method namespace.

+1
source

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


All Articles