传递参数到Ruby中包含的模块?

我希望实现像所有伟大的插件那样的红宝石,所以你可以这样做:
acts_as_commentable
has_attached_file :avatar

我有一个约束:

That helper method can only include a module; it can’t define any variables or methods.

这样做的原因是因为我想要选项哈希来定义类似的东西,并且可以转换成一个说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宝石,这完全是你想要的.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...