Apr14

Extend After

ruby metaprogramming dynamic | comments

I was faced with a situation not too long ago that forced me to copy and paste a lot of code that did the same thing. It was one line, self.save, but still felt too redundant. Then I realized I was using ruby, so why not let it’s magic powers do it for me? I came up with several implementations but used this one in the end:

module After
  def after(*methods, &block)
    methods.each do |name|
      m = self.instance_method(name).bind(self.new)
      define_method name do
        instance_exec m.call, &block
      end
    end
  end
end

It could still be more dynamic in the way it calls the methods. You are forced to call after after you define your class methods, when I’d rather call after at the top of the class definition. Maybe I’ll re-implement this some day (or maybe it already exists?) or optionally fork it and help me out.

Continue reading »

Apr12

Fire and Forget

ruby asynchronous programming | comments

This was an exercise I did for Crowdflower. The idea was to implement a ruby mixin that enabled a Fire and Forget method. I chose to do a simple implementation that forked the method into a seperate process that was also detached. Here’s the code.

Continue reading »
Archive