通缉:最优雅的方式来编写匿名类进行嘲弄

时间:2021-01-15 20:19:47

I'm mocking part of the Net::SFTP for my tests. The following mimicks dir.entries, entry.name and entry.attributes.size by reading locally from fixture_path:

我正在为我的测试嘲笑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

An alternative would be:

另一种选择是:

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

Both versions work absolutely fine, however, I don't like neither of them. The Class.new do ... end.new is just ugly and I'm no fan of object = Object.new; ...; object code at all.

两个版本的工作都很好,但是,我不喜欢它们。 Class.new做... end.new只是丑陋而且我不喜欢object = Object.new; ...;目标代码。

Is there a third way to write this?

有没有第三种方式来写这个?

1 个解决方案

#1


0  

How about actually declaring the class?

实际上宣布课程怎么样?

class MockedSFTP

  mattr_accessor :fixture_path

  class Dir
    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

  def dir
    Dir.new
  end
end

#1


0  

How about actually declaring the class?

实际上宣布课程怎么样?

class MockedSFTP

  mattr_accessor :fixture_path

  class Dir
    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

  def dir
    Dir.new
  end
end