Last active
May 1, 2023 19:24
-
-
Save georgiybykov/943b9f6b1d96315a74198b8d2b3a59ff to your computer and use it in GitHub Desktop.
Compare two
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require 'docx' | |
module Docx | |
# docs | |
class Differences | |
class << self | |
# @param file_paths [Array<String>] ARGV with absolute files pathes | |
# @return [Array<Hash>] | |
def call(file_paths) | |
find_different_paragraphs(*extract_files_paragraphs_data(file_paths)) | |
end | |
private | |
# @param main_paragraphs [Aray<Docx::Elements::Containers::Paragraph>] | |
# @param comparison_paragraphs [Array<Docx::Elements::Containers::Paragraph>] | |
# @return [Array<Hash>] | |
def find_different_paragraphs(main_paragraphs, comparison_paragraphs) | |
different_paragraps = [] | |
main_paragraphs.each_with_index do |paragraph, index| | |
comparison_paragraph = comparison_paragraphs.at(index) | |
if paragraph.text != comparison_paragraph.text | |
different_paragraps << collect_differect_paragraphs_data(paragraph, comparison_paragraph) | |
end | |
end | |
different_paragraps | |
end | |
# @param file_paths [Array<String>] | |
# @return [Array<Docx::Document>] | |
def extract_files_paragraphs_data(file_paths) | |
file_paths.map! { |file_path| Docx::Document.open(file_path).paragraphs } | |
end | |
# @param paragraph [Docx::Elements::Containers::Paragraph] | |
# @param comparison_paragraph [Docx::Elements::Containers::Paragraph] | |
# @return [Hash] | |
def collect_differect_paragraphs_data(paragraph, comparison_paragraph) | |
{ current: paragraph.text, previous: comparison_paragraph.text } | |
end | |
end | |
end | |
# docs | |
class Interface | |
class << self | |
# @param file_paths [Array<Hash>] | |
def render(results) | |
return puts '~~ Nothing was changed ~~' if results.empty? | |
puts 'You could find the differences between text in below paragraphs:' | |
results.each.with_index(1) do |result, index| | |
puts <<~TEXT | |
********************************************************************************************* | |
#{index}) | |
Current text: | |
#{result[:current]} | |
Previous text: | |
#{result[:previous]} | |
TEXT | |
end | |
end | |
end | |
end | |
end` | |
Docx::Differences | |
.call([ARGV[0], ARGV[1]]) | |
.then { Docx::Interface.render(_1) } | |
=begin | |
How to run: | |
$ ruby compare_docx.rb '/home/user/folder/target_file_name.docx' '/home/user/folder/comparison_file_name.docx' | |
You have to set the `rb` file and then pass the target file with the file to compare in the following ARGV's (arguments). | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment