Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

question regarding rails framework code

I noticed that the code in the rails framework is using the following convention all over the place:

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

rather than

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 accomplish them same thing

like image 687
josephmisiti Avatar asked May 06 '26 22:05

josephmisiti


2 Answers

Dave Thomas has a nice metaprogramming screencast series that goes into these advanced topics. I believe episode II talks about class << self. The screencasts can be found at http://www.pragprog.com/screencasts/v-dtrubyom/the-ruby-object-model-and-metaprogramming

like image 53
techiferous Avatar answered May 09 '26 12:05

techiferous


One advantage of the class << self choice is that it allows you to define private class methods easily:

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

Otherwise, you have to use private_class_method, i.e.:

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
like image 39
Greg Campbell Avatar answered May 09 '26 13:05

Greg Campbell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!