Skip to content

Commit

Permalink
Add comprehensive tests for YAML filter with various options
Browse files Browse the repository at this point in the history
  • Loading branch information
buty4649 committed Dec 22, 2024
1 parent 119bf84 commit 27fcf7d
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 5 deletions.
16 changes: 15 additions & 1 deletion mrblib/rf/00filter/yaml.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@ module Filter
class Yaml < Base
class << self
def config
@config ||= Struct.new(:no_doc, :boolean_mode).new.tap do |config|
@config ||= Struct.new(:no_doc, :boolean_mode, :raw).new.tap do |config|
config.no_doc = true
config.boolean_mode = true
config.raw = false
end
end

def configure(opt)
opt.on('-r', '--raw-string', 'output raw strings') do
config.raw = true
end
opt.on('--disable-boolean-mode', 'consider true/false/null as yaml literal') do
config.boolean_mode = false
end
Expand All @@ -26,6 +30,10 @@ def boolean_mode?
config.boolean_mode
end

def raw?
config.raw
end

def format(val, record)
return unless yaml_obj = obj_to_yaml(val, record)

Expand All @@ -36,6 +44,12 @@ def format(val, record)

def obj_to_yaml(val, record)
case val
when String
if raw?
val
else
val.to_yaml(colorize:)
end
when MatchData
record.to_yaml(colorize:)
when Regexp
Expand Down
28 changes: 24 additions & 4 deletions spec/filter/yaml_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,32 @@
context 'with -r option' do
describe 'Output string' do
let(:input) { load_fixture('yaml/multibyte_string.yml') }
let(:output) { '🍣🍣🍣' }
let(:args) { '-t yaml -r _' }
let(:expect_output) { "🍣🍣🍣\n" }

before { run_rf('-t yaml -r _', input) }
it_behaves_like 'a successful exec'
end

it { expect(last_command_started).to be_successfully_executed }
it { expect(last_command_started).to have_output output_string_eq output }
describe 'Ouput yaml to JSON string' do
let(:input) { load_fixture('json/hash.json') }
let(:args) { '-t yaml -r "_.to_json(pretty_print: true)"' }
let(:expect_output) do
<<~OUTPUT
{
"foo": 1,
"bar": {
"baz": [
"a",
"b",
"c"
]
},
"foo bar": "foo bar"
}
OUTPUT
end

it_behaves_like 'a successful exec'
end
end

Expand Down
1 change: 1 addition & 0 deletions spec/global_options/help_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
-m, --minify minify json output
yaml options:
-r, --raw-string output raw strings
--disable-boolean-mode consider true/false/null as yaml literal
--[no-]doc [no] output document sperator (refers to ---) (default:--no-doc)
TEXT
Expand Down

0 comments on commit 27fcf7d

Please sign in to comment.