Module: DocumentMapper::YamlParsing

Included in:
Document
Defined in:
lib/document_mapper/yaml_parsing.rb

Instance Method Summary collapse

Instance Method Details

#read_yamlObject



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/document_mapper/yaml_parsing.rb', line 5

def read_yaml
  file_path = self.attributes[:file_path]
  @content = File.read(file_path)

  if @content =~ /^(---\s*\n.*?\n?)^(---\s*$\n?)/m
    @content = @content[($1.size + $2.size)..-1]
    self.attributes.update(yaml_load($1, file_path).transform_keys(&:to_sym))
  end

  file_name = File.basename(file_path)
  extension = File.extname(file_path)
  self.attributes.update({
    :file_name => file_name,
    :extension => extension.sub(/^\./, ''),
    :file_name_without_extension => File.basename(file_path, extension)
  })

  if !self.attributes.has_key? :date
    begin
      match = attributes[:file_name].match(/(\d{4})-(\d{1,2})-(\d{1,2}).*/)
      year, month, day = match[1].to_i, match[2].to_i, match[3].to_i
      self.attributes[:date] = Date.new(year, month, day)
    rescue NoMethodError => err
    end
  end

  if self.attributes.has_key? :date
    self.attributes[:year] = self.attributes[:date].year
    self.attributes[:month] = self.attributes[:date].month
    self.attributes[:day] = self.attributes[:date].day
  end

  self.class.define_attribute_methods self.attributes.keys
  self.attributes.keys.each { |attr| self.class.define_read_method attr }
end

#yaml_load(yaml, file) ⇒ Object



41
42
43
44
45
# File 'lib/document_mapper/yaml_parsing.rb', line 41

def yaml_load(yaml, file)
  YAML.load(yaml)
rescue ArgumentError, Psych::SyntaxError
  raise YamlParsingError, "Unable to parse YAML of #{file}"
end