R/write_datamodel.R

Defines functions empty_line make_field write_datamodel

write_datamodel = function(model, filepath, name = NULL){
  maxwidth = max(nchar(model_names(model)))

  fields = Map(make_field,
               model_names(model),
               maxwidth,
               model_types(model),
               model_widths(model),
               model_decimals(model),
               model_labels(model))
  header = paste0('DATAMODEL ', name, '\nFIELDS')
  content = paste(fields, collapse = '\n')
  footer = 'ENDMODEL'
  text = paste(header, content, footer, sep = '\n')
  readr::write_file(text, filepath)
}

make_field = function(name, max_char, type, width, dec = NA, levels = NA){
  name = format(name, width = max_char)
  width = as.character(width)

  # if a decimal is given, change [] part to incorporate it
  if (!is.na(dec)){
    paste0(width, ',', as.character(dec))
  }

  if (type == 'ENUM'){
    tabwidth = nchar(sprintf('  %s : (', name))
    field = sprintf('  %s : (%s)',
                    name,
                    paste(levels,
                          collapse = sprintf(',\n%s', empty_line(tabwidth))))
  }
  else if (type == 'DATETYPE'){
    field = sprintf('  %s : %s',
                    name,
                    type)
  }
  else {
    field = sprintf('  %s : %s[%s]',
                    name,
                    type,
                    width)
  }
}

empty_line = function(nchars){
  paste(replicate(nchars, ' '), collapse = '')
}

Try the blaise package in your browser

Any scripts or data that you put into this service are public.

blaise documentation built on Aug. 18, 2023, 5:06 p.m.