Pass Arguments to 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:21 UTC
Read the original article
Hit count: 186
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.
The reason for this is because, I want the options hash to define something like type
, and that could be converted into one of say 20 different 'workhorse' modules, all of which I could sum up in a line like this:
def dynamic_method(options = {})
include ("My::Helpers::#{options[:type].to_s.camelize}").constantize(options)
end
Then those 'workhorses' would handle the options, doing things like:
has_many "#{options[:something]}"
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 = {})
# 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!"
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