How to convert the data to the yml file - ruby

I have a Ruby file, "one.rb":
require 'yaml'
e = { "names"=>{"first_name" => "shaik", "last_name" => "farooq"} }
puts e.to_yaml
When I run this it gets executed successfully in the console and outputs:
---
names:
first_name: shaik
last_name: farooq
I want to store the executed data in a file with a "yml" extension. How can I do this from the above file (test.rb)?

It's really simple:
require 'yaml'
e = { "names"=>{"first_name" => "shaik", "last_name" => "farooq"} }
File.write('test.yaml', e.to_yaml)
After running that, a file called "test.yaml" will exist in the current directory that contains:
---
names:
first_name: shaik
last_name: farooq
You can reload that data easily also:
new_e = YAML.load_file('test.yaml')
# => {"names"=>{"first_name"=>"shaik", "last_name"=>"farooq"}}

You can write the yaml to file with:
require 'yaml'
e = { "names"=>{"first_name" => "shaik", "last_name" => "farooq"} }
File.open('your_file_name.yml', 'w') { |f| f.write(e.to_yaml) }

Related

How to inspect CSV file columns inside RSpec test?

I really don't know how to inspect CSV file I created in my ROR App.
require "rails_helper"
require "shared_contexts/vcr/s3"
require "csv"
RSpec.describe ReportRuns::RunService do
describe "CSV columns" do
include_context "vcr s3 put csv"
let(:report_run) { create :report_run, report_template: report_template, created_by: user.id, mime_type: "csv" }
#let(:report_template) { create :report_template, template_structure: { module: "trial_members", filters: { trial_members: [trial_members.id] } } }
let(:report_template) { create :report_template, trial: trial }
let(:trial) { create :trial }
let(:user) { create :user }
let(:user_role) { create :user_role }
subject { described_class.new(report_run) }
before do
end
it do
get :index, format: :csv
p "response jee: #{response.body}"
p response.headers
p "report run: #{report_run.inspect}"
p "templejt: #{report_template.inspect}"
p "mime type: #{report_run[:mime_type]}"
#p "trila je: #{trial.inspect}"
p "users are: #{user.inspect}"
p "user roles su: #{user_role.inspect}"
is_expected.to be_truthy
expect(5).to match(5)
end
end
end
Use the CSV library to parse the body of the response. Then work with the CSV object.
csv = CSV.new(response.body)
You can also check the Content-type headers are correct, text/csv.

Proper cmd line for ExifTool for pdf meta tagging

I'm having issues getting exiftools to write custom meta tags for my pdf files. In MacOS terminal with exiftools installed. Here's a sample command.
exiftool -overwrite_original -config
new.config -XMP::pdfx:document_id=”7A 2017 091 d” -XMP::pdfx:description=”Booklet on stuff and more stuff” pdf_files/7A_2017_091_d.pdf
Here's the config lines:
#user-defined pdfs
%Image::ExifTool::UserDefined = (
'Image::ExifTool::XMP::pdfx' => {
document_id => { },
description => { },
},
);
1; #end
All I get back is:
Warning: Tag 'XMP::pdfx:Document_id' is not defined
Warning: Tag 'XMP::pdfx:Description' is not defined
Nothing to do.
What am I doing wrong?
This is the config file that worked for me:
#user-defined pdfs
%Image::ExifTool::UserDefined = (
'Image::ExifTool::XMP::pdfx' => {
document_id => { Writable => 'string', },
description => { Writable => 'string',},
},
);
1; #end
And the command line with results (you don't need the config file to read XMP tags, just write)
C:\>exiftool -config temp.txt -xmp-pdfx:document_id="test" -xmp-pdfx:description="Description Test" y:/!temp/test.pdf
1 image files updated
C:\>exiftool -xmp-pdfx:document_id -xmp-pdfx:description y:/!temp/test.pdf
Document id : test
Description : Description Test

translation from XML to rest-client for POST request

The is the XML request via POST I have to make in order to receive a response:
<BackgroundCheck userId="username" password="password">
<BackgroundSearchPackage action="submit" type="demo product">
<ReferenceId>some_id_value</ReferenceId>
<PersonalData>
<PersonName>
<GivenName>John</GivenName>
<MiddleName>Q</MiddleName>
<FamilyName>Test</FamilyName>
</PersonName>
<Aliases>
<PersonName>
<GivenName>Jack</GivenName>
<MiddleName>Quigley</MiddleName>
<FamilyName>Example</FamilyName>
</PersonName>
</Aliases>
<DemographicDetail>
<GovernmentId issuingAuthority="SSN">123456789</GovernmentId>
<DateOfBirth>1973-12-25</DateOfBirth>
</DemographicDetail>
<PostalAddress>
<PostalCode>83201</PostalCode>
<Region>UT</Region>
<Municipality>Salt Lake City</Municipality>
<DeliveryAddress>
<AddressLine>1234</AddressLine>
<StreetName>Main Street</StreetName>
</DeliveryAddress>
</PostalAddress>
<EmailAddress>john#test.com</EmailAddress>
<Telephone>801-789-4229</Telephone>
</PersonalData>
</BackgroundCheck>
</BackgroundSearchPackage>
Using the examples on the rest-client github page I came up with the following translation using rest-client:
response = RestClient.post( 'url',
{
:BackgroundCheck => {
:userID => 'username',
:password => 'password',
},
:BackgroundSearchPackage => {
:action => 'submit',
:type => 'demo'
},
:ReferenceID => 'some_id_value',
:PersonalData => {
:PersonalName => {
:GivenName => 'John',
:MiddleName => 'Q',
:FamilyName => 'Test'
},
:Aliases => {
:GivenName => 'Jack',
:MiddleName => 'Quigly',
:FamilyName => 'Example'
}
},
:DemographicDetail => {
:GovernmentId => {
:issuingAuthority => "SSN"
}, ## where do I enter the SSN?
:DateOfBirth => '1972-12-25'
},
:PostalAddress => {
:PostalCode => '83201',
:Region => 'UT',
:Municipality => 'Salt Lake City',
:DeliveryAddress => {
:AddressLine => '1234',
:StreetName => 'Main Street'
}
},
:EmailAddress => 'john#test.com',
:Telephone => '801-789-4229'
})
Its my first time with XML and the rest-client gem.
My question is did I translate the XML correctly in the POST request?
More specifically how do I handle the GovernmentID and referencing the SSN entry?
First of all, the XML you've provided isn't valid! Your root element starts with BackgroundCheck and ends with BackgroundSearchPackage:
<BackgroundCheck userId="username" password="password">
<BackgroundSearchPackage action="submit" type="demo product">
</BackgroundCheck>
</BackgroundSearchPackage>
In addition, your translation / transformation from XML to Ruby hash is incorrect. If BackgroundCheck is your root element and BackgroundSearchPackage is a child of it, your Ruby hash should look like this (rest-client accepts the string and the symbol notation):
my_xml_hash = {
"BackgroundCheck" => {
"userId"=>"username",
"password"=>"password",
"BackgroundSearchPackage" => {
"action"=>"submit",
"type"=>"demo product",
...
"PersonalData" => { ... },
...
}
}
}
You can access values in a Ruby hash like this:
# string syntax
my_xml_hash['BackgroundCheck']['BackgroundSearchPackage']['PersonalData']['DemographicDetail']['GovernmentId']
=> "123456789"
# symbol syntax
other_xml_hash[:BackgroundCheck][:BackgroundSearchPackage][:PersonalData][:DemographicDetail]['GovernmentId']
=> "123456789"
If I understood you correctly, you want to send XML via a POST request. But if you use the hash syntax, you will not achieve the result, what you probably want, because rest-client will post your data as parameters and not as XML data!
If you need to adjust only GovernmentID and issuingAuthority, I would do it as follows.
require 'rest_client'
# the customized 'GovernmentID'
government_id = '123'
# the customized 'issuingAuthority'
issuing_authority = 'FOO'
xml_template =<<END_OF_XML
<BackgroundCheck userId="username" password="password">
<BackgroundSearchPackage action="submit" type="demo product">
<ReferenceId>some_id_value</ReferenceId>
<PersonalData>
<PersonName>
<GivenName>John</GivenName>
<MiddleName>Q</MiddleName>
<FamilyName>Test</FamilyName>
</PersonName>
<Aliases>
<PersonName>
<GivenName>Jack</GivenName>
<MiddleName>Quigley</MiddleName>
<FamilyName>Example</FamilyName>
</PersonName>
</Aliases>
<DemographicDetail>
<GovernmentId issuingAuthority="#{issuing_authority}">#{government_id}</GovernmentId>
<DateOfBirth>1973-12-25</DateOfBirth>
</DemographicDetail>
<PostalAddress>
<PostalCode>83201</PostalCode>
<Region>UT</Region>
<Municipality>Salt Lake City</Municipality>
<DeliveryAddress>
<AddressLine>1234</AddressLine>
<StreetName>Main Street</StreetName>
</DeliveryAddress>
</PostalAddress>
<EmailAddress>john#test.com</EmailAddress>
<Telephone>801-789-4229</Telephone>
</PersonalData>
</BackgroundSearchPackage>
</BackgroundCheck>
END_OF_XML
# Go to http://requestb.in/ , click on "Create a RequestBin", copy the "Bin URL" and use it for your tests ;-)
response = RestClient.post('http://your.target.tld/your/webservice', xml_template, { content_type: :xml })
puts "Response: #{response.inspect}"
REXML example:
require 'rest_client'
require 'rexml/document'
xml_string =<<END_OF_XML
<BackgroundCheck userId="username" password="password">
<BackgroundSearchPackage action="submit" type="demo product">
<ReferenceId>some_id_value</ReferenceId>
<PersonalData>
<PersonName>
<GivenName>John</GivenName>
<MiddleName>Q</MiddleName>
<FamilyName>Test</FamilyName>
</PersonName>
<Aliases>
<PersonName>
<GivenName>Jack</GivenName>
<MiddleName>Quigley</MiddleName>
<FamilyName>Example</FamilyName>
</PersonName>
</Aliases>
<DemographicDetail>
<GovernmentId issuingAuthority="SSN">123456789</GovernmentId>
<DateOfBirth>1973-12-25</DateOfBirth>
</DemographicDetail>
<PostalAddress>
<PostalCode>83201</PostalCode>
<Region>UT</Region>
<Municipality>Salt Lake City</Municipality>
<DeliveryAddress>
<AddressLine>1234</AddressLine>
<StreetName>Main Street</StreetName>
</DeliveryAddress>
</PostalAddress>
<EmailAddress>john#test.com</EmailAddress>
<Telephone>801-789-4229</Telephone>
</PersonalData>
</BackgroundSearchPackage>
</BackgroundCheck>
END_OF_XML
# Build XML document from string
doc = REXML::Document.new(xml_string)
government_element = REXML::XPath.first(doc, "//GovernmentId")
# Read values:
puts government_element.text
puts government_element.attributes['issuingAuthority']
# OR directly via XPath
puts REXML::XPath.first(doc, "//GovernmentId").text
puts REXML::XPath.first(doc, "//GovernmentId/#issuingAuthority").value
# Write values:
government_element.text = 'my new text value'
government_element.attributes['issuingAuthority'] = 'my new attribute value'
# Go to http://requestb.in/ , click on "Create a RequestBin", copy the "Bin URL" and use it for your tests ;-)
response = RestClient.post('http://your.target.tld/your/webservice', doc.to_s, { content_type: :xml })
puts "Response: #{response.inspect}"
If you need to write complex XML trees, I recommend you to take a look at the following gems:
Nokogiri
LibXml Ruby
XmlSimple
REXML (Ruby built in)
Or use a templating engine like ERB, to simplify it.

Create a domain-specific ".site.com" cookie with Ruby's selenium-webdriver [duplicate]

This question already has answers here:
How to set a cookie for another domain
(11 answers)
Closed 9 years ago.
I am trying to create a cookie with domain, not host, or entire website.
I have this code now
driver.manage.add_cookie(:name => 'test', :value => 'testvalue', :path => '/', :secure => false)
I want something like this
name=test
value=testvalue
domain=.site.com
path=/
I am getting such result in a firefox cookie dialog
while I want something like this
You can see Host: is empty in my case and in another case it is replaced with Domain: and this is what I want to achieve, to set a cookie domain to .mydomain.com
I want to achieve this for JavaScript to be able to read domain-specific cookies as it can not read what's outside of current domain scope.
Try following:
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
driver.get('http://eu.httpbin.org') # <-- required.
driver.manage.add_cookie(name: 'test', value: 'testvalue', path: '/', domain: '.httpbin.org')
driver.get('http://eu.httpbin.org/cookies') # eu.httpbin.org
puts driver.page_source
# => ...
# {
# "cookies": {
# "test": "testvalue"
# }
# }
# ...
driver.get('http://httpbin.org/cookies') # httpbin.org
puts driver.page_source
# => ...
# {
# "cookies": {
# "test": "testvalue"
# }
# }
# ...
NOTE: You have to go to the same domain page (html page) before adding cookie.
You can do as below using JavaScript :
require "selenium-webdriver"
require "awesome_print"
driver = Selenium::WebDriver.for :firefox
driver.navigate.to "http://example.com"
COOKIE_DOMAIN = <<-eotl
var cookieName = arguments[0];
var cookieValue = arguments[1];
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + encodeURIComponent(cookieValue)
+ ";expires=" + myDate
+ ";domain=.example.com;path=/";
eotl
driver.execute_script(COOKIE_DOMAIN,'test','testvalue')
ap driver.manage.cookie_named('test')
output
{
:name => "test",
:value => "testvalue",
:path => "/",
:domain => ".example.com",
:expires => #<DateTime: 2014-09-09T07:43:12+00:00 ((2456910j,27792s,999999924n),+0s,2299161j)>,
:secure => false
}

RCov doesn't work

I am currently developing a Ruby gem and want to create metrics.
I am using 'metric_fu', but RCov seems to leave my specs.
Here is my metric_fu configuration:
MetricFu::Configuration.run do |config|
config.metrics = [:churn, :saikuro, :flog, :flay, :reek, :roodi, :rcov]
config.graphs = [:flog, :flay, :reek, :roodi, :rcov]
config.flay = { :dirs_to_flay => ['lib'] }
config.flog = { :dirs_to_flog => ['lib'] }
config.reek = { :dirs_to_reek => ['lib'] }
config.roodi = { :dirs_to_roodi => ['lib'] }
config.saikuro = { :output_directory => 'scratch_directory/saikuro',
:input_directory => ['lib'],
:cyclo => "",
:filter_cyclo => "0",
:warn_cyclo => "5",
:error_cyclo => "7",
:formater => "text"} #this needs to be set to "text"
config.churn = { :start_date => "1 year ago", :minimum_churn_count => 10}
config.rcov = { :test_files => ["spec/**/*_spec.rb"],
:rcov_opts => ["--sort coverage",
"--no-html",
"--text-coverage",
"--no-color",
"--profile",
"--spec-only",
"--exclude /gems/,/Library/,spec"]}
end
Do you have some tips?
Best regards
Well this is going to be hard to diagnose without a stack trace but I would suggest changing your config to this:
MetricFu::Configuration.run do |config|
config.metrics = [:rcov]
config.graphs = [:rcov]
config.rcov = { :test_files => ["spec/**/*_spec.rb"],
:rcov_opts => ["--sort coverage",
"--no-html",
"--text-coverage",
"--no-color",
"--profile",
"--spec-only",
"--exclude /gems/,/Library/,spec"]}
end
So you can isolate the problem. Then run 'rake metrics:all --trace' and if you can't figure it out from there, post the results either here or the metric_fu google group: http://groups.google.com/group/metric_fu
You can also try running rcov straight from the command line (which is essentially what metric_fu does).
Hope that helps.

Resources