Last active
August 29, 2015 13:56
-
-
Save steven-ferguson/9083414 to your computer and use it in GitHub Desktop.
Book Data Merger
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
require 'json' | |
class BookMetaMerge | |
def initialize(output_file='result_example.file') | |
@output_file = output_file | |
end | |
def merge_files(file1, file2) | |
hash_one = JSON.parse(file1) | |
hash_two = JSON.parse(file2) | |
merged_json = hash_merge(hash_one, hash_two).to_json | |
write_to_output_file(merged_json) | |
end | |
private | |
def write_to_output_file(json) | |
File.open(@output_file, 'w') { |file| file.write(json) } | |
end | |
def hash_merge(hash_one, hash_two) | |
hash_one.merge(hash_two) do |key, oldval, newval| | |
if oldval == newval | |
oldval | |
elsif oldval.is_a?(Hash) && newval.is_a?(Hash) | |
hash_merge(oldval, newval) | |
else | |
[newval, oldval] | |
end | |
end | |
end | |
end | |
merge = BookMetaMerge.new | |
merge.merge_files(File.read('source1.file'), File.read('source2.file')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment