Rodrigo Souza Rodrigo Souza - 12 days ago 5
Ruby Question

how to parse LDAP into Ruby data?

I'm trying consume a LDAP database of users that I have and I already made some previous text processing so that I have a text like this:

uid: angelica
cn: Angelica Turaca
homeDirectory: /home/exaluno/angelica
mail: angelica@linux.ime.usp.br,

uid: ljunior
cn: Lourinaldo Anastacio da Silva Junior
homeDirectory: /home/exaluno/ljunior
mail: ljunior@linux.ime.usp.br,

uid: acvm
cn: Ana Cristina Vieira de Melo
homeDirectory: /home/prof/acvm
mail: acvm@linux.ime.usp.br,


It contains all data that I want to have. I just would like to transform it into something like:

users[0]['uid'] #angelica
users[1]['mail'] #ljunior@linux.ime.usp.br


What would be the easiest way?

Max Max
Answer

It's not pretty, but some regexes do the job quickly:

obj = {}
users = []

ldap_file.each_line do |line|
  if line =~ /([^:]+): (.*?),?$/
    obj[$1] = $2
    if line =~ /,$/
      users << obj
      obj = {}
    end
  else
    warn "Failed to match: #{line}"
  end
end

A more elegant solution (though you need the whole text in memory at once)

users = ldap_text.split(/,\s*/m).map do |grp|
  grp.each_line.map { |line| line.strip.split(/:\s*/) }.to_h
end
Comments