views:

59

answers:

1

I have a Mix-in that reflects on the receiver class to generate some code. This means that I need to execute the class method at the end of the class definition, like in this trivially dumbed down example:

module PrintMethods
  module ClassMethods
    def print_methods
      puts instance_methods
    end
  end

  def self.included(receiver)
    receiver.extend ClassMethods
  end
end

class Tester
  include PrintMethods

  def method_that_needs_to_print
  end

  print_methods
end

I'd like to have the mixin do this for me automatically, but I can't come up with a way. My first thought was to add receiver.print_methods to self.included in the mixin, but that won't work because the method that I want it to reflect on has not been declared yet. I could call include PrintMethods at the end of the class, but that feels like bad form.

Are there any tricks to make this happen so I don't need to call print_methods at the end of the class definition?

+1  A: 

First of all, there's no end of class definition. Remember that in Ruby you can reopen the Tester class method after you have 'initialized' it, so the interpreter can't know where the class 'ends'.

The solution I can come up with is to make the class via some helper method, like

module PrintMethods
  module ClassMethods
    def print_methods
      puts instance_methods
    end
  end

  def self.included(receiver)
    receiver.extend ClassMethods
  end
end

class Object
  def create_class_and_print(&block)
    klass = Class.new(&block)
    klass.send :include, PrintMethods
    klass.print_methods
    klass
  end
end

Tester = create_class_and_print do
  def method_that_needs_to_print
  end
end

But certainly having to define classes this way makes my eyes hurt.

Chubas
Ouch. Yeah, that hurts. It also has print_methods happen every time an instance is created. Ultimately, it only needs to be done once, or when the class is modified. For that matter, I could just add an initialize instance method on the class... I think I am just going to have to call the method at the end of the class.
Brian Genisio
`print_methods` isn't called when you create an instance of Tester, just when you create the class. Oh, and for that matter, I don't know why I defined create_class_and_print in the Object class in the first place, you could have just defined it in a module, or somewhere else outside of Object.
Chubas
OK, I get it. Yeah, I think that this is probably about the best way to do what I want to do... but I will probably just require that it be called and be done with it. Thanks.
Brian Genisio