Skip to content

Instantly share code, notes, and snippets.

@shakemurasan
Last active July 15, 2017 04:58
Show Gist options
  • Save shakemurasan/77bfe5f9418650876db8706c7aba72fe to your computer and use it in GitHub Desktop.
Save shakemurasan/77bfe5f9418650876db8706c7aba72fe to your computer and use it in GitHub Desktop.
Example of "Naught" ( https://github.com/avdi/naught )
class NullObjectExample
require 'naught'
NullObject = Naught.build
def null_object
null = NullObject.new
null.foo # => nil
null.bar # => nil
end
end
class BlackHoleExample
require 'naught'
BlackHole = Naught.build do |config|
config.black_hole
end
def black_hole
null = BlackHole.new
null.foo # => <null>
null.foo.bar.baz # => <null>
null << "hello" << "world" # => <null>
end
end
class MimicExample
require 'naught'
NullIO = Naught.build do |config|
config.mimic IO
end
def mimic
null_io = NullIO.new
null_io << "foo" # => nil
null_io.readline # => nil
null_io.foobar # =>
# undefined method `foobar' for <null:IO>:MimicExample::NullIO (NoMethodError)
end
end
class MimicDefineMethodExample
require 'naught'
NullIO = Naught.build do |config|
config.mimic IO
def relation
true
end
def readline
"This is mimic!"
end
end
def mimic
null_io = NullIO.new
null_io << "foo" # => nil
null_io.relation # => true
null_io.readline # => "This is mimic!"
end
end
module PracticalExample
# 偽のAPI
module Hogehoge
module Type
class Record
def initialize(_args); end
end
end
class Api
def initialize(_init_params); end
def register(_record)
raise "Mimicになっていればここには到達しない"
end
def bulk_register(_records)
raise "Mimicになっていればここには到達しない"
end
end
end
# APIを利用するクラス
class HogehogeApiAdapter
require 'naught'
NullObject = Naught.build { |config| config.singleton }
HogehogeApiMimic = Naught.build do |config|
config.mimic Hogehoge::Api
end
def initialize(init_params)
# 実際には、決め打ちでfalseにしている部分を環境の判別にする
@api = false ? Hogehoge::Api(init_params).new : HogehogeApiMimic.new
end
# Hogehoge::Apiに生えているメソッドは全て握り潰されるので、APIクラスの先にある実装を意識する必要がない
def insert(args)
record = Hogehoge::Type::Record.new(args)
@api.register(record)
end
def bulk_insert(args_array)
records = args_array.map { |args| Hogehoge::Type::Record.new(args) }
@api.bulk_register(records)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment