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

Can I somehow use this
settings = {
'user1' => { 'path' => '/','days' => '5' },
'user2' => { 'path' => '/tmp/','days' => '3' }
}
in a external file as settings?
How can I include this into my script?

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

you can also use Marshal
settings = {
'user1' => { 'path' => '/','days' => '5' },
'user2' => { 'path' => '/tmp/','days' => '3' }
}
data=Marshal.dump(settings)
open('output', 'wb') { |f| f.puts data }
data=File.read("output")
p Marshal.load(data)

A really simple one is to use eval.
config.txt
{
'user1' => { 'path' => '/','days' => '5' },
'user2' => { 'path' => '/tmp/','days' => '3' }
}
program.rb
configuration = eval(File.read("./config.txt"))
puts configuration['user1']

Related

Savon: Wrong Element Name Prefix. How can I change it?

So here is the code that I have:
resp = client.call(
:producer_query,
message: {
'cmn:Carrier' => '',
'cmn:ProducerCriteria' => { 'cmn:EntityType' => 'Individual',
'cmn:CustomerId' => 5555,
:attributes! => {'CustomerId' => {'type' => 'AGENTCD'}}},
'cmn:SectionConfiguration' => { 'cmn:SectionType' => 'Associations', :attributes! => {'cmn:SectionType' => {'activeOnly' => 'false'}}},
:attributes! => { 'cmn:Carrier' => { "id" => 55555 }}
}
) do
wsse_auth ENV['ID'], ENV['PASSWORD'], :digest
end
And it produces something that looks like:
<soapenv:Body>
<cmn:ProducerQuery>
<cmn:Carrier id="5555"/>
<cmn:ProducerCriteria>
<cmn:EntityType>Individual</cmn:EntityType>
<cmn:CustomerId>55555</cmn:CustomerId>
</cmn:ProducerCriteria>
<cmn:SectionConfiguration>
<cmn:SectionType activeOnly="false">Associations</cmn:SectionType>
</cmn:SectionConfiguration>
</cmn:ProducerQuery>
</soapenv:Body>
I've added in the 'cmn' to everything, but the ProducerQuery to make it match what I think it should be. However, I think it really should read 'tran' instead. I can control the 'cmn' for everything but the part that reads <cmn:ProducerQuery>. How can I make it read <cmn:ProducerQuery>?

Putting Variable with in single quotes?

Hi all I am making a request to the Campaign Monitor API and the data has to be held with in single quotes as a string but in JSON format. As it has to be single quotes I am unable to put in any variable values. Below is the code.
response = HTTParty.post(url,
:basic_auth => auth, :body => '{
"EmailAddress":"js#mike.com",
"Name":"#{#fname}",
"CustomFields":[
{
"Key":"firstName",
"Value":"#{#fname}"
},
{
"Key":"country",
"Value":"#{#country}"
}
],
"Resubscribe":true,
"RestartSubscriptionBasedAutoresponders":true
}')
I have tried a few different methods such as breaking the string up and piecing it back together with the variable with in double quotes but that has failed as well for the request to be successful it has to be exact.
Instead of building a JSON structure by hand, you can build a Ruby hash and convert it to JSON:
require 'json'
data = {
'EmailAddress' => 'js#mike.com',
'Name' => #fname,
'CustomFields' => [
{ 'Key' => 'firstName', 'Value' => #fname },
{ 'Key' => 'country', 'Value' => #country }
],
'Resubscribe' => true,
'RestartSubscriptionBasedAutoresponders' => true
}
response = HTTParty.post(url, basic_auth: auth, body: data.to_json)
Also note that there's a Ruby gem for the Campaign Monitor API: createsend-ruby
Using the gem, the above code translates to:
custom_fields = [
{ 'Key' => 'firstName', 'Value' => #fname },
{ 'Key' => 'country', 'Value' => #country }
]
response = CreateSend::Subscriber.add(auth, list_id, 'js#mike.com', #fname, custom_fields, true, true)
you can try with heredoc :
response = HTTParty.post(url,
:basic_auth => auth, :body => <<-BODY_CONTENT
{
"EmailAddress":"js#mike.com",
"Name":"#{#fname}",
"CustomFields":[
{
"Key":"firstName",
"Value":"#{#fname}"
},
{
"Key":"country",
"Value":"#{#country}"
}
],
"Resubscribe":true,
"RestartSubscriptionBasedAutoresponders":true
}
BODY_CONTENT
)
You can use heredoc as explained here
Double-quoting rules are also followed if you put double quotes around
the identifier. However, do not put double quotes around the
terminator.
puts <<"QUIZ"
Student: #{name}
1.\tQuestion: What is 4+5?
\tAnswer: The sum of 4 and 5 is #{4+5}
QUIZ
You can use here documents:
name = 'John'
<<EOS
This is #{name}
EOS
Alternatively you can use flexible quotes, they can handle both ' and " characters:
name = 'John'
%{
This is #{name}
}
Flexible quoting works with %() and %!! as well.

How do I add attributes to a nested XML array using Savon?

I am using savon version 2.2 to call some SOAP services. For simple services everything is working OK. However one service has a complex structure like the example below with both repeating groups and attributes on each group:
<sch:RequestControl>
<sch:requestID>6989668868</sch:requestID>
</sch:RequestControl>
<sch:InquiryParam>
<sch:crmParam name="AccountNumber">1234567</sch:crmParam>
<sch:crmParam name="History">1</sch:crmParam>
</sch:InquiryParam>
My current message looks like this:
<RequestControl>
<requestID>6989668868</requestID>
</RequestControl>
<InquiryParam>
<crmParam>1234567</crmParam>
<attributes>
<crmParam>
<name>AccountNumber</name>
</crmParam>
</attributes>
</InquiryParam>
<InquiryParam>
<crmParam>1</crmParam>
<attributes>
<crmParam>
<name>History</name>
</crmParam>
</attributes>
</InquiryParam>
The above is produced using this logic:
message = { :RequestControl =>
{ :requestID => 6989668868 },
:InquiryParam => [
{ :crmParam => { :content! => #account_number } ,
:attributes => { "crmParam" => {"name" => "AccountNumber"} } },
{ :crmParam => { :content! => #history } ,
:attributes => { "crmParam" => {"name" => "History"} } } ]
}
I've tried various combinations using :crmParam => { :content! => #account_number, :attributes => {'name'=>'AccountNumber'} } and similar based on the savon and gyoku documentation but have run onto a brick wall in getting the XML to format like the example. I know I can brute force the message by assigning it to xml but that makes it difficult to see what's going on.
Can anyone suggest a fix to have the attributes inside the crmParam tags?
I'm not sure Savon handles a Ruby array as you'd like, but the following script should give you a better idea what you can do.
require 'savon'
c = Savon.client(endpoint: "http://www.example.com",
namespace: "urn:ns.example.com",
log: true,
log_level: :debug,
pretty_print_xml: true)
r = c.call(:call,
:message => {
:InquiryParam => [
{"crmParam" => 123,
:attributes! => { "crmParam" => { "name" => "AccountNumber" }}},
{"crmParam" => 456,
:attributes! => { "crmParam" => { "name" => "history" }}}
]
}

Chef Attribute set a variable in an array hash

In a cookbook I have the following in my attributes/default.rb:
default.ark.packages = [
{
'name' => 'optipng',
'url' => 'http://squirrelyjim.cloudfront.net/heroes/optipng-0.7.5.tar.gz',
'version' => '0.7.5'
},
{
'name' => 'imagemagick',
'url' => 'http://squirrelyjim.cloudfront.net/heroes/ImageMagick-6.9.0-4.tar.gz',
'version' => '6.9.0-4'
},
{
'name' => 'jpegoptim',
'url' => 'http://squirrelyjim.cloudfront.net/heroes/jpegoptim-1.4.1.tar.gz',
'version' => '1.4.1'
}
]
I then call those values using the ark resource as follows:
node.ark.packages.each do |pkg|
ark pkg['name'] do
url pkg['url']
version pkg['version']
action :install_with_make
notifies :run, "execute[ldconfig]", :immediately
end
end
This works great but I would like to somehow get the version to automatically get called at the end of the url, instead of typing it out twice. Is there a way to get a value in a hash updated with another value from the same hash, similar to:
http://squirrelyjim.cloudfront.net/heroes/optipng-#{version}.tar.gz
Dynamically build the URL inside the loop:
node.ark.packages.each do |pkg|
url = "http://squirrelyjim.cloudfront.net/heroes/#{pkg['name']}-#{pkg['version']}.tar.gz"
ark pkg['name'] do
url url
version pkg['version']
action :install_with_make
notifies :run, "execute[ldconfig]", :immediately
end
end

Iterating over files in Puppet (3.1)

I am looking for a dry version of the following:
Ideally it could be just an array and a loop. What is the way to go in Puppet?
class hive_cdh4::configs inherits hive_cdh4 {
define hive_configs () {
file { "/etc/hive/conf.rr/hive-site.xml":
owner => root,
group => root,
mode => 664,
ensure => present,
content => template("hive_cdh4/hive-site.xml.erb")
}
file { "/etc/hive/conf.rr/hive-exec-log4j.properties":
owner => root,
group => root,
mode => 664,
ensure => present,
content => template("hive_cdh4/hive-exec-log4j.properties.erb")
}
file { "/etc/hive/conf.rr/hive-log4j.properties":
owner => root,
group => root,
mode => 664,
ensure => present,
content => template("hive_cdh4/hive-log4j.properties.erb")
}
}
}
How about something like this:
define hive_config ($file_name = $title, $format = 'properties') {
file { "/etc/hive/conf.rr/$file_name.$format":
owner => root,
group => root,
mode => '0664',
ensure => present,
content => template("hive_cdh4/$file_name.$format.erb")
}
}
hive_config {'hive-site':}
hive_config {'hive-exec-log4j':}
hive_config {'hive-log4j':
format => 'xml'
}
I tested it quickly in a Vagrant provision, and it seems to work?

Resources