Module: StripComments

Defined in:
lib/strip_comments.rb,
lib/strip_comments/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"0.4.1"

Class Method Summary collapse

Class Method Details

.strip(language, str) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/strip_comments.rb', line 8

def self.strip(language, str) 
  case language
  when "yaml", "yml"
    strip_yaml(str)
  when "glsl"
    strip_glsl(str)
  when "css"
    strip_css(str)
  when "properties"
    strip_properties(str)
  when "html"
    strip_html(str)
  when "po", "pot"
    strip_properties(str)
  else
    raise Error.new("unknown language '#{language}'")
  end
end

.strip_c_like(str) ⇒ Object



63
64
65
66
# File 'lib/strip_comments.rb', line 63

def self.strip_c_like(str)
  str.gsub(/\/\/[^\n]+/, '')
      .gsub(/\/\*.+?\*\//m, '')
end

.strip_css(str) ⇒ Object



59
60
61
# File 'lib/strip_comments.rb', line 59

def self.strip_css(str)
  strip_c_like(str)
end

.strip_glsl(str) ⇒ Object



55
56
57
# File 'lib/strip_comments.rb', line 55

def self.strip_glsl(str)
  strip_c_like(str)
end

.strip_html(str) ⇒ Object



68
69
70
# File 'lib/strip_comments.rb', line 68

def self.strip_html(str)
  str.gsub(/<!--.+?-->/m, '')
end

.strip_properties(str) ⇒ Object



51
52
53
# File 'lib/strip_comments.rb', line 51

def self.strip_properties(str)
  str.gsub(/(\n)[\t ]*#[^\n]+/, '\\1').gsub(/^#[^\n]+/, '\\1')
end

.strip_yaml(str) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/strip_comments.rb', line 27

def self.strip_yaml(str)
  stripped_strings_to_not_be_uncommented = {}

  str.gsub!(/"([^\n"]+)"/) do |m|
    strip_key = "__STRIPPED_KEY_#{stripped_strings_to_not_be_uncommented.size}__"
    stripped_strings_to_not_be_uncommented[strip_key] = m
    strip_key
  end

  str.gsub!(/'([^\n']+)'/) do |m|
    strip_key = "__STRIPPED_KEY_#{stripped_strings_to_not_be_uncommented.size}__"
    stripped_strings_to_not_be_uncommented[strip_key] = m
    strip_key
  end

  str.gsub!(/#[^\n]+/, '')

  stripped_strings_to_not_be_uncommented.reverse_each do |k,v|
    str.gsub!(k, v)
  end

  str
end