how to create custom yaml

I need to create a method that should return yaml in the following format

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:

def to_yaml

yaml = “—”

yaml += “- name: #{self.device_name or wherever you store this}”

blah blah

so on

return yaml

end

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...

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.

Many thanks for your help. It worked for me :