Class: YRB

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

Overview

Processes Yahoo! Resource Bundle format translation files and converts them to a hash.

Options

:unique    (true/false) Raise an error if a file contains duplicated values. Defaults to true.

Defined Under Namespace

Classes: DuplicateKeyError

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Attribute Details

#pathObject

Returns the value of attribute path.



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

def path
  @path
end

Class Method Details

.comment?(line) ⇒ Boolean

Is this line a valid comment in YRB?

Returns:

  • (Boolean)


23
24
25
# File 'lib/yrb.rb', line 23

def self.comment?(line)
  line =~ /^[\s]*#/
end

.key_and_value_from_line(line) ⇒ Object

Is this line valid YRB syntax?



29
30
31
32
33
34
35
# File 'lib/yrb.rb', line 29

def self.key_and_value_from_line(line)
  if line =~ /^([^\=]+)=(.+)/
    return $1, $2.strip
  else
    return nil, nil
  end
end

.load_file(path, options = {}) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/yrb.rb', line 12

def self.load_file(path, options={})
  @path = path
  
  unless options.has_key?(:unique)
    options[:unique] = true
  end
  parse(File.read(path), options)
end

.parse(template, options = {}) ⇒ Object

Parse YRB and add it to a hash. Raise an error if the key already exists in the hash.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/yrb.rb', line 39

def self.parse(template, options={})
  @hash = {}
  lines = template.split("\n")
  lines.each do |line|
    unless comment?(line)
      key, value = key_and_value_from_line(line)
      if key
        if options[:unique] && @hash.has_key?(key)
          raise DuplicateKeyError.new("Duplicate key error: #{key}")
        end
        @hash[key] = value
      end
    end
  end
  @hash
end