Last active
December 14, 2015 02:59
-
-
Save kmayer/5017936 to your computer and use it in GitHub Desktop.
Replace dynamic method receptor with dynamic method definition
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
| private | |
| - def method_missing(method, *args) | |
| - if method.to_s =~ /^create_(.+)$/ | |
| - send("new_#{$1}", *args).tap(&:save!) | |
| - else | |
| - super | |
| - end | |
| + def self.included(base) | |
| + ObjectCreationMethods.public_instance_methods(false).each do |new_method_name| | |
| + next unless new_method_name.to_s =~ /^new_(.+)$/ | |
| + create_method_name = "create_#{$1}" | |
| + base.module_eval <<-RUBY | |
| + def #{create_method_name}(overrides = {}) # def create_foo(overrides = {}) | |
| + #{new_method_name}(overrides).tap(&:save!) # new_foo(overrides).tap(&:save!) | |
| + end # end | |
| + RUBY | |
| + end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment