Skip to content

Instantly share code, notes, and snippets.

@kkchu791
Last active November 15, 2015 21:52
Show Gist options
  • Save kkchu791/97e543dc18b0400c56ef to your computer and use it in GitHub Desktop.
Save kkchu791/97e543dc18b0400c56ef to your computer and use it in GitHub Desktop.
# how do you mix module "Mixin" into class Charlie, such that I can call Charlie.method1?
module Mixin
def method1
"method1"
end
end
class Charlie
include Mixin
def self.method1
Charlie.new.method1
end
end
p Charlie.method1
# How do you mix module "Mixin" into Charlie, such that I can call method1 as Charlie.new.method1?
module Mixin
def method1
"method1"
end
end
class Charlie
include Mixin
end
p Charlie.new.method1
# Part 2
module Mixin
def self.method1
"method1"
end
def method1
Mixin.method1
end
end
class Charlie
include Mixin
def self.method1
Charlie.new.method1
end
end
p Charlie.new.method1
p Charlie.method1
@charliemcelfresh
Copy link

mixin1.rb

Kirk you took the long way on this one -- all you need to do is this:

module Mixin
  def method1
    'method1'
  end
end

class Charlie
  extend Mixin
end

mixin2.rb
good!

mixin3.rb

So close! You made the same mistake as you made on mixin1.rb; otherwise, this is the idiom i was looking for. Treat Mixin's self.method1 as a sort of private method to the module, then make a method called method1 in Mixin, that calls self.method1. Nice! But burn "extended" into your brain!

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