Convert string to enum in ruby (in controller) - ruby

I am creating a webhook route where I will receive a JSON, so I am converting it into an object as follows:
data = JSON.parse(request.body.read, object_class: OpenStruct)
And that generates the object I want. This object however has a property that is similar to an ENUM, which has some 'predictable' values
being: PURCHASE_APPROVED, PURCHASE_CANCELED.
They come as a string, so I tried to do the following to convert them
events = { PURCHASE_CANCELED: 0, PURCHASE_APPROVED: 1 }
So I want to take the value that came as a string and transform it into an enum, the way I managed to convert the data was:
data.event = events[data.event.to_sym]
But the data doesn't become an enum, I can't use some properties like the
data.event.PURCHASE_APPROVED?
Is there any simple way to do this within the controller? Or would I have to create a class and specify each property just to have 1 enum?

Related

Initialize non existing keys to empty array list

I have a class :
class Con {
private List<Ind> inds;
}
I am using Gson in the usual way to convert a JSON string to this class object. so in case, the JSON doesn't have the key inds present this variable inds is assigned a null value. Is there a way to assign inds an empty ArrayList instead?
My Thoughts:
One straightforward way could be once the Gson object is built. Go over all the null objects and assign them to the new ArrayList<>(). Is there a better approach?
public List<Ind> getInds() {
return inds;
}
Currently I am using the above getter in a code like : con.getInds().stream() which is causing NullPointerException.
I am not sure what would be a good way to resolve this. Instead of List Should I return an Optional or Should I modify this getter like
public List<Ind> getInds() {
inds==null?new ArrayList<>():inds;
}
The above will also resolve the NullPointerException. Not sure if there are pros and cons to using this approach. Although now there is no way to identify if the Json has a key with name inds or not. For the current code that I am writing this may not be required. But there is a meaning loss here certainly.
One solution to this would be to assign default values to the fields, for example:
class Con {
private List<Ind> inds = new ArrayList<>();
}
Gson will keep this default value; only if the field is present in the JSON data it will reassign the field value.
There are however a few things to keep in mind:
Your class needs a no-args constructor (implicit or explicit); otherwise Gson might create instances without invoking the initializer blocks of the class, and therefore the field will be null
If the field is present in JSON but has a JSON null value, then Gson will still set that as value
You cannot tell afterwards whether the field was present in JSON but had an empty JSON array as value, or whether it was missing

K8s operator read raw data

Im trying to get RAW data from operator CR and im getting an empty object . (all others value are working as expected )
I’ve created a minimal example for the issue, in the example im trying to read the infrastructureConfig object
The tricky part here that my struct is reference to another struct which have a property type rawdata
https://github.com/JennyMet/gardner_test
Here the simple CR
https://github.com/JennyMet/gardner_test/blob/main/config/samples/mygroup_v1alpha1_rawtest.yaml#L11
Here im tying to read the data and get an empty object, any idea?
https://github.com/JennyMet/gardner_test/blob/main/controllers/rawtest_controller.go#L70
this is the reference of the type which im using
https://github.com/gardener/gardener/blob/5522be0e17ccf38aae36efb9fdb6463c66d6e4f1/pkg/apis/core/v1beta1/types_shoot.go#L1184
I think its related to fields
x-kubernetes-preserve-unknown-fields: true
https://book.kubebuilder.io/reference/markers/crd-processing.html
which is not existing
How can I add it to the schema here ?
https://github.com/JennyMet/gardner_test/blob/main/api/v1alpha1/rawtest_types.go#L32 as under the hood it uses
https://github.com/gardener/gardener/blob/5522be0e17ccf38aae36efb9fdb6463c66d6e4f1/pkg/apis/core/v1beta1/types_shoot.go#L1184
I mean I tried and it doesnt work as the InfrastructureConfig which is RAW is under the
type System struct {
Type system `json:"type,omitempty"`
// +kubebuilder:pruning:PreserveUnknownFields
Provider v1beta1.Provider `json:"provider,omitempty"`
}
But the rawData is under Provider which is not my struct, im just using it.
which is like this , see the InfrastructureConfig type...
type Provider struct {
Type string `json:"type" protobuf:"bytes,1,opt,name=type"`
ControlPlaneConfig *runtime.RawExtension `json:"controlPlaneConfig,omitempty" protobuf:"bytes,2,opt,name=controlPlaneConfig"`
InfrastructureConfig *runtime.RawExtension `json:"infrastructureConfig,omitempty" protobuf:"bytes,3,opt,name=infrastructureConfig"`
}
Currently, you can only put the // +kubebuilder:pruning:PreserveUnknownFields on the Provider v1beta1.Provider, which means all sub fields in it will be allowed with additional unknown fields.
The good news is, your problem will be solved after https://github.com/kubernetes-sigs/controller-tools/pull/683 merged. After that, you have not to use // +kubebuilder:pruning:PreserveUnknownFields and controller-tools would automatically add x-kubernetes-preserve-unknown-fields: true for all RawExtension fields.

How to implement Google Protobuf containing map with custom key

I want to create a protobuf which returns a map containing custom keys. When I try to make one, I get an error: Key in map fields cannot be float/double, bytes or message types. I want to know if there is a workaround for it.
I am trying to create a map of following type (as an illustration):
message Name {
string first_name = 1;
string last_name = 2;
}
message GetNameResp {
map<Name, string> name_info = 1;
}
So, can the Name here be a possible key to the map? The only solution I could find was to serialize the map and then return as repeated values.
Thanks!
Map keys may not be message types:
https://developers.google.com/protocol-buffers/docs/proto3#maps
You would have to work around this in code.
You could convert Name to string:
serialize the protobuf message
marshaling to JSON
hashing the value (though you'd potentially have collisions)

Convert interface{} to struct in Golang

I am very new to Go and am trying to get my head around all the different types and how to use them. I have an interface with the following (which was originally in a json file):
[map[item:electricity transform:{fuelType}] map[transform:{fuelType} item:gas]]
and I have the following struct
type urlTransform struct {
item string
transform string
}
I have no idea how to get the interface data into the struct; I'm sure this is really stupid, but I have been trying all day. Any help would be greatly appreciated.
Decode the JSON directly to types you want instead of decoding to an interface{}.
Declare types that match the structure of your JSON data. Use structs for JSON objects and slices for JSON arrays:
type transform struct {
// not enough information in question to fill this in.
}
type urlTransform struct {
Item string
Transform transform
}
var transforms []urlTransform
The field names must be exported (start with uppercase letter).
Unmarshal the JSON to the declared value:
err := json.Unmarshal(data, &transforms)
or
err := json.NewDecoder(reader).Decode(&transforms)
From your response : [map[item:electricity transform:{fuelType}] map[transform:{fuelType} item:gas]].
As you can see here this is a an array that has map in it.
One way to get the value from this is :
values := yourResponse[0].(map[string]interface{}). // convert first index to map that has interface value.
transform := urlTransform{}
transform.Item = values["item"].(string) // convert the item value to string
transform.Transform = values["transform"].(string)
//and so on...
as you can see from the code above I'm getting the the value using map. And convert the value to the appropriate type in this case is string.
You can convert it to appropriate type like int or bool or other type. but this approach is painful as you need to get the value one bye one and assign it your your field struct.

string was not recognized as a valid datetime. in c#

i am using this code for passing datetime.
Convert.ToDateTime(textBox1.Text)
but the compiler show an error that string was not recognized as a valid datetime. so how to avoid this error and is a datetime field in my database.
Convert.ToDateTime(textBox1.Text)
This code will throw an exception if the string value in textBox1.Text doesn't represent a valid DateTime (or at least can't be parsed into one with default functionality in C#). You can add some defensive programming to handle errors like this.
The DateTime type (as well as most, if not all, common value types in .NET) has a method on it called TryParse() specifically for the purpose to attempting to parse a value into that type without throwing an exception. The method returns true if the parse was successful, false otherwise. And it accepts an out parameter to hold the resulting parsed value (or the original value if parsing is unsuccessful).
So instead of this:
var dateTimeValue = Convert.ToDateTime(textBox1.Text);
You could use something like this:
var dateTimeValue = DateTime.MinValue;
if (DateTime.TryParse(textBox1.Text, out dateTimeValue))
// use the value for something

Resources