Skip to content

Instantly share code, notes, and snippets.

@kmayer
Last active December 14, 2015 02:59
Show Gist options
  • Select an option

  • Save kmayer/5017936 to your computer and use it in GitHub Desktop.

Select an option

Save kmayer/5017936 to your computer and use it in GitHub Desktop.
Replace dynamic method receptor with dynamic method definition
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