class Object

Public Instance Methods

write_to_json(file, options = {}) click to toggle source

Writes the Object serialized as JSON to the specified file, overwriting the file if it exists. Creates the file if it does not exist, including any necessary parent directories. Returns the Object, unmodified.

For information about options see {docs.ruby-lang.org/en/master/JSON.html#method-i-generate JSON.generate}. By default, this method uses {docs.ruby-lang.org/en/master/JSON.html#attribute-c-dump_default_options JSON.dump_default_options}.

@example

{ "key" => "value" }.write_to_json("file.json")  # == { "key" => "value" }
File.read("file.json")                           # == '{"key":"value"}'

@param file [String, Pathname] @param options [Hash{Symbol => Object}] @return [self]

# File lib/pleasant_path/json/object.rb, line 21
def write_to_json(file, options = {})
  options = JSON.dump_default_options.merge(options)
  file.to_pathname.write_text(self.to_json(options))
  self
end
write_to_yaml(file, options = {}) click to toggle source

Writes the Object serialized as YAML to the specified file, overwriting the file if it exists. Creates the file if it does not exist, including any necessary parent directories. Returns the Object, unmodified.

For information about options see {docs.ruby-lang.org/en/master/Psych.html#method-c-dump YAML.dump}.

@example

{ "key" => "value" }.write_to_yaml("file.yaml")  # == { "key" => "value" }
File.read("file.yaml")                           # == "---\nkey: value\n"

@param file [String, Pathname] @param options [Hash{Symbol => Object}] @return [self]

# File lib/pleasant_path/yaml/object.rb, line 21
def write_to_yaml(file, options = {})
  file.to_pathname.make_dirname.open("w") do |f|
    YAML.dump(self, f, options)
  end
  self
end