How to Save Settings as a Hash in a External File

How do I save settings as a hash in a external file?

The most common way to store configuration data in Ruby is to use YAML:

settings.yml

user1:
path: /
days: 5

user2:
path: /tmp/
days: 3

Then load it in your code like this:

require 'yaml'
settings = YAML::load_file "settings.yml"
puts settings.inspect

You can create the YAML file using to_yaml:

File.open("settings.yml", "w") do |file|
file.write settings.to_yaml
end

That said, you can include straight Ruby code also, using load:

load "settings.rb"

However, you can't access local variables outside the file, so you would have to change your code to use an instance variable or a global variable:

settings.rb

SETTINGS = { 
'user1' => { 'path' => '/','days' => '5' },
'user2' => { 'path' => '/tmp/','days' => '3' }
}
@settings = { 'foo' => 1, 'bar' => 2 }

Then load it thus:

load "settings.rb"
puts SETTINGS.inspect
puts @settings.inspect

How to permanently update a hash in Ruby?

Here is code you could use. It takes advantage of yaml to store the hash.

require 'yaml'

file = '/tmp/test.yml'
if File.exists?(file)
hash = YAML::load_file(file) # load yaml
else
hash = Hash.new
end

puts "Type 'add' to add an item to the hash"
choice = gets.chomp.downcase

if choice == 'add'
puts "What do you want to add?"
addition = gets.chomp
if hash[addition.to_sym].nil?
puts "What value will #{addition} have? (integer)"
add_value = gets.chomp
hash[addition.to_sym] = add_value.to_i
puts "#{addition} has been added with a value of #{add_value}."
else
puts "That item already exists! Its value is # {hash[addition.to_sym]}."
end
end

File.open(file, 'w') {|f| f.write hash.to_yaml } #store yaml

Perl Hashes: Using key/value pairs from external text file

When you read from the file, you get a string (or multiple strings, if you read line-by-line). The Perl parser only parses source code passed to the Perl interpreter, not anything you read from files or elsewhere. You can use the eval function to evaluate arbitrary strings like this as perl code and return the result of the last expression (in this case, a list of strings), but string eval is dangerous because it can run any code; if you accidentally read a file containing system 'rm -rf ~/*' you have a problem.

A better option is to store your data in a known serialization format. A common format used for such things is JSON, because it maps neatly to Perl data structures, but you can also just store your strings as lines (without Perl syntax like quoting) for a simple case like this. There are any number of other options like YAML, or even XML, but they are harder to decode; and binary formats like Storable, Sereal, and CBOR, but they are not human-readable so can only be interacted with by your code.

use strict;
use warnings;
use JSON::MaybeXS;
# if you store it as JSON: {"SGBK":"PRINT","SGDVD":"VIDEO"}
my %format_key = %{decode_json($output)};
# or from an even-sized array: ["SGBK","PRINT","SGDVD","VIDEO"]
my %format_key = @{decode_json($output)};

# if you store it as one value per line
my %format_key = split /\n/, $output;

How to set save the variable in a PHP file?

The config file needs to be in PHP? You can hack together a quick configuration array into an external file using var_export

The config file config.php

$config = array(
'name' => 'My Name',
'email' => 'some@one',
);

Loading/saving the config file:

include 'config.php';  // Bring config into the current namespace
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Update on POST
$config['name'] = $_POST['name'];
$config['email'] = $_POST['email'];
file_put_contents('config.php', sprintf("<?php\n%s\n", var_export($config, true)));
}
print_r($config);

As with any user input you should be sure to filter the input against a whitelist to weed out dangerous data. For instance, preg_replace('/\W/', '', $_POST['name']) will remove unsafe data (non-word characters) from the user-supplied values.

How to write and read a file with a HashMap?

HashMap implements Serializable so you can use normal serialization to write hashmap to file

Here is the link for Java - Serialization example

Save file MD5 hash to file metadata

I determined that this approach was indeed a dead end, due to the fact that I can't ensure that files will always be hosted on an NTFS formatted drive. Especially in smaller firms a NAS is a common location, and with Work from Home becoming a thing, so is a local external FAT32 formatted drive.
The solution is to prevalidate the XML, get a hash of the XML as a string, and then add that hash to the root node at an attribute. The XML load code can then pass loaded XML to a method that compares the value of that hash to a rehash of the same XML as a string, with the attribute removed. Net result, a universally applicable way to verify if the XML is changed since prevalidation. Which was really the goal.

Save external files by php

Maybe this will help you solve the question

function remote_merge($sourceurl,$targetftp){
$ch = curl_init ($sourceurl);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec($ch);
curl_close ($ch);
$tempfile = "/path/to/temp/".basename(parse_url($sourceurl, PHP_URL_PATH));
if(file_exists($tempfile)){
unlink($tempfile);
}
$fp = fopen($tempfile,'x');
fwrite($fp, $rawdata);
fclose($fp);

$ch = curl_init();
$fp = fopen($tempfile, "rb");

curl_setopt($ch, CURLOPT_URL, $targetftp);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($tempfile));
$error = curl_exec($ch);
// check $error here to see if it did fine or not!
curl_close($ch);
}

Use this to tryout the remote_merge function

$sourceurls = array(
"http://site.com/1.pdf",
"http://site.com/234234234.png",
"http://site.com/archive.zip",
"http://site.com/1f41f.anyformat",
"http://site.com/file.txt"
);

foreach($sourceurl as $sourceurls){
$filename = basename(parse_url($sourceurl, PHP_URL_PATH);
$targetftp = "ftp://${ftpuser}:${ftppasswd}@${ftpserver}${ftppath}/$filename";
remote_merge($sourceurl,$targetftp)
}

How can I write out or read in a Perl hash of arrays?

Check out Data::Dumper.

For instance, this microscopic script:

#!/bin/perl -w
use strict;
use Data::Dumper;

my(%hash);

$hash{key1} = [ 1, "b", "c" ];
$hash{key2} = [ 4.56, "g", "2008-12-16 19:10 -08:00" ];

print Dumper(\%hash);

produces this output, which could clearly be edited:

$VAR1 = {
'key2' => [
'4.56',
'g',
'2008-12-16 19:10 -08:00'
],
'key1' => [
1,
'b',
'c'
]
};

It can also be evaluated to read the data back into the program.


Extending the example to show reading in as well as printing out...Note that the code is in two main blocks, and the only variable common between the blocks is the name of the file.

#!/bin/perl -w
use strict;
use Data::Dumper;
use FileHandle;

my $file = "data.out";

{
my(%hash);

$hash{key1} = [ 1, "b", "c" ];
$hash{key2} = [ 4.56, "g", "2008-12-16 19:10 -08:00" ];

my $str = Data::Dumper->Dump([ \%hash ], [ '$hashref' ]);
print "Output: $str";

my($out) = new FileHandle ">$file";
print $out $str;
close $out;
}

{
my($in) = new FileHandle "<$file";
local($/) = "";
my($str) = <$in>;
close $in;

print "Input: $str";

my($hashref);
eval $str;
my(%hash) = %$hashref;

foreach my $key (sort keys %hash)
{
print "$key: @{$hash{$key}}\n";
}
}

The output from that script is:

Output: $hashref = {
'key2' => [
'4.56',
'g',
'2008-12-16 19:10 -08:00'
],
'key1' => [
1,
'b',
'c'
]
};
Input: $hashref = {
'key2' => [
'4.56',
'g',
'2008-12-16 19:10 -08:00'
],
'key1' => [
1,
'b',
'c'
]
};
key1: 1 b c
key2: 4.56 g 2008-12-16 19:10 -08:00



Related Topics



Leave a reply



Submit