Rails 3 与 Rails 4 中 try 方法的不同
2016-06-01 11:16
561 查看
Rails 最新版本中,在使用 try 调用私有方法的时候,有了一些差异
rails4:
测试,Rails 3 中对象可以直接使用 try 调用私有方法,但是 Rails 4 中则不可以
我们来看看源代码
主要差异在于 send 和 public_send, 如果你是个老手,肯定知道怎么回事了
send 是 Ruby 的内核方法,可以调用任意方法
public_send 则只能调用公有方法
class User include Mongoid::Document private def say puts "hello, world" end end
Rails 3:
u = User.new u.try(:say) ==> hello, world
rails4:
u = User.new u.try(:say) ==> nil
测试,Rails 3 中对象可以直接使用 try 调用私有方法,但是 Rails 4 中则不可以
我们来看看源代码
Rails 3.1 稳定版
def try(*a, &b) if a.empty? && block_given? yield self else __send__(*a, &b) end end
Rails 4.1 稳定版
def try(*a, &b) if a.empty? && block_given? yield self else public_send(*a, &b) if respond_to?(a.first) end end
主要差异在于 send 和 public_send, 如果你是个老手,肯定知道怎么回事了
send 是 Ruby 的内核方法,可以调用任意方法
public_send 则只能调用公有方法
相关文章推荐
- 【问题处理】GIT删除主分支报错:[remote rejected] master (deletion of the current branch prohibited)
- RAC原理 转载自http://blog.csdn.net/xabc3000/article/details/7078399
- lr 远程控制报Vuser compilation failed.
- leetcode----Container With Most Water
- 将数据划分为训练数据及测试数据(div_train_val.py 解析)
- ccah-500 第5题 How will the Fair Scheduler handle these two jobs?
- SQL Server2008如何设置开启远程连接http://jingyan.baidu.com/article/fec4bce226a264f2618d8ba5.html
- root.sh Fails to Start HAIP as Default Gateway is Configured for Private Network VLAN (ID 1366211)
- IntelliJ中的main函数和System.out.println()快捷键
- MSVCRTD.lib(crtexew.obj) : error LNK2019: 无法解析的外部符号 _WinMain@16,该符号在函数 ___tmainC
- RAID卡
- maven install Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.1.1:war (default-wa
- 游戏编程中的人工智能技术-遗传算法入门(四)
- 关于人工智能的幻想(九)第三部分
- 游戏编程中的人工智能技术-遗传算法入门(三)
- Hard-题目47:336. Palindrome Pairs
- 区间动规--区分两道题--【cqoi】涂色&【cdoi】string painter
- 游戏编程中的人工智能技术-遗传算法入门(二)
- RAII(资源创建即释放)
- root.sh Fails to Start HAIP as Default Gateway is Configured for Private Network VLAN (文档 ID 1366211