QA MichaelPeng

一个QA的零零碎碎

偷天换日

class Module
# Declare an attribute accessor with an initial default return value.
#
# To give attribute <tt>:age</tt> the initial value <tt>25</tt>:

#   class Person
#     attr_accessor_with_default :age, 25
#   end
#
#   some_person.age
#   => 25
#   some_person.age = 26
#   some_person.age
#   => 26
#
# To give attribute <tt>:element_name</tt> a dynamic default value, evaluated
# in scope of self:
#
#   attr_accessor_with_default(:element_name) { name.underscore }
#
def attr_accessor_with_default(sym, default = nil, &block)
raise 'Default value or block required' unless !default.nil? || block
    define_method(sym, block_given? ? block : Proc.new { default })
module_eval(<<-EVAL, __FILE__, __LINE__)
      def #{sym}=(value)                        # def age=(value)
        class << self; attr_reader :#{sym} end  #   class << self; attr_reader :age end
        @#{sym} = value                         #   @age = value
      end                                       # end
EVAL
end
end

 

读ActiveSupport代码时看到上面这个方法,即定义有缺省值的属性。看了n遍加上动手注解掉class << self ...这句后终于理解了这个缺省属性的实现方法:

1 define_method(...)定义了一个名为sym的方法,相当于一个读属性,在对象上调用 sym方法时返回default值或者block的返回值

2 在对象上调用#{sym}=方法c时lass << self; attr_reader:#{sym} end先为对象创建一个虚拟类,在该类中用attr_reader覆盖define_method中定义的sym方法,直接返回@{#sym}变量。然后再把value赋给@#{sym}

 

来看一个例子

require 'active_support'

class NiceGirl

include ActiveSupport

attr_accessor :real_age

attr_accessor_with_default(:age) {real_age}

end

nice_girl = NiceGirl.new

nice_girl.real_age = 18

puts "here calls real_age #{nice_girl.age}"

nice_girl.age = 16

puts "here returns @age #{nice_girl.age}"

puts "here returns real_age #{nice_girl.real_age}"

下面是输出

here calls real_age 18

here returns @age 16

here returns real_age 18

即在调用属性setter时动态改变了属性getter的定义。这种做法的确相当灵活,也只有ruby这种动态语言能做得出来。

posted on   Michael Peng  阅读(375)  评论(0编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
< 2010年5月 >
25 26 27 28 29 30 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示