Skip to content

Instantly share code, notes, and snippets.

@dgorodnichy
Last active April 6, 2020 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgorodnichy/e52326b5f1d211a2ad2a44c901a2b27a to your computer and use it in GitHub Desktop.
Save dgorodnichy/e52326b5f1d211a2ad2a44c901a2b27a to your computer and use it in GitHub Desktop.
Dependency injection example
posts = Posts.new
posts.source = PostsSources::FakeMedium
posts.user_posts
posts = Posts.new
posts.source = PostsSources::Medium
posts.user_posts
class Medium
cattr_accessor :adapter
def initialize(name = nil)
@client = adapter.new(name)
end
def posts
@client.user_posts
end
end
class Posts
cattr_accessor :source
def initialize
@client = source.new
end
def posts(args)
@client.user_posts(args)
end
end
module PostsAdapter
class Fake
def initialize(username)
@client = OpenStruct.new(
posts: [
{
title: 'Signal v Noise exits Medium[Fake adapter]',
...
}
]
)
end
def user_posts
@client.posts
end
end
end
module PostsAdapter
class Medium
def initialize(username)
@client = MediumAPI.new(username)
end
def user_posts
@client.posts
end
end
end
RSpec.configure do |config|
config.around do |example|
# keep old adapter to use after test runs
default_source = PostsSources::Medium
# set our in-memory adapter
Posts.adapter = PostsSources::Fake
# run the test
example.run
# put back the previous adapter
Posts.adapter = default_source
end
end
class Posts
cattr_accessor :source
self.adapter = PostsSources::Medium
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment