Class: Xcop::Document

Inherits:
Object
  • Object
show all
Defined in:
lib/xcop.rb

Overview

One document.

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Document

Ctor.

path

Path of it



72
73
74
# File 'lib/xcop.rb', line 72

def initialize(path)
  @path = path
end

Instance Method Details

#diffObject

Return the difference, if any (empty string if everything is clean).



77
78
79
80
81
82
83
84
# File 'lib/xcop.rb', line 77

def diff
  xml = Nokogiri::XML(File.open(@path), &:noblanks)
  ideal = xml.to_xml(indent: 2)
  now = File.read(@path)
  Differ.format = :color
  return Differ.(ideal, now).to_s unless now == ideal
  ''
end

#fix(license = '') ⇒ Object

Fixes the document.



98
99
100
101
102
103
104
105
106
107
108
# File 'lib/xcop.rb', line 98

def fix(license = '')
  xml = Nokogiri::XML(File.open(@path), &:noblanks)
  unless license.empty?
    xml.xpath('/comment()').remove
    xml.children.before(
      Nokogiri::XML::Comment.new(xml, "\n#{license.strip}\n")
    )
  end
  ideal = xml.to_xml(indent: 2)
  File.write(@path, ideal)
end

#ldiff(license) ⇒ Object

Return the difference for the license.



87
88
89
90
91
92
93
94
95
# File 'lib/xcop.rb', line 87

def ldiff(license)
  xml = Nokogiri::XML(File.open(@path), &:noblanks)
  comment = xml.xpath('/comment()')[0]
  now = comment.nil? ? '' : comment.text.to_s.strip
  ideal = license.strip
  Differ.format = :color
  return Differ.(ideal, now).to_s unless now == ideal
  ''
end