靠……靠谱量又足啊

起源: 慎用类变量 - 实例变量靠谱量又足

   

大概如下的代码,查了我一晚上 + 一早上:

irb(main):002:0> User.class_inheritable_hash :genders
=> [:genders]
irb(main):003:0> User.genders
=> nil
irb(main):004:0> User.genders = {:a=>1}
=> {:a=>1}
irb(main):005:0> User.genders = {:b=>1}
=> {:b=>1}
我以为User.genders的结果是{:b=>1},但是:

irb(main):006:0> User.genders
=> {:a=>1, :b=>1}

翻了源码才知道:

  def class_inheritable_hash(*syms)
    class_inheritable_reader(*syms)
    class_inheritable_hash_writer(*syms)
  end

  def class_inheritable_hash_writer(*syms)
    options = syms.extract_options!
    syms.each do |sym|
      class_eval(<<-EOS, __FILE__, __LINE__ + 1)
        def self.#{sym}=(obj)                          # def self.nicknames=(obj)
          write_inheritable_hash(:#{sym}, obj)         #   write_inheritable_hash(:nicknames, obj)
        end                                            # end
                                                       #
        #{"                                            #
        def #{sym}=(obj)                               # def nicknames=(obj)
          self.class.#{sym} = obj                      #   self.class.nicknames = obj
        end                                            # end
        " unless options[:instance_writer] == false }  # # the writer above is generated unless options[:instance_writer] == false
      EOS
    end
  end

  def write_inheritable_hash(key, hash)
    write_inheritable_attribute(key, {}) if read_inheritable_attribute(key).nil?
    write_inheritable_attribute(key, read_inheritable_attribute(key).merge(hash))
  end

你可能感兴趣的:(Ruby,Rails)