Skip to content

Instantly share code, notes, and snippets.

Created January 19, 2011 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/785774 to your computer and use it in GitHub Desktop.
Save anonymous/785774 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
require 'pp'
# Create a module that defines several methods. The _(alpha|beta) methods are
# not to be directly called, but are rather a semantic sugar way of accessing
# some sort of datum created by their clustering method (foo_cluster in this
# case)
module MethodModule
def foo_cluster(*arg)
puts "in foo_cluster with #{arg[0]} "
ds = {
:_alpha => lambda{ puts "This is the alpha lambda" },
:_beta => lambda{ puts "This is the beta lambda" }
}
ds[arg[0].to_sym]
end
def foo_cluster_alpha; end
def foo_cluster_beta; end
end
# This class serves as a method proxy. It has (effectively) no methods. By
# using method_missing, we capture the method and lop off the part that
# matches a clustering name ($1) and the remainder ($2) which behaves,
# effectively, as a method.
class Proxy
def initialize
@clusters = %w{foo_cluster}
end
def method_missing(sym, *args, &block)
@clusters.map do |c|
return [$1, $2] if sym.to_s.match(/^(#{c})(.*)/)
super
end
end
end
# Create a shell class that derives all its instance methods from the
# MethodModule mixin.
class Concept
include MethodModule
end
c = Concept.new
puts c.respond_to? :foo_cluster_alpha #=> true
puts c.respond_to? :foo_cluster_beta #=> true
c.instance_eval do
p = Proxy.new
puts p.respond_to? :foo_cluster_beta #=> false
puts p.respond_to? :foo_cluster #=> false
# The Proxy class knows to basically do a hash key lookup based on a method
# name within the clustering method.
hook = p.foo_cluster_beta
# That lookup could return a closure...
action = send(hook[0].to_sym, hook[1])
# which you could call...
action.call
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment