ruby 动态链接方法
嗨,
我尝试构建一些动态定义的方法并链接一些作用域方法,例如:
define_method "#{instance_name_method}" do
Kernel.const_get(model_name).___some_chaining methods basd on condition
end
一个想法是这样的:
method_action = model_name #ex Post
['latest', 'old', 'deleted','latest_deleted','archived'].each do |prefix|
method_action << ".deleted" if prefix.match('deleted')
method_action << ".latest" if prefix.match('latest')
method_action << ".old" if prefix.match('old')
define_method "#{prefix}_#{instance_name_method}" do
eval( method_action)
end
end
在帖子中,我们有最新的、旧的保护作用域...
现在我们可以调用如下方法:
Post.latest or Post.old_archived etc...
我的问题是:
有更好的方法吗? (类似于活动记录查找,但没有 method_missing)这有点难看...
如何动态链接方法?
我已经知道 send('method',var) 但我不知道如何根据条件从字符串中加入这些方法...
谢谢
HI
I try to build some dynamic defined methods and chain some scope methods something like:
define_method "#{instance_name_method}" do
Kernel.const_get(model_name).___some_chaining methods basd on condition
end
One idea for that is something like:
method_action = model_name #ex Post
['latest', 'old', 'deleted','latest_deleted','archived'].each do |prefix|
method_action << ".deleted" if prefix.match('deleted')
method_action << ".latest" if prefix.match('latest')
method_action << ".old" if prefix.match('old')
define_method "#{prefix}_#{instance_name_method}" do
eval( method_action)
end
end
in post we have defiend scopes latest,old ...
Now we can call methods like:
Post.latest or Post.old_archived etc...
My questions are:
Is there a better approach for doing this? (similar to active record find but without method_missing) this is kind ugly...
How can I chain methods dynamically ?
I already know for send('method',var) but i don't know how to join those methods from strings based on condition...
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
抱歉,但我很难准确理解您在问什么。我不确定您是否正确使用了某些术语,例如“范围方法”是什么意思?您是指类方法还是实例方法?这与范围有关。
当你说链时,你的意思是一个接一个地调用一个方法吗?像这样吗?
我只是评论说你上面不那么动态的部分可以写成:
我在你的问题中没有看到任何实际的链接,所以我不确定你是否只是想连接字符串来动态构建名称。如果您确实想要链接方法,您需要记住,您需要始终在想要链接回该类的方法末尾返回 self。
例如:
会输出:
I'm sorry but it's difficult for me to understand exactly what you're asking. And I'm not sure you're using some terms correctly for instance what do you mean by "scope methods?" Do you mean a class method vs. an instance method? That would pertain to scope.
And when you say chain do you mean to call one method after the other? Like so?
I will just comment that your not so dynamic part above could be written:
I don't see any actual chaining in your question so I'm not sure if you just mean to concatenate stings to build names dynamically. If you do in fact mean to chain methods you need to remember that you need to always return self at the end of a method you want to make chainable back to that class.
For instance:
Would output: