Skip to content

Instantly share code, notes, and snippets.

@bsodmike
Created June 24, 2013 22:49
Show Gist options
  • Save bsodmike/5854423 to your computer and use it in GitHub Desktop.
Save bsodmike/5854423 to your computer and use it in GitHub Desktop.
Example of conditionally mixing in Instance Methods if the base klass implements certain instance methods
require 'rails/all'
require 'rspec'
require 'pry'
module MyMixin
extend ActiveSupport::Concern
included do
raise NotImplementedError.new("#{self} must implement '#bar'.") unless self.instance_methods.include?(:bar)
send(:include, MixinInstanceMethods)
end
module MixinInstanceMethods
def hai
"Hai Mike!"
end
end
end
class Foo
attr_accessor :bar
include MyMixin
end
f = Foo.new
f.respond_to?(:bar).should == true
f.hai.should == "Hai Mike!"
@bsodmike
Copy link
Author

Commenting out the 'getter' for :bar will cause

conditional_mixin.rb:9:in `block in <module:MyMixin>': Foo must implement '#bar'. (NotImplementedError)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment