【发布时间】:2014-02-03 20:22:01
【问题描述】:
我在为我的测试模拟部分 Net::SFTP。以下通过从fixture_path 本地读取来模仿dir.entries、entry.name 和entry.attributes.size:
class MockedSFTP
mattr_accessor :fixture_path
def dir
Class.new do
def entries(path)
MockedSFTP.fixture_path.join(path.sub(%r{^/}, '')).children.map do |child|
OpenStruct.new(
name: child.basename,
attributes: OpenStruct.new(size: child.size)
)
end
end
end.new
end
end
另一种选择是:
class MockedSFTP
mattr_accessor :fixture_path
def dir
object = Object.new
def object.entries(path)
MockedSFTP.fixture_path.join(path.sub(%r{^/}, '')).children.map do |child|
OpenStruct.new(
name: child.basename,
attributes: OpenStruct.new(size: child.size)
)
end
end
object
end
end
两个版本都工作得很好,但是,我都不喜欢它们。 Class.new do ... end.new 很丑,我根本不喜欢 object = Object.new; ...; object 代码。
有没有第三种写法?
【问题讨论】: