Skip to content

Instantly share code, notes, and snippets.

@mynameisrufus
Forked from pmyjavec/gist:5466564
Last active December 16, 2015 17:39
Show Gist options
  • Save mynameisrufus/5471536 to your computer and use it in GitHub Desktop.
Save mynameisrufus/5471536 to your computer and use it in GitHub Desktop.
### Problem, rigid dependency injection ###
class Demo
def initialize
@instancev = Something.new
end
def method_1
do_that
@instancev.something
end
def method_2
filter_something
@instancev.orother
end
end
### Solution (Factory method) ###
class Demo
def something
Something
end
def will_use_something
s = something.new
s.awesome_stuff
end
# `will_use_something` has no side effects
def change_something_state
s = somthing.new.mutate
s.awesome_stuff
end
end
### Solution (Singleton method) ###
class Demo
def something
@something ||= Something.new
end
def will_use_something
something.awesome_stuff
end
# Side effects as `will_use_something` might return something else now.
def change_something_state
something.mutate!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment