Module: Bismas::XML

Extended by:
Bismas, XML
Included in:
XML
Defined in:
lib/bismas/xml.rb

Constant Summary

Constants included from Bismas

CATEGORY_CHAR_SKIP, CHARS, DEFAULT_CATEGORY_LENGTH, DEFAULT_ENCODING, DEFAULT_PADDING_LENGTH, REGEX, VERSION

Instance Method Summary collapse

Methods included from Bismas

amend_encoding, chars, encode, execute, execute_options, filter, input_options, mapping, regex, require_gem, safe_yaml, to_xml

Instance Method Details

#run(options, &block) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/bismas/xml.rb', line 37

def run(options, &block)
  block ||= method(:abort)

  require_gem 'builder'

  block['Schema file is required'] unless schema_file = options[:schema]
  block["No such file: #{schema_file}"] unless File.readable?(schema_file)

  schema = Schema.parse_file(schema_file)

  execute = execute_options(options, &block)
  mapping = mapping(options[:mapping], &block)

  records_element, record_element = case options[:type].to_s
    when 'solr' then %w[add doc]
    else             %w[records record]
  end

  records_attributes = {
    name:        schema.name,
    description: schema.title,
    mtime:       File.mtime(options[:input]).xmlschema
  }

  reader_options = input_options(options, schema.category_length)

  schema, encoding = mapping.apply(schema), options[:output_encoding]

  execute[0][bind1 = binding]

  File.open_file(options[:output], {}, 'wb') { |f|
    xml = Builder::XmlMarkup.new(indent: 2, target: f)
    xml.instance_eval("@encoding = #{encoding.inspect}") if encoding
    xml.instruct!

    xml.method_missing(records_element, records_attributes) {
      Reader.parse_file(options[:input], reader_options) { |id, record|
        xml.method_missing(record_element, id: id) {
          execute[1][bind2 = binding]
          record = mapping.apply(encode(record, encoding))

          execute[2][bind2]
          record.sort_by { |key,| key }.each { |key, values|
            field_attributes = { name: key }
            desc = Array(schema[key]).join('/')
            field_attributes[:description] = desc unless desc.empty?

            Array(values).each { |value| xml.field(value, field_attributes) }
          }
        }
      }
    }
  }

  execute[3][bind1]
end