I suggest you choose @matts solution. Besides being more circumspect, it handles scalars correctly.
The trick might be the monkeypatch TreeBuilder#scalar :
y=' en: errors: # Some comment format: "%{attribute} %{message}" # One more comment messages: "1": "Message 1" "2": "Message 2" long_error_message: | This is a multiline message date: format: "YYYY-MM-DD"' require 'yaml' yphc = Class.new(YAML.parser.handler.class) do def scalar value, anchor, tag, plain, quoted, style value = { value: value, line: $line } if style > 1 $line = $parser.mark.line + 1
Actually, we are almost done. It remains only to leave the corrected values ββwith line numbers only in sheets. I did not put this logic into an interview with goals.
def unmark_keys hash hash.map do |k,v| [k.is_a?(Hash) ? k[:value] : k, v.is_a?(Hash) ? unmark_keys(v) : v] end.to_h end p unmark_keys result #β {"en"=> #β {"errors"=> #β { #β "format"=>{:value=>"%{attribute} %{message}", :line=>4}, #β "messages"=> #β { #β "1"=>{:value=>"Message 1", :line=>8}, #β "2"=>{:value=>"Message 2", :line=>9} #β } #β }, #β "long_error_message"=>{ #β :value=>"This is a\nmultiline message\n", :line=>11 #β }, #β "date"=>{"format"=>{:value=>"YYYY-MM-DD", :line=>16}} #β } #β }
Of course, you can get rid of global variables, etc. I tried to simplify the implementation of the kernel as much as possible.
Here we go. Hope this helps.
UPD Thanks to @matt, the code above does not work on scalars:
key1: val1 key2: val2
This syntax is allowed by YAML, but the above approach does not have the ability to handle it correctly. No string will be returned for this. Besides the annoying lack of scalar support, the lines are being reported correctly for anything else, please refer to the comments on this answer for more information.
mudasobwa
source share