Created
June 19, 2011 21:23
-
-
Save keithrbennett/1034775 to your computer and use it in GitHub Desktop.
Validates that public instance methods of a class are defined.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Shows a crude way to enforce that a class implements | |
| # required methods. Use it like this: | |
| # | |
| # class OkClass | |
| # def foo; end | |
| # def bar; end | |
| # def baz; end | |
| # end | |
| # | |
| # | |
| # class NotOkClass | |
| # def foo; end | |
| # end | |
| # | |
| # | |
| # verifier = InstanceMethodVerifier.new([:foo, :bar, :baz]) | |
| # verifier.verify('OkClass') | |
| # verifier.verify('NotOkClass') | |
| # | |
| # $ ruby instance_method_verifier.rb 14.Jun.11 15.21 | |
| # instance_method_verifier.rb:22:in `verify': Class NotOkClass is missing the following required functions: bar, baz (RuntimeError) | |
| # from instance_method_verifier.rb:42 | |
| class InstanceMethodValidator | |
| attr_accessor :required_function_names | |
| def initialize(required_function_names) | |
| @required_function_names = required_function_names | |
| end | |
| # klass can be either a class name or a class object. | |
| def validate(klass) | |
| if klass.is_a? String | |
| klass = Kernel.const_get(klass) | |
| end | |
| missing_function_names = required_function_names - klass.public_instance_methods | |
| unless missing_function_names.empty? | |
| raise Error.new("Class #{klass} is missing the following required functions: #{missing_function_names.join(", ")}.") | |
| end | |
| end | |
| class Error < RuntimeError | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment