How to rename fields in array in .lua - lua

I'm new in .lua. I read the documentation, but didn't find the answer to my question.
There is a space "company".
Inside it's an "information" map.
Inside this map is a "job" object and an array of "users" objects.
The "users" array consists of 2 objects. Each object has 4 fields.
I need to rename 2 fields:
Old field names -> rate and address.
New field names -> user_rate and user_address
"company": {
"information":
{
"job":
{
"job_name": "N",
"job_address": 1670392687114,
"job_salary": 1234567890123,
"contacts": 0
},
"users":
[
{
"id": 1,
"name": "Alex",
"rate": 4,
"address": "bla bla bla"
},
{
"id": 2,
"name": "Jenifer",
"rate": 5,
"address": "bla bla bla"
}
]
}
}
My solution was the following:
for _, tuple in space:pairs() do
if tuple.params ~= nil or tuple.params.offer_params ~= nil then
local information = tuple.information or {}
local users = information.users
for _, attr in pairs(users) do
local user_rate = attr.rate
local user_address = attr.address
end
local key = {}
for _, part in ipairs(key_parts) do table.insert(key, tuple[part.fieldno]) end
space:update(key, { {'=', 'information', information} })
Here I am trying to rename rate to -> user_rate and address to -> user_address and then doing an update.
Please tell me what is wrong here.
Please help me figure it out.

for _, attr in pairs(users) do
local user_rate = attr.rate
local user_address = attr.address
end
he're you're just creating two local variables and assign a value to them. After the loop they run out of scope. So you really didn't do anything useful.
If you want to "rename" table fields you need to assign the values of those fileds to the new field names and assign nil to the old field.
for _, user in pairs(users) do
user.user_rate = user.rate
user.rate = nil
user.user_address = user.address
user.address = nil
end
For more you might want to implement a function that does that to keep your code clean.

Related

Adding a new field to each array element in .lua

Please tell me, if there are any errors here and how to make the code more clean.
There is a space "company". Inside it's a string "type" and "information" map. Inside this map is a "job" object and an array of "users" objects. The "users" array consists of 2 objects. Each object has 4 fields.
I need to add a new field:
status = "UPDATED"
inside each object in the "users" array, under a certain condition
"company": {
"type" : "01",
"information":
{
"job":
{
"job_name": "N",
"job_address": 1670392687114,
"job_salary": 1234567890123,
"contacts": 0
},
"users":
[
{
"id": 1,
"name": "Alex",
"rate": 4,
"address": "bla bla bla"
},
{
"id": 2,
"name": "Jenifer",
"rate": 5,
"address": "bla bla bla"
}
]
}
}
My logic is next:
if tuple.type == "01" or tuple.type == "02" or tuple.type == "03" or tuple.type == "04" then
for _, attr in pairs(users) do
attr.status = "UPDATED"
end
end
Is it correct to add a new status="UPDATED" field to each object in the array "users" here?
Does this entry exist?
And yet, tell me please, can I somehow make the condition in if more beautiful? For example analog in Java list.contains()
Updated:
The final version after adding new field "status" should look like this (see image)
Is it correct to add a new status="UPDATED" field to each object in
the array "users" here? Does this entry exist?
If you want the table to have a status field with value "UPDATED" then attr.status = "UPDATED"is correct.
This only makes sense if you'll add more non-updated users to that table later though as you're updating the entire list. you could as well just mark the users table object as updated.
And yet, tell me please, can I somehow make the condition in if more
beautiful? For example analog in Java list.contains()
No but you could write your own function.
function table.contains(tbl, value)
for _, v in pairs(tbl) do
if (v == value) then return true end
end
return false
end
if table.contains({"01", "02", "03", "04"}, tuple.type) then
for _, attr in pairs(users) do
attr.status = "UPDATED"
end
end
Alternatively you could use a lookup table
local isUpdateType = {
["01"] = true,
["02"] = true,
["03"] = true,
["04"] = true,
}
and later
if isUpdateType[tuple.type] then end
How to solve this depends very much on what you consider "beautiful" here.

Correct test in .lua

I'm new in lua.
Sorry for too much text, but I really need help
There is a space "company". Inside it's "information" map. Inside this map is a "job" object and an array of "users" objects. The "users" array consists of 2 objects. Each object has 4 fields.
"company": {
"company_id" : 1,
"type" : "01",
"number" : "YES",
"information":
{
"job":
{
"job_name": "N",
"job_address": 1670392687114
},
"users":
[
{
"id": 1,
"name": "Alex",
"rate": 4,
"address": "bla bla bla"
},
{
"id": 2,
"name": "Jenifer",
"rate": 5,
"address": "bla bla bla"
}
]
}
}
There is a migration for renaming fields in a space and adding new field data, provided:
local space_name = 'company'
local space = box.space[space_name]
local key_parts = space.index.primary.parts
local updated = 0
local counter = 0
local isUpdateType = {
["01"] = true,
["02"] = true,
["03"] = true,
["04"] = true,
}
for _, tuple in space:pairs() do
if tuple.information ~= nil and tuple.information.users ~= nil then
local information = tuple.information
local users = tuple.information.users
-- rename fields and assign nil to the old fields
for _, attr in pairs(users) do
attr.user_rate = attr.rate
attr.rate = nil
attr.user_address = attr.address
attr.address = nil
end
-- update data according to the condition
if isUpdateType[tuple.type] and tuple.number == "YES" then
for _, attr in pairs(users) do
attr.status = "UPDATED"
end
end
local key = {}
for _, part in ipairs(key_parts) do table.insert(key, tuple[part.fieldno]) end
space:update(key, { {'=', 'information', information} })
updated = updated + 1
end
counter = counter + 1
if counter % 1000 == 0 then
fiber.yield()
end
if counter % 10000 == 0 then
log.info('%s: %s tuples have been checked in space %s', migration, counter, space_name)
end
end log.info('%s: %s tuples have been updated from space %s', migration, updated, space_name)
Here we are at the beginning
rename fields and assign nil to the old fields
update data according to the condition: if type = "01" or "02" or "03" or "04" and number = "YES", then add a new field status = "UPDATED" to each element of the users array
I wrote a part of the test that checks if there is a "company" space and if it contains an "information" map and if it contains an array "users" in which the fields from "rate" and "address" have been renamed to the new "user_rate" and "user_address".
I'm not sure I wrote the test correctly.
Also I'm missing part of the test for the second condition of the migration: adding a new field status = "UPDATED" under a certain condition.
local space_name = 'company'
g.before_all(function()
utils.init_config_loader(helper)
utils.apply_migrations_before(helper, '005')
end)
g.after_all(function()
utils.cleanup(helper)
end)
g.check_if_exist_space = function()
local operation = 'upsert'
utils.data_into_space(helper, space_name, 4, operation)
utils.apply_migrations(helper, { '005_update_company.lua' },
{ './migrations/005_update_company.lua' })
for index = 1, 4 do
local res, err = helper.cluster.main_server.net_box:eval([[
local router_helper = require('app.utils.router_helper')
local space_name, key, shard_value = ...
return crud.get(space_name, key, { fields = {'information'}})
]], { space_name, 'company_id' .. index })
t.assert_equals(err, nil)
t.assert_equals(#res.rows, 1)
t.assert_equals(#res.rows[1], 1)
local information = res.rows[1][1]
t.assert_equals(#information, 1)
t.assert_equals(information.users[1].rate, 'user_rate' .. index)
t.assert_equals(information.users[1].address, 'user_address' .. index)
end
end
Can you help me please?

Using data from the first response in the body of the second

I'm trying to combine requests from two services in one endpoint.
The first returns the list of users, like this:
{
"data": [
{ "id": 1, "name": "first", "photo": "employee_photos/key1.png" },
{ "id": 2, "name": "second", "photo": null },
{ "id": 3, "name": "third", "photo": "employee_photos/key3.png" }
]
}
The second is supposed to receive the POST request with the JSON listing photo keys to get the required version URLs.
Request:
{
"keys": [ "employee_photos/key1.png", "employee_photos/key3.png" ],
"versions": [ "small", "large" ]
}
I created a small Lua script to process the response of the first request and collect the list of keys. It looks like this:
function post_employees(request, employeesResponse)
local resp = employeesResponse.load()
local data = resp:data():get("data")
local photo_keys = {}
for i = 0, data:len() - 1, 1 do
local rec = data:get(i)
local id = rec:get("id")
local photo = rec:get("photo")
if photo then
table.insert(photo_keys, photo)
end
end
resp:data():set("photos", table.concat(photo_keys, ","))
end
But then... I can't find a way to use this list of keys in the second request. Is it even possible?

LUA - Is possible to get values of an index in a multidimensional table?

It is possible to get/return multiple values of an index in a multidimensional array/table?
I have tried lots of methods but none seem to work or at least IDK how to implement them since I'm new to Lua.
This is what I have done or got so far, my table looks like this:
data = {
["oranges"] = {
["price"] = {
"0.23",
},
["location"] = {
["nearest"] = {
"Russia",
"United States",
},
["farthest"] = {
"Brazil",
"Australia",
},
},
},
-- More...
}
What I want from that is all values from let's say ["nearest"]
The function I'm working with is a mess but well:
function getNearestLocation(data)
for k, v in pairs(data) do
if v == "oranges"
then
-- Whatever I do here can't get it to work.
for data, subdata in pairs({v}) do
if subdata == "location"
then
return subdata["nearest"]
end
end
end
end
end
It is possible then to get {"Russia","United States"} for example. Thanks in advance.
The table you seek is data["orange"]["location"]["nearest"].
If you need a function, use
function getNearestLocation(data)
return data["orange"]["location"]["nearest"]
end

Stripe_ruby Unable to store card_last4 and card_type after successful customer creation

After creating a customer successfully, I can inspect the object with:
Rails.logger.debug("single card object has: #{customer.cards.data.card.inspect}")
which returns a json like this:
#<Stripe: : Customer: 0x2801284>JSON: {
"id": "cus_2WXxmvhBJgSmNY",
"object": "customer",
"cards": {
"object": "list",
"data": [
{
"id": "card_2WXxcCsdY0Jjav",
"object": "card",
"last4": "4242",
"type": "Visa",
"exp_month": 1,
"exp_year": 2014,
}
]
},
"default_card": "card_2WXxcCsdY0Jjav"
}
But I will do Customer.cards.data.last4 it gives a NOMethodError.
If I remove the last4 and just call Customer.cards.data, it gives
#<Stripe: : Card: 0x1ed7dc0>JSON: {
"id": "card_2Wmd80yQ76XZKH",
"object": "card",
"last4": "4242",
"type": "Visa",
"exp_month": 1,
"exp_year": 2015,
}
Now I seem to have the direct card object but if I do
card = Customer.cards.data
self.last4 = card.last4
I still get a noMethodError
Here is shortened version of my model:
class Payment < ActiveRecord::Base
def create_customer_in_stripe(params)
if self.user.stripe_card_token.blank?
user_email = self.user.email
customer = Stripe::Customer.create(email: user_email, card: params[:token])
card = customer.cards.data
self.card_last4 = card.last4
self.card_type = card.type
self.card_exp_month = card.exp_month
self.card_exp_year = card.exp_year
self.user.save
end
self.save!
end
end
customer.cards, as the name implies, returns multiple cards in an array.
You can't call card accessor methods because you don't have a Stripe::Card object; you have an array of Stripe::Card objects. You need to either call customer.cards.first (the most likely answer) or iterate over the array for a specific card you're looking for.
Once you have a Stripe::Card object, all the accessor methods will work correctly.
cself.card_last4 = card.last4 should be self.card_last4 = card["last4"] as the gem itself doesn't have a last4 method when searching on github. I know i have to use Hash syntax.
I have a feeling that all of your methods on card will need this syntax.
EDit:
So it sounds like your model's last4 column is an integer, do card["last4"].to_i or change the migration to a string column in the DB.
card = Customer.cards.data
self.last4 = card[0].last4
how do you get the default active card in
rails "default_card": "card_2WXxcCsdY0Jjav" in the list of customer.cards?
is there a better way rather than to loop thru customer.cards to get it or even easier way?
Any pointers?
Hope this help someone who is wondering as well :- )
default_active_card = customer.cards.data.detect{|obj| obj[:id] == customer.default_card}

Resources