From: ptkwt@... (Phil Tomson) Date: 2006-02-11T06:13:24+09:00 Subject: Re: rebinding a Proc Sorry to respond to my own message, but sometimes it helps to write these things out. Here's how I did it (look for changes in the RHDL class below): > >So I'd like the user to be able to declare a logic gate like so: > > class AndGate < RHDL > inputs :a, :b > inouts :bus > outputs :a_and_b > > define_behavior { > puts "Inside of define_behavior: a is: #{a}, b is: #{b}" > a_and_b = a & b > } > end > >And then the user should be able to instantiate an AndGate like so: > > andg = AndGate.instance() #optional args > > > >class RHDL > class << self > def instance(*args) #clones this class. > puts "instance:self is: #{self}" > klass = self.clone > puts "klass.class is: #{klass.class}" @ubm.bind(klass) #bind the unboundmethod to the cloned class meth = klass.method(:do_it) #get a method object from the newly # bound 'do_it' method. klass.set_behavior &meth #set cloned class' @__behavior proc #to the new method object #('&' converts to proc) > klass > end > def define_behavior(&b) > @__behavior = b self.class.send(:define_method, :do_it, &b) #define a 'do_it' method @ubm = self.class.instance_method(:do_it) #create an unbound method > puts "@behavior.class is: #{@__behavior.class}" > end #add a set_behavior method: def set_behavior &b @__behavior = b end > def behavior > @__behavior > end > def run > puts "in #{self}::run" > puts "a is: #{a}, b is: #{b} " > @__behavior.call > end > def inports > @__inports ||=[] > end > def inoutports > @__inoutports ||=[] > end > def outports > @__outports ||=[] > end > def create_accessor str > instance_eval "def #{str}=(val); puts \"self is: #{self}\"; @#{str} = >val; end" > instance_eval "def #{str}; @#{str} ||=0; end" > end > def inputs *in_syms > in_syms.each {|input| > inports << Port.new(input.to_s) > create_accessor input > } > end > #... outputs, inouts, etc. >end > > Now it seems to work: > > AndGate.a=1; AndGate.b=1 > AndGate.run #=> 1 > > a = AndGate.instance() > a.a=0; a.b=0 > a.run #=> 0 #a now is independent of AndGate > ....seems to work, but it also seems a bit convoluted ;-) Phil