Skip to content

Instantly share code, notes, and snippets.

@mvr
Created April 10, 2009 00:25
Show Gist options
  • Save mvr/92839 to your computer and use it in GitHub Desktop.
Save mvr/92839 to your computer and use it in GitHub Desktop.
class Class
attr_reader :conditional_methods
def defined_when(name, condition, &method)
@conditional_methods ||= {}
@conditional_methods[name.to_sym] = condition
define_method(name) do
if self.instance_eval(&condition)
self.instance_eval(&method)
else
raise NoMethodError.new("undefined method `#{name}' for #{self.inspect}:#{self.class}")
end
end
end
end
class Object
alias :defined_when_original_respond_to? :respond_to?
def respond_to?(sym)
defined_when_original_respond_to?(sym) and self.instance_eval(&self.class.conditional_methods[sym])
end
end
class Array
defined_when(:sum, lambda {
all? { |element|
element.is_a? Numeric
}
}) do
self.inject(0) {|a, b| a + b}
end
end
p [1, 2, 3].respond_to? :wibble # => false
p [1, 2, "WUT"].respond_to? :wibble # => false
p [1, 2, 3].respond_to? :sum # => true
p [1, 2, "WUT"].respond_to? :sum # => false
p [1, 2, 3].sum # => 6
p [1, 2, "WUT"].sum # => NoMethodError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment