Rails replace one hash by another if keys exists - ruby-on-rails

I don't know what's going on but I've got two hashes:
first_hash
{
'Ids' => ['string_first_hash'],
'Description' =>
{
'Url' => 'some_path',
'EventCallback' => {
'Url' => 'some_path',
'WhiteList' => ['string'],
},
'Steps' => [{
'OrderIndex' => 1,
'Recipients' => [
{
'Email' => 'email#first.hash',
'FirstName' => 'first_hash_name',
'LastName' => 'first_hash_last_name',
'LanguageCode' => 'en',
},
],
}],
},
}
And the second one:
template_hash
{
'Ids' => ['template_stirng'],
'Description' => {
'Name' => 'Template_name',
'Subject' => 'template_subject',
'Finish' => false,
'Steps' => [{
'OrderIndex' => 1,
'Recipients' => [
{
'Email' => 'Placeholder =>',
'FirstName' => '',
'LastName' => '',
'LanguageCode' => '',
'DisableEmail' => false,
'IdentificationMethods' => [],
},
],
'RecipientType' => 'Signer',
}],
},
}
Now I want to add first_hash to the template_hash and override only those key/value which exist in both and leave the rest from second_hash unchanged (should be added in the result). I thought all I want to do is:
test = first_hash.merge(template_hash)
But the result is surprising - nothing change, it prints second hash unchanged:
> test
{"SspFileIds"=>["7fcf6021-386d-4f31-a871-a89afb8fb36e"],
"SendEnvelopeDescription"=>
{"Name"=>"1 Recipient",
"EmailSubject"=>"Please sign the enclosed envelope",
"EmailBody"=>"Dear #RecipientFirstName# #RecipientLastName#\n\n#PersonalMessage#\n\nPlease sign the envelope #EnvelopeName#\n\nEnvelope will expire at #ExpirationDate#",
"DisplayedEmailSender"=>"",
"EnableReminders"=>true,
"FirstReminderDayAmount"=>5,
"RecurrentReminderDayAmount"=>3,
"BeforeExpirationDayAmount"=>3,
"DaysUntilExpire"=>28,
"StatusUpdateCallbackUrl"=>"",
"LockFormFieldsAtEnvelopeFinish"=>false,
"Steps"=>
[{"OrderIndex"=>1,
"Recipients"=>
[{"Email"=>"Placeholder:",
"FirstName"=>"",
"LastName"=>"",
"LanguageCode"=>"",
"DisableEmail"=>false,
"AddAndroidAppLink"=>false,
"AddIosAppLink"=>false,
"AddWindowsAppLink"=>false,
"AllowDelegation"=>true,
"AllowAccessFinishedWorkstep"=>false,
"SkipExternalDataValidation"=>false,
"AuthenticationMethods"=>[],
"IdentificationMethods"=>[]}],
"RecipientType"=>"Signer"}]}}
What's going on, am I misunderstand something? I'm using Rails 7 and Ruby 3.
[EDIT]
expected_result
{
'Ids' => ['string_first_hash'],
'Description' => {
'Name' => 'Template_name',
'Subject' => 'template_data_string',
'Finish' => false,
'Steps' => [{
'OrderIndex' => 1,
'Recipients' => [{
'Email' => 'email#first.hash',
'FirstName' => 'first_hash_name',
'LastName' => 'first_hash_last_name',
'LanguageCode' => 'en',
}],
'RecipientType' => 'Signer',
}],
'Url' => 'some_path',
'EventCallback' => {
'Url' => 'some_path',
'WhiteList' => ['string'],
},
},
}

Have you tried using deep_merge? https://apidock.com/rails/Hash/deep_merge
What you want is
test = first_hash.deep_merge(second_hash)

Related

How do I display "Loading..." message in Highcharts using only the yii2 extension?

