Aug 19, 2011

Ruby super metaprogramming

I'm posting as a reference. What it does is that it will turn every method in a class into a class method and all of them will be one-level curriable.


class Validator

@@__being_checked_method = nil

def self.method_added(method_name)

puts "#{method_name} added to #{self}"

return if method_name == :validate
return if method_name.to_s.match(/^validation__proxy__/)
return if @@__being_checked_method == method_name

@@__being_checked_method = method_name

puts method_name
new_name = "validation__proxy__#{method_name}".to_sym

alias_method new_name, method_name

define_singleton_method(method_name) { |*args|
puts args.length
puts args.inspect

l = lambda(&(self.new.method(new_name))).curry

args.each { |a|
l = l.curry[a]
}

return l
}

end

class << self
def validate(lamb_func)
puts "hello"
end
end

end

class KratooValidator < Validator

def max_length(length,value)
puts "#{length} #{value}"
end

validate max_length(5)

end


puts KratooValidator.new.validation__proxy__max_length(5,10)
puts KratooValidator.max_length(5).call(12)