Lan*_*ard 12 ruby module eval dynamic
我希望能够实现像ruby那样的所有优秀插件,以便你可以这样做:
acts_as_commentable
has_attached_file :avatar
Run Code Online (Sandbox Code Playgroud)
但我有一个约束:
该辅助方法只能包含一个模块; 它无法定义任何变量或方法.
这样做的原因是,我希望选项哈希定义类似的东西type,并且可以将其转换为20个不同的"主力"模块中的一个,所有这些我可以在这样的行中总结:
def dynamic_method(options = {})
include ("My::Helpers::#{options[:type].to_s.camelize}").constantize(options)
end
Run Code Online (Sandbox Code Playgroud)
那些'workhorses'会处理选项,做的事情如下:
has_many "#{options[:something]}"
Run Code Online (Sandbox Code Playgroud)
这是结构的样子,我想知道你是否知道拼图中缺失的部分:
# 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!"
Run Code Online (Sandbox Code Playgroud)
那%Q?我不完全知道如何使用,但我基本上只是想以某种方式能够通过options从helper方法散列成主力模块.那可能吗?这样,主力模块可以定义各种功能,但我可以在运行时将变量命名为任何我想要的.