I'm rendering Highcharts on my page with Pjax.
My view code:
<?php Pjax::begin() ?>
<?php ActiveForm::begin() ?>
//some code there...
<?= Html::submitButton( 'Calculate', [
'class' => 'btn btn-primary',
'id' => 'calculate-button',
]);
ActiveForm::end();
?>
<?php
if ($data) {
echo $this->render('HolidayChart', ['data' => $data]);
}
?>
Highcharts widget:
echo Highcharts::widget([
'scripts' => [
'highcharts-more'
],
'htmlOptions' => ['id' => 'holidayChart-id'],
'options' => [
'chart' => [
'type' => 'columnrange',
'inverted' => true,
'zoomType' => 'y',
],
'title' => ['text' => 'Chart'],
'inverted' => true,
'yAxis' => [
'title' => [],
'type' => 'datetime',
'dateTimeLabelFormats' =>
[
'day' => '%d.%m.%Y',
],
'min' => 1514764800000,
'max' => 1546300800000
],
'xAxis' => [
'title' => ['text' => Names'],
'categories' => $data['users'],
],
'series' => [
[
'name' => 'Name',
'data' => $data['data'],
]
]
]
]);
Controller code:
$calculateForm = new CalculateHolidayForm();
$data = '';
if ($calculateForm->load(Yii::$app->request->post()) && $calculateForm->validate()) {
$data = UserHoliday::calculateHoliday(UserSubgroup::findOne($calculateForm->subgroup), $calculateForm->dateRange);
}
return $this->render('about', ['calculateForm' => $calculateForm, 'data' => $data]);
I have two questions:
1. How can I display "Loading..." message before the rendering chart?
2. How can I display "Loading..." message before update data on the chart using only the extension? (About like this https://jsfiddle.net/hLj1advd/ )
Thanks a lot!

ARRAY ACCESS AND INSERTION RECORD DATABASE

I would need to access the array to retrieve the information and insert it into the database (Code, Customer, Phone1, Phone2). Someone can help me?
{
:recordset => {
:row => [
[0] {
:property => [
[0] {
:name => "Code",
:value => "C0001"
},
[1] {
:name => "Customer",
:value => "ROSSI MARIO"
},
[2] {
:name => "Phone1",
:value => "1234567890"
}
]
},
[1] {
:property => [
[0] {
:name => "Code",
:value => "C0002"
},
[1] {
:name => "Customer",
:value => "VERDE VINCENT"
},
[2] {
:name => "Phone1",
:value => "9876543210"
},
[3] {
:name => "Phone2",
:value => "2468101214"
}
]
}
]
},
:#xmlns => "http://localhost/test"
}
p.s. The Phone2 value during the SOAP call is only displayed if it is present in an archive
Thank you
Your data doesn't look like a valid ruby structure. Once you are able to convert it to be more ruby-like, you can make use of each_with_object to generate a well formatted set of attributes and their values from your data:
data
=> {:recordset=>{
:row=>[{
:property=>[
{:name=>"Code", :value=>"C0001"},
{:name=>"Customer", :value=>"ROSSI MARIO"},
{:name=>"Phone1", :value=>"1234567890"}
]
}, {
:property=>[
{:name=>"Code", :value=>"C0002"},
{:name=>"Customer", :value=>"VERDE VINCENT"},
{:name=>"Phone1", :value=>"9876543210"},
{:name=>"Phone2", :value=>"2468101214"}
]
}]
},
:#xmlns=>"http://localhost/test"}
data.keys
=> [:recordset, :#xmlns]
data[:recordset][:row].count
=> 2 # There are 2 set of attribute-value pairs
result = data[:recordset][:row].each_with_object([]) do |hash, out|
out << hash[:property].each_with_object({}) do |h, o|
o[h[:name]] = h[:value]
end
end
=> [{"Code"=>"C0001", "Customer"=>"ROSSI MARIO", "Phone1"=>"1234567890"},
{"Code"=>"C0002", "Customer"=>"VERDE VINCENT", "Phone1"=>"9876543210", "Phone2"=>"2468101214"}]
Now, you can iterate over result and create respective records in database.

Why am I getting singleton cant be dumped err?

When I try to add a variable value into session, I am getting singleton cant be dumped err.
Here is the value in the varibale
[
[0] {
:id => "574ecb43a7a5bb44c000443b",
:_id => "574ecb43a7a5bb44c000443b",
:active => true,
:capabilities => {
:network_connections => [
[0] {
:type => "ethernet-wan",
:name => "wan"
},
[1] {
:type => "ethernet-lan",
:name => "lan"
},
[2] {
:type => "wifi",
:name => "wlan"
},
[3] {
:type => "cellular",
:name => "wwan"
}
]
},
:commander_ids => [],
:created_at => "2016-05-11T15:46:12+00:00",
:deleted_at => nil,
:firmware_upgradable => true,
:ingestor_ids => [],
:last_known_translator_port => nil,
:long_description => "this is a liong desc",
:manufacturer => "test_sushant",
:model => "sushant_test",
:name => "zxc",
:parent_gateway_data_source_type_id => nil,
:rule_ids => [],
:software => "qwe",
:translator => "edge",
:type => "asd",
:updated_at => "2016-05-11T15:46:12+00:00",
:user_id => "572adee5a7a5bb320b000852"
},
The variable is an array of objects. I do not know why this is causing an err.

Rails jqgrid column background color dynamic

I'm using jqgrid with ruby on rails and as per my requiremnet in jqgrid listing page i need background color as dynamic for a particular column values.
Here is my code for helper,
include JqgridsHelper
def colors_jqgrid
options = {:on_document_ready => true, :html_tags => false}
grid = [{
:sortable => true,
:url => '/colors',
:datatype => 'json',
:mtype => 'GET',
:colNames => ['colors_id','ID','External ID','name','Color Swatch','Actions'],
:colModel => [
{ :name => 'colors_id', :index => 'colors_id',:hidden => true},
{ :name => 'ID', :index => 'ID', :width => 180 ,:searchoptions => {
:sopt => ['eq','ne','bw','ew','cn'],
}},
{ :name => 'External ID', :index => 'color_id',:search=>false, :width => 180 ,:searchoptions => {
:sopt => ['eq','ne','bw','ew','cn'],
} },
{ :name => 'name', :index => 'name', :width => 180 ,:searchoptions => {
:sopt => ['eq','in'],
} },
{ :name => 'color_id', :index => 'Color Swatch',:search=>false, :width => 180},
{name:'Actions',index:'action',align:'center',sortable:false,formatter: 'function(cellvalue, options, rowObject) {
edit = "<span class=\"ui-icon ui-icon-pencil\" title=\"Edit\" style= \"cursor:pointer;float:left;\" onclick=\"window.location.href = '"'colors/edit?id="'"+options.rowId+"'"'"';\"></span>";
edit += "<span class=\"ui-icon ui-icon-trash\" title=\"Delete\" style= \"cursor:pointer;\" onclick=\"jQuery.fn.fmatter.rowactions.call(this,'"'del'"');\"></span>";
return edit;
}'.to_json_var },
],
:editurl => '/colors/grid_update',
:pager => '#colors_pager',
:rowNum => 10,
:rowList => [10, 20, 30],
:caption => 'Colors',
:autowidth => true,
:navigator=>true,
:excel=>true,
:viewrecords=>true,
:ondblClickRow => "function(rowId, iRow, iCol, e) { window.location = 'colors/edit?id='+ rowId; }".to_json_var
}]
pager = [:navGrid, "#colors_pager", { :del => false,:search=>true,:edit => false,:add => false},
{:closeAfterEdit => true, :closeOnEscape => true}, {}, {}, {:multipleSearch => true}, {}]
options = [:navButtonAdd, "#colors_pager", {caption: "Columns", title: "Reorder Columns", onClickButton: "function() { jQuery('#colors_list').jqGrid('columnChooser'); }".to_json_var }]
jqgrid_api 'colors_list', grid, pager, options
end
Add following line anywhere in grid variable section.
:afterInsertRow => "function(rowId, data) { $(\"#colors_list\").setCell(rowId, 'color_id', '', {'background-color':'#'+data.color_id }); }".to_json_var
it requires 2 parameters. First is rowId which is identifier of row. second is data which is content of that row with all fields. so i used data.color_id for fetching color code which u want to use to set background color.

Active resource param serialization issue

I'm trying to pass the following ruby hash into an active resource(3.0.9) find(:from) call.
my_hash = {
:p => {:s => 100, :e => 2},
:k => "blah",
:f => [
{
:fl => :bt,
:tp => :trm,
:vl => "A::B"
},
{
:fl => :jcni,
:tp => :trm,
:vl => [133, 134]
},
{
:mnfl => :bmns,
:mxfl => :bmxs,
:tp => :rfstv,
:vl => 1e5
},
{
:fl => :bpo,
:tp => :rftv,
:op => :eta,
:vl => 1.months.ago.strftime("%Y-%m-%d")
}
]
}
Resource.find_by_x_and_y(:all, :from => :blah, params: my_hash)
On the server side action, when I print the params hash, its all messed up. ( last 3 hashes in the array mapped to :f )
{
"f" => [
{
"fl" => "bt",
"tp" => "trm",
"vl" => "A::B"
},
{
"fl" => "jcni",
"tp" => "trm",
"vl" => [
"133",
"134"
],
"mnfl" => "bmns",
"mxfl" => "bmxs"
},
{
"tp" => "rfstv",
"vl" => "100000.0",
"fl" => "bpo",
"op" => "eta"
},
{
"tp" => "rftv",
"vl" => "2013-01-25"
}
],
"k" => "blah",
"p" => {
"e" => "2",
"s" => "100"
},
"action" => "blah",
"controller" => "x/Y",
"format" => "json"
}
my_hash.to_query gives me
f[][fl]=bt&f[][tp]=trm&f[][vl]=A%3A%3AB&f[][fl]=jcni&f[][tp]=trm&f[][vl][]=133&f[][vl][]=134&f[][mnfl]=bmns&f[][mxfl]=bmxs&f[][tp]=rfstv&f[][vl]=100000.0&f[][fl]=bpo&f[][op]=eta&f[][tp]=rftv&f[][vl]=2013-01-25&k=blah&p[e]=2&p[s]=100
which doesn't have indices, hence the mixup.
Is there a name for this type of serialization using "[]" ? Is this guaranteed to serialize/deserialize arbitrarily nested hashes/arrays/primitives faithfully ? How do I make active resource behave sanely ?

Resources