Class: Diffy::Diff

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/diffy/diff.rb

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string1, string2, options = {}) ⇒ Diff

supported options

:diff

A cli options string passed to diff

:source

Either strings or files. Determines whether string1 and string2 should be interpreted as strings or file paths.



16
17
18
19
20
21
22
# File 'lib/diffy/diff.rb', line 16

def initialize(string1, string2, options = {})
  @options = {:diff => '-U 10000', :source => 'strings'}.merge(options)
  if ! ['strings', 'files'].include?(@options[:source])
    raise ArgumentError, "Invalid :source option #{@options[:source].inspect}. Supported options are 'strings' and 'files'."
  end
  @string1, @string2 = string1, string2
end

Class Attribute Details

.default_formatObject



5
6
7
# File 'lib/diffy/diff.rb', line 5

def default_format
  @default_format || :text
end

Instance Attribute Details

#diffObject (readonly)

Returns the value of attribute diff.



10
11
12
# File 'lib/diffy/diff.rb', line 10

def diff
  @diff
end

#optionsObject (readonly)

Returns the value of attribute options.



10
11
12
# File 'lib/diffy/diff.rb', line 10

def options
  @options
end

#string1Object (readonly)

Returns the value of attribute string1.



10
11
12
# File 'lib/diffy/diff.rb', line 10

def string1
  @string1
end

#string2Object (readonly)

Returns the value of attribute string2.



10
11
12
# File 'lib/diffy/diff.rb', line 10

def string2
  @string2
end

Instance Method Details

#eachObject



45
46
47
48
49
50
51
52
53
# File 'lib/diffy/diff.rb', line 45

def each
  lines = diff.split("\n").reject{|x| x =~ /^---|\+\+\+|@@|\\\\/ }.
    map{|line| line + "\n"}
  if block_given?
    lines.each{|line| yield line}
  else
    Enumerable::Enumerator.new(lines)
  end
end

#each_chunkObject



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/diffy/diff.rb', line 55

def each_chunk
  old_state = nil
  chunks = inject([]) do |cc, line|
    state = line.each_char.first
    if state == old_state
      cc.last << line
    else
      cc.push line.dup
    end
    old_state = state
    cc
  end

  if block_given?
    chunks.each{|chunk| yield chunk }
  else
    Enumerable::Enumerator.new(chunks)
  end
end

#tempfile(string) ⇒ Object



75
76
77
78
79
80
# File 'lib/diffy/diff.rb', line 75

def tempfile(string)
  t = Tempfile.new('diffy')
  t.print(string)
  t.flush
  t.path
end

#to_s(format = nil) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/diffy/diff.rb', line 82

def to_s(format = nil)
  format ||= self.class.default_format
  formats = Format.instance_methods(false).map{|x| x.to_s}
  if formats.include? format.to_s
    enum = self
    enum.extend Format
    enum.send format
  else
    raise ArgumentError,
      "Format #{format.inspect} not found in #{formats.inspect}"
  end
end