分享 原来 class << self 是这样的

pynix · September 18, 2020 · Last by lithium4010 replied at October 16, 2020 · 1714 hits

ruby 中的 << 符号作用太多。

移位计算 数组 append 还有 open singleton class

我居然一直没懂这个奇奇怪怪的写法。。

要看《Ruby 元编程》,记得是“打开类”一章说到。

https://book.douban.com/subject/7056800/

Reply to Rei

主要是没有系统看过。

感觉要找时间回味一下了。

Airbnb Ruby Style 不建議 class << self 這樣玩 就是因為太魔幻了

https://github.com/airbnb/ruby#no-class-self

Reply to Aiken00

Rails 建议用class << self https://guides.rubyonrails.org/contributing_to_ruby_on_rails.html#follow-the-coding-conventions

Prefer class << self over self.method for class methods.

Reply to piecehealth

感觉 class << self 没有优势反而有劣势,代码长了一眼分辨不出一个方法到底是类方法还是实例方法,相反 self.xxx 就没有这种问题

class Sample
  class << self 
    # 4空格缩进是类方法
    def class_method
    end

   private
    # 6空格缩进是私有类方法
      def private_class_method
      end
  end

  # 2空格缩进是实例方法
  def instance_method
  end

  private
    # 下区4空格缩进是私有实例方法
    def private_instance_method
    end 
end
Reply to piecehealth

代码长了就不能靠缩进区分了

Reply to piecehealth

可以约定下 class << self 在类的最后。

class Sample


  # 2空格缩进是实例方法
  def instance_method
  end

  private
    # 下区4空格缩进是私有实例方法
    def private_instance_method
    end 

  class << self 
    # 4空格缩进是类方法
    def class_method
    end

   private
    # 6空格缩进是私有类方法
      def private_class_method
      end
  end
end

这样子

写那么长的文件不好维护

You need to Sign in before reply, if you don't have an account, please Sign up first.