Last active
December 15, 2015 22:59
-
-
Save holsee/5336517 to your computer and use it in GitHub Desktop.
I'm no expert but this is how I would use modules instead of IoC container.
This file contains 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
class Nails | |
def to_s | |
"nails" | |
end | |
end | |
class Glue | |
def to_s | |
"glue" | |
end | |
end | |
class PowerSaw | |
def initialize(power_source) | |
@power_source = power_source | |
end | |
def to_s | |
"#{@power_source} power saw" | |
end | |
end | |
class HandSaw | |
def to_s | |
"hand saw" | |
end | |
end | |
class Electricity | |
def to_s | |
"electrical" | |
end | |
end | |
class Carpenter | |
def build_something | |
puts "Building something in wood with #{fixings} and #{tool}" | |
end | |
end | |
module ManualToolsModule | |
def tool | |
HandSaw.new | |
end | |
def fixings | |
Glue.new | |
end | |
end | |
module PowerToolsModule | |
def power_source | |
Electricity.new | |
end | |
def tool | |
PowerSaw.new power_source | |
end | |
def fixings | |
Nails.new | |
end | |
end | |
# reopening the class to mix the module in | |
class Carpenter | |
include ManualToolsModule | |
end | |
# or (alt registration which replaces first registration) | |
class Carpenter | |
include PowerToolsModule | |
end | |
Carpenter.new.build_something | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I totally get what you are saying here. I guess it's a mindset thing to some degree. Are classes loosely coupled in a dynamic language by default because it's easier to change the behaviour compared to a static language.
I wonder if IoC is more popular in status languages because it is the only way to get nice loosely coupled classes whereas in dynamic languages there are other options that are easy and so people take that approach even if these methods are not strictly IoC/loosely coupled as seen by a purest.
Just a word on testability. For me, being able to mock/test easily is not the goal of IoC but a nice side affect of doing it. Obviously in ruby we can mock anything using the language features but my feeling is that we do this because it's the easy way rather than the "right" way.