Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add #to_ary to Diff::LCS::Change and Diff::LCS::ContextChange #47

Merged
merged 2 commits into from Jan 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions lib/diff/lcs.rb
Expand Up @@ -181,6 +181,20 @@ def diff(seq1, seq2, callbacks = nil, &block) # :yields diff changes:
# Class argument is provided for +callbacks+, #diff will attempt to
# initialise it. If the +callbacks+ object (possibly initialised) responds
# to #finish, it will be called.
#
# Each element of a returned array is a Diff::LCS::ContextChange object,
# which can be implicitly converted to an array.
#
# Diff::LCS.sdiff(a, b).each do |action, (old_pos, old_element), (new_pos, new_element)|
# case action
# when '!'
# # replace
# when '-'
# # delete
# when '+'
# # insert
# end
# end
def sdiff(seq1, seq2, callbacks = nil, &block) #:yields diff changes:
diff_traversal(:sdiff, seq1, seq2, callbacks || Diff::LCS::SDiffCallbacks,
&block)
Expand Down
4 changes: 4 additions & 0 deletions lib/diff/lcs/change.rb
Expand Up @@ -41,6 +41,8 @@ def to_a
[ @action, @position, @element ]
end

alias to_ary to_a

def self.from_a(arr)
arr = arr.flatten(1)
case arr.size
Expand Down Expand Up @@ -132,6 +134,8 @@ def to_a
]
end

alias to_ary to_a

def inspect(*args)
to_a.inspect
end
Expand Down
24 changes: 24 additions & 0 deletions spec/change_spec.rb
Expand Up @@ -62,4 +62,28 @@
it { should_not be_finished_a }
it { should be_finished_b }
end

describe "as array" do
it "should be converted" do
action, position, element = described_class.new('!', 0, 'element')
expect(action).to eq '!'
expect(position).to eq 0
expect(element).to eq 'element'
end
end
end

describe Diff::LCS::ContextChange do
describe "as array" do
it "should be converted" do
action, (old_position, old_element), (new_position, new_element) =
described_class.new('!', 1, 'old_element', 2, 'new_element')

expect(action).to eq '!'
expect(old_position).to eq 1
expect(old_element).to eq 'old_element'
expect(new_position).to eq 2
expect(new_element).to eq 'new_element'
end
end
end