Dynamic Variable Names in Included Module in Ruby?

Posted by viatropos on Stack Overflow See other posts from Stack Overflow or by viatropos
Published on 2010-03-22T08:07:33Z Indexed on 2010/03/22 8:11 UTC
Read the original article Hit count: 213

Filed under:
|
|
|

I'm hoping to implement something like all of the great plugins out there for ruby, so that you can do this:

acts_as_commentable
has_attached_file :avatar

But I have one constraint:

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

Here's what the structure looks like, and I'm wondering if you know the missing piece in the puzzle:

# 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 = {})
      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!"

That %Q? I'm not totally sure how to use, but I'm basically just wanting to somehow be able to pass the options hash from that helper method into the workhorse module. Is that possible? That way, the workhorse module could define all sorts of functionality, but I could name the variables whatever I wanted at runtime.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about dynamic