reduce method missing call stack with dynamic define method

理解Ruby中method_missing机制及其在Rails中的应用
本文深入探讨了Ruby中的method_missing机制,解释了其在Rails框架中的重要应用,包括如何通过method_missing实现动态方法定义,以及如何避免其性能损耗,通过将method_missing与define_method结合使用来优化性能。
method_missing是ruby里面一个非常cool的hook。rails里面很多特性都是基于method missing实现的。
但是method missing也不是那么完美。各种rails性能优化的文章都建议避免使用method missing,原因很简单,method missing的实现机制确实会是增加call ruby stack次数。

使用method missing + define method,调用一次method missing后动态定义方法来减少call ruby stack次数。

class A
def method_missing(method_id, *args)
puts "method missing stack called.."
if method_id.to_s =~ /^find_by_(.*?)$/
name = $1
self.class.send(:define_method, method_id) do
name
end
send(method_id, *args)
else
super
end
end
end
obj = A.new
p obj.find_by_title
p obj.find_by_title


输出:

method missing stack called..
"title"
"title" #第二次没有执行method missing方法..


rails里的find by和动态属性都是这样实现的:
[url]https://github.com/rails/rails/blob/master/activerecord/lib/active_record/base.rb[/url]

[url]https://github.com/rails/rails/blob/master/activerecord/lib/active_record/attribute_methods.rb[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值