传递参数到Ruby中包含的模块?
发布时间:2020-12-16 19:35:36 所属栏目:百科 来源:网络整理
导读:我希望实现像所有伟大的插件那样的红宝石,所以你可以这样做: acts_as_commentablehas_attached_file :avatar 但我有一个约束: That helper method can only include a module; it can’t define any variables or methods. 这样做的原因是因为我想要选项哈
我希望实现像所有伟大的插件那样的红宝石,所以你可以这样做:
acts_as_commentable has_attached_file :avatar 但我有一个约束:
这样做的原因是因为我想要选项哈希来定义类似的东西,并且可以转换成一个说20个不同的’主力’模块,所有这些都可以这样总结一下: def dynamic_method(options = {}) include ("My::Helpers::#{options[:type].to_s.camelize}").constantize(options) end 那么那些“马”就可以处理这些选项,做如下事情: has_many "#{options[:something]}" 这是结构的样子,我想知道如果你知道在拼图中缺少的部分: # 1 - The workhorse,encapsuling all dynamic variables module My::Module def self.included(base) base.extend ClassMethods base.class_eval do include InstanceMethods end end module InstanceMethods self.instance_eval %Q? def #{options[:my_method]} "world!" end ? end module ClassMethods end end # 2 - all this does is define that helper method module HelperModule def self.included(base) base.extend(ClassMethods) end module ClassMethods def dynamic_method(options = {}) # don't know how to get options through! include My::Module(options) end end end # 3 - send it to active_record ActiveRecord::Base.send(:include,HelperModule) # 4 - what it looks like class TestClass < ActiveRecord::Base dynamic_method :my_method => "hello" end puts TestClass.new.hello #=> "world!" 那个%Q我不完全确定如何使用,但我基本上只是想以某种方式将选项哈希从该帮助方法传递到workhorse模块.那可能吗?这样,主机模块可以定义各种功能,但是我可以在运行时为所需的变量命名变量. 解决方法
你可能想看看
Modularity宝石,这完全是你想要的.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |