Class: GetText::ErbParser

Inherits:
Object
  • Object
show all
Defined in:
lib/gettext/tools/parser/erb.rb

Constant Summary collapse

MAGIC_COMMENT =
/\A#coding:.*\n/
@@erb_accept_keyword_arguments =
ERB.instance_method(:initialize).parameters.any? {|type, _| type == :key}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, options = {}) ⇒ ErbParser

Returns a new instance of ErbParser.

Parameters:

  • path (String)

    eRuby script path to be parsed

  • options (Hash) (defaults to: {})


55
56
57
58
# File 'lib/gettext/tools/parser/erb.rb', line 55

def initialize(path, options={})
  @path = path
  @options = options
end

Class Method Details

.init(config) ⇒ Object

Sets some preferences to parse ERB files.

  • config: a Hash of the config. It can takes some values below:
    • :extnames: An Array of target files extension. Default is [".rhtml"].


25
26
27
28
29
# File 'lib/gettext/tools/parser/erb.rb', line 25

def init(config)
  config.each{|k, v|
    @config[k] = v
  }
end

.parse(path, options = {}) ⇒ Array<POEntry>

Parses eRuby script located at path.

This is a short cut method. It equals to new(path, options).parse.

Returns:

  • (Array<POEntry>)

    Extracted messages

See Also:



45
46
47
48
# File 'lib/gettext/tools/parser/erb.rb', line 45

def parse(path, options={})
  parser = new(path, options)
  parser.parse
end

.target?(file) ⇒ Boolean

:nodoc:

Returns:

  • (Boolean)


31
32
33
34
35
36
# File 'lib/gettext/tools/parser/erb.rb', line 31

def target?(file) # :nodoc:
  @config[:extnames].each do |v|
    return true if File.extname(file) == v
  end
  false
end

Instance Method Details

#detect_encoding(erb_source) ⇒ Object



86
87
88
89
90
91
92
# File 'lib/gettext/tools/parser/erb.rb', line 86

def detect_encoding(erb_source)
  if /\A#coding:(.*)\n/ =~ erb_source
    $1
  else
    nil
  end
end

#parseArray<POEntry>

Extracts messages from @path.

Returns:

  • (Array<POEntry>)

    Extracted messages



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/gettext/tools/parser/erb.rb', line 66

def parse
  content = IO.read(@path)
  if @@erb_accept_keyword_arguments
    erb = ERB.new(content, trim_mode: "-")
  else
    erb = ERB.new(content, nil, "-")
  end
  src = erb.src

  # Force the src encoding back to the encoding in magic comment
  # or original content.
  encoding = detect_encoding(src) || content.encoding
  src.force_encoding(encoding)

  # Remove magic comment prepended by erb in Ruby 1.9.
  src = src.gsub(MAGIC_COMMENT, "")

  RubyParser.new(@path, @options).parse_source(src)
end