taw*_*taw 11 ruby code-formatting
这是一个最佳实践问题.有明显的方法可以做到这一点,其中没有一个看起来很正确.
我经常需要测试是否产生了一些多行字符串.这通常会打破缩进,使一切看起来像一团糟:
class TestHelloWorld < Test::Unit::TestCase
def test_hello
assert_equal <<EOS, hello_world
Hello, world!
World greets you
EOS
end
end
Run Code Online (Sandbox Code Playgroud)
随着<<-我在这里可以缩进文档的盯防,但是它不会删除里面定界符缩进,它仍然看起来太可怕了.
class TestHelloWorld < Test::Unit::TestCase
def test_hello
assert_equal <<-EOS, hello_world
Hello, world!
World greets you
EOS
end
end
Run Code Online (Sandbox Code Playgroud)
这让我缩进,但测试线的可读性受到影响.这gsub真的感觉不对劲.
class TestHelloWorld < Test::Unit::TestCase
def test_hello
assert_equal <<-EOS.gsub(/^ {6}/, ""), hello_world
Hello, world!
World greets you
EOS
end
end
Run Code Online (Sandbox Code Playgroud)
有没有办法测试这种真正可读的多行字符串?
小智 9
如果您正在构建Rails应用程序,请尝试使用strip_heredoc,否则您可能始终需要active_support核心扩展.
您的示例可能如下所示:
require 'active_support/core_ext'
class TestHelloWorld < Test::Unit::TestCase
def test_hello
assert_equal <<-EOS.strip_heredoc, hello_world
Hello, world!
World greets you
EOS
end
end
Run Code Online (Sandbox Code Playgroud)
如果您确实不想包含它们,则会从active_support复制以下代码,以及如何处理格式设置的示例.
class String
def try(*a, &b)
if a.empty? && block_given?
yield self
else
__send__(*a, &b)
end
end
def strip_heredoc
indent = scan(/^[ \t]*(?=\S)/).min.try(:size) || 0
gsub(/^[ \t]{#{indent}}/, '')
end
end
Run Code Online (Sandbox Code Playgroud)
就个人而言,我认为Ruby的缩进here文档是无用的,他们应该工作更喜欢猛砸缩进here文档,也剥夺空格内的串...
无论如何,有几个图书馆试图处理这种情况.有很多库试图解决这个问题:
| 归档时间: |
|
| 查看次数: |
9578 次 |
| 最近记录: |