惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Security Latest
Security Latest
Recorded Future
Recorded Future
人人都是产品经理
人人都是产品经理
S
SegmentFault 最新的问题
Hacker News - Newest:
Hacker News - Newest: "LLM"
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 三生石上(FineUI控件)
博客园 - 聂微东
P
Privacy & Cybersecurity Law Blog
WordPress大学
WordPress大学
Know Your Adversary
Know Your Adversary
Spread Privacy
Spread Privacy
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
量子位
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
博客园 - Franky
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Tor Project blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
雷峰网
雷峰网
阮一峰的网络日志
阮一峰的网络日志
V
Visual Studio Blog
T
Threatpost
T
Tenable Blog
有赞技术团队
有赞技术团队
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
C
Cisco Blogs
H
Heimdal Security Blog
Attack and Defense Labs
Attack and Defense Labs
A
About on SuperTechFans
Last Week in AI
Last Week in AI
N
News and Events Feed by Topic
T
Threat Research - Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
I
Intezer
V
V2EX
Cyberwarzone
Cyberwarzone
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
B
Blog RSS Feed
V
Vulnerabilities – Threatpost
N
Netflix TechBlog - Medium
T
The Blog of Author Tim Ferriss
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
U
Unit 42
PCI Perspectives
PCI Perspectives
P
Privacy International News Feed
D
Docker

博客园 - Michael Peng

用马尔科夫模型做拼写检查 商业软件编程很无聊(转载) VS2010 Debugger bug 编程之初 编程之美 1.4买书问题常数时间空间解法 vc2010 std::tr1 bind库捉虫记 用vs2010编译kigg 3.0遇到的问题 在vs中获得当前所有快捷键代码 最近的一些面试感悟 这两天被vs2010的std::tr1::bind郁闷了 error C2065: '__LINE__Var' : undeclared identifier 写错名字了 啰嗦几句,关于动机,学习与批评,架构和代码风格 金山卫士代码批评 24点计算 部门开始做技术talk 数据库的坏味道 --《Refactoring Database: Evolutionary Database Design》读书笔记 初识rails ruby解数独问题
偷天换日
Michael Peng · 2010-05-22 · via 博客园 - Michael Peng

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这种动态语言能做得出来。