On Sun, Feb 24, 2013 at 7:49 PM, Joshua Shane Martin
<josmar52789-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
wrote:> Is the result a Rails model? If so, easy, just build a string and insert
> your variables into the string. You can do this in a model method like so:
No idea, really, why you''d tell someone to rewrite the to_yaml
method...
> On Thursday, February 21, 2013 7:08:18 AM UTC-5, Ruby-Forum.com User wrote:
>>
>> I need to create a method that should return yaml in the following
>> format
>>
>> ---
>> - name: device-1
>> parameters:
>> app_folder: deploy_project
>> app_id: "1"
>> tar_file: deploy_project.tar.gz
>> profile_id: "3"
>> version_id: "2"
>> classes:
>> - install
>>
>> I have all these values (device-1, deploye-project etc) captured into a
>> variable "result" that are coming from the database but i
just need to
>> return them in the above format as a yaml using
>>
>> puts yaml_obj = result.to_yaml
Let''s look at this from the end, you have your desired format in yaml,
if you read it in, you''ll see what structure is produced:
1.9.3-head :002 > isit = YAML.load(File.read(''isit.yml''))
=> [{"name"=>"device-1",
"parameters"=>{"app_folder"=>"deploy_project",
"app_id"=>"1",
"tar_file"=>"deploy_project.tar.gz",
"profile_id"=>"3",
"version_id"=>"2"},
"classes"=>["install"]}]
Since your first item starts with a ''-'', yaml reads this and
thinks
what it will be getting is a list of items, thus the outer portion is
an Array.
For the first (and only element) of the array, there is a Hash with three keys:
1.9.3-head :006 > isit.first.keys
=> ["name", "parameters", "classes"]
The first one is trivial:
isit.first[''name''] => ''device-1''
The second key is a Hash of your parameters:
isit.first[''parameters''] =>
{"app_folder"=>"deploy_project",
"app_id"=>"1",
"tar_file"=>"deploy_project.tar.gz",
"profile_id"=>"3",
"version_id"=>"2"}
And the third is an array, again because your item underneath classes
begins with a ''-'':
isit.first[''classes''] => ["install"]
So the data structure you want to construct looks like:
[{''name'' => ''device-1'',
''parameters'' =>
{''app_folder'' => ''deploy_project'',
''app_id'' => ''1'',
''tar_file'' =>
''deploy_project.tar.gz'',
''profile_id'' => ''1'',
''version_id'' => ''2''},
''classes'' =>
[''install'']
}
]
and chaining that to .to_yaml will create the YAML you want.
Converting your input to that structure is still up to you. Not
knowing anything about where you are getting the input, it''s hard to
advise.
--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
For more options, visit https://groups.google.com/groups/opt_out.