Is there a way to tell Psych in ruby to using inline mode?
Question
environment: ruby1.9.3 , psych(any version) ex:
o = { 'hash' => { 'name' => 'Steve', 'foo' => 'bar' } }
=> {"hash"=>{"name"=>"Steve", "foo"=>"bar"}}
#is there a inline option?
puts Psych.dump(o,{:inline =>true})
real result:
---
hash:
name: Steve
foo: bar
expect output:
---
hash: { name: Steve, foo: bar }
Solution
Psych supports this, although it isn't at all straightforward.
I've started researching this in my own question on how to dump strings using literal style.
I ended up devising a complete solution for setting various styles for specific objects, including inlining hashes and arrays.
With my script, a solution to your problem would be:
o = { 'hash' => StyledYAML.inline('name' => 'Steve', 'foo' => 'bar') }
StyledYAML.dump o, $stdout
OTHER TIPS
The representable gem provides this in a convenient OOP style.
Considering you have a model User:
user.name => "Andrew"
user.age => "over 18"
You'd now define a representer module to render/parse User instances.
require 'representable/yaml'
module UserRepresenter
include Representable::YAML
collection :hash, :style => :flow
def hash
[name, age]
end
end
After defining the YAML document you simply extend the user instance and render it.
user.extend(UserRepresenter).to_yaml
#=> ---
hash: [Andrew, over 18]
Hope that helps, Andrew!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow