Skip to content

Instantly share code, notes, and snippets.

@kangkyu
Last active November 15, 2015 23:08
Show Gist options
  • Save kangkyu/c67165d06b1c19039d97 to your computer and use it in GitHub Desktop.
Save kangkyu/c67165d06b1c19039d97 to your computer and use it in GitHub Desktop.
Today's Kata 11-13-2015
=begin
# Question 1. A mixin is a module whose methods you want to use in more than one class. One popular interview question is: How do you use module methods as class methods, and how to you use them as instance methods? In other words, given this module ...
module Mixin
def method1
'method1'
end
end
# and class Charlie
class Charlie
end
# ... how do you mix module "Mixin" into class Charlie, such that I can call Charlie.method1? How do you mix module "Mixin" into Charlie, such that I can call method1 as Charlie.new.method1?
=end
Mixin = Module.new do
def method1
'method1'
end
end
Charlie = Class.new do
self.include Mixin
self.extend Mixin
end
require 'minitest/autorun'
class MixinTest < Minitest::Test
def test_class_method_extend_mixin
assert_equal 'method1', Charlie.method1
end
def test_instance_method_include_mixin
charlie = Charlie.new
assert_equal 'method1', charlie.method1
end
end
=begin
# Question 2. Now suppose we change our Mixin to this:
module Mixin
def self.method1
'method1'
end
end
# How do we make method1 available to class Charlie? Please make sure you test your code before you post your answer.
=end
module Mixin
extend self
def method1
'method1'
end
end
class Charlie
include Mixin
extend Mixin
end
require 'minitest/autorun'
class MixinTest < Minitest::Test
def test_module_method
assert_equal 'method1', Mixin.method1
end
def test_class_method
assert_equal 'method1', Charlie.method1
end
def test_instance_method
charlie = Charlie.new
assert_equal 'method1', charlie.method1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment