如何使用diffy gem显示两个文件之间的差异?

时间:2015-09-06 12:05:24

标签: ruby-on-rails ruby

我正在尝试使用diffy gem比较本地文件和Internet文件。

def show
  require 'open-uri'
  @file1 = File.open('app/assets/files/example.html')
  @file2 = open('http://www.example.com/example.html')
end

在我看来,我有:

<%= puts Diffy::Diff.new(@file1, @file2).to_s(:html_simple) %>

但是,除了我的菜单栏等之外,这在我的视图中不会生成任何内容(也没有错误消息),即使我确保这两个文件确实不同。开发中页面的源代码是空的,可以/应该列出差异。

我也尝试<%= puts Diffy::Diff.new(@file1, @file2, :source => 'files'),但这会产生错误no implicit conversion of File into String。我做错了什么?

更新:服务器日志显示以下内容:

Started GET "/test_diffy" 
<div class="diff">
  <ul>
    <li class="del"><del>#&lt;File:0x007f369032e038&gt;</del></li>

    <li class="ins"><ins>#&lt;File:0x007f36902eab80&gt;</ins></li>

  </ul>
</div>
  Rendered test_diffy/show.html.erb within layouts/application (2.7ms)
  Rendered shared/_shim.html.erb (0.1ms)
  Rendered layouts/_header.html.erb (45.2ms)
  Organization Exists (0.4ms)  SELECT  1 etc.
  Rendered shared/_footer.html.erb (1.9ms)
Completed 200 OK in 1136ms (Views: 386.7ms | ActiveRecord: 1.3ms)

如果我将debugger放置在展示视图中,它会显示@file1#<File:0x00000005cb5728>和类似@file2

Update2:我也在我的观点中尝试过:<%= puts Diffy::Diff.new(@file1, @file2) %>。视图仍然没有显示任何差异,服务器日志包括:

-#<File:0x007f3692bae4e0>
\ No newline at end of file
+#<File:0x007f3693065c18>
\ No newline at end of file

不确定这意味着什么/做什么!?

1 个答案:

答案 0 :(得分:1)

https://github.com/samg/diffy快速浏览一下,初始化程序似乎希望字符串作为参数传递。一种可能的解决方案是在传递之前将输入转换为字符串:

file1_content = File.open('app/assets/files/example.html').read
file2_content = open('http://www.example.com/example.html').read
@diff = Diffy::Diff.new(file1_content, file2_content).to_s(:html_simple)

然后在您的视图中使用

进行渲染
<%= @diff %>