I'm new to dart development...
I can't figure out how to use the Json_serializable package with enum types. my database has the enum values as an integer, but it looks like JSON_Serializable wants the value to be a string representation of the enum name.. IE:
enum Classification { None, Open, Inactive, Closed, Default, Delete, ZeroRecord }
database has Classification as an integer value (4: which is Default)
when loading from JSON I get an exception
EXCEPTION: Invalid argument(s): 4 is not one of the supported values: None, Open, Inactive, Closed, Default, Delete, ZeroRecord
How do I force JSON_Serializable to treat 4 as "Default"?
Basically you have two options. (AFAIK)
In your enum file, for each value you may add a #JsonValue(VALUE) annotation, json_serializable will use that value instead of the name, and it can be anything actually.
You could have your enum as follows:
enum Classification {
#JsonValue(0)
None,
#JsonValue(1)
Open,
#JsonValue(2)
Inactive,
#JsonValue(3)
Closed,
#JsonValue(4)
Default,
#JsonValue(5)
Delete,
#JsonValue(6)
ZeroRecord,
}
another thing you can do if you really want a default value, is to use the #JsonKey annotation and set the unknownEnumValue property to the desired default value
class MyModel {
#JsonKey(unknownEnumValue: Classification.Default)
Classification classification;
}
Related
My Swift 3 app uses CoreData. Since the transition to Swift3/Xcode 8, I have abandoned automatic code generation for NSManagedObject subclasses (The new behavior, I still haven't quite figured it out yet), so I just specify non/manual and create my own classes. So far so good.
I am storing all my scalar attributes in NSNumber? properties, not optional scalar types like Int?, Double?, etc. (I'm not sure if optional scalar properties work well with Core Data...?).
The problem is, I can not detect the "Value not Yet Set" state of the attributes in my freshly created objects.
For example, I have:
class MyClass: NSManagedObject {
// Stores a double
#NSManaged var length: NSNumber?
}
Whenever I try to access the value, I never get nil, but 0.0 instead:
if let value = myObject.length?.doubleValue {
// Always gets executes and value 0.0 is unwrapped
// for new objects
} else {
// Never gets executed
}
However, if I manually set it to nil on instance insertion, i.e.:
override awakeFromInsert(){
super.awakeFromInsert()
// Explicitly set to nil:
self.length = nil
}
...then, I get the expected behavior.
Did I miss something?
I'm guessing that the #NSManaged attribute makes it in many ways different than a run-of-the-mill swift optional property... But I can not find mention of this behavior anywhere.
I agree with Arun that you need to select a type (in fact, you should be getting an error if you don't).
As to your issue, by default CoreData adds defaults for numeric fields. You can, however direct it to not set a default value by using the Data Model inspector, as shown below:
If you do turn off the default and leave the field empty when you create a new record, be sure the Optional checkbox is checked as well (it's a few rows above the default checkbox).
Also, if you add required fields without defaults after your first deployment, you will need to handle migration yourself as light migrations rely on the default when adding new mandatory fields to existing databases.
You cannot select NSNumber as datatype while selecting from the core-data .xcmodel class. When you create attribute you define a default value. Below is the screenshot which mentions the default value type .
So if you want the value in the length as double select double as default value.
Create managed class from the Xcode. Xcode->Editor->Create NSManagedObject SubClass. You generate the classes automatically.
I have an enum in one of my model in my api
enum pay_method: {
cash: 0,
card: 1
}
I want to have validation for this enum but i can not do that . I wrote a validation in my model for that but it did not take any effect
A validation for enum is not going to work, because Rails does not even allow to assign an enum variable with a wrong value. You will get an error before a validation. There is a good discussion of this behaviour here https://github.com/rails/rails/issues/13971
rails enum functionality throws an error if the value submitted does not correspond to one of the keys or values of the hash. in this case it does not correspond to the key because the value you are submitting is a string so until here you are correct.
the error still appear because enums are set before the validation process. this could help you understand
#shippimg = Shippig.first
#shipping.status = 99
ArgumentError: '99' is not a valid status
rails developers say that programmers are the ones responsible taking care of what values they use assingning to enum attributes
i have made a gem for validating enums inclusion. this at least stops your server from crashing https://github.com/CristiRazvi/enum_attributes_validation
For certain operations, our API responds with static bits of JSON, for example:
{"status":"ok"}
The closest I've come to making a model definition for this is:
definitions:
OKMessage:
type: object
properties:
status:
type: string
enum: ['ok']
but it feels like there should be a more straightforward way of representing a static string in a model (and results in clearer docs). Is there something in the spec I'm missing?
I think that's the correct way to define the response. You may consider using just string (not enum) to give you flexibility in adding different values (e.g. error, processing, etc) in the future.
I have a model to handle different application settings. Each setting has a value_type e.g. string, integer, boolean and enum. If a settings is defined as enum, it has many enum_options (just saved as key, value with a reference to the setting in database).
To handle these enums I want to use Enumerize gem. I tried a lot but I can't set enum option from database.
Here is my code how I try to define the different enum options.
enumerize :enum_values, in: -> { EnumOption.where(functional_parameter_id: self.id).map(&:value.to_sym) }
After that I try to call Setting.find(1).enum_values and I got nil.
If I call Setting.enum_values.values to get all available options to select, I just got ["#<Proc:0x007fd7e78e9218#/Users/path/to/app/app/models/setting.rb:31 (lambda)>"]
Is it possible to set the enum options dynamically?
I don't think you can use in with a lamdba literal in enumerize. This feature is not documented anywhere, and having a look at https://github.com/brainspec/enumerize/blob/c65867580967724479af1bffbfbea05cbfa62db4/lib/enumerize/attribute.rb#L15, it seems that enumerize strictly wants you to pass an array.
I want to build a wrapper around log4j2 to do the below:
1) There are around 6 mandatory fields like event_name, action, desc etc
2) Some fields, i want to make them use only certain values, like enum
3) log should be created in key value pairs for Splunk.
Below is my approach:
1) Created a class called CustomLogger accepeting the mandatory fields, logger and variable fields as key value
2) Users can call methods like below:
CustomLogger.info(logger, transactionId, app_name, event_name,
"inside the loop", "inside the loop of the sample app",
CustomLogger.Result.success, "looped in", "loop_count",
String.valueOf(i));
Method definition:
public static String log(LogLevel logLevel, Logger logger,
String transactionId, String app_name, String event_name,
String action, String desc, Result result, String reason,
String... addtnlFields)
Issues with the approach:
1) Not extending the log4j, not sure if this is the right way
2) need to pass the logger from every class. If that can be avoided
3) method and line number is lost since it is getting called from a different method
This will be widely used across my internal applications, so want to do it right. Is this approach ok or is there a better approach?
Take a look at the code generator attached to this Jira: https://issues.apache.org/jira/browse/LOG4J2-519
Perhaps you can use that as a base class? Gives you a slightly nicer API.
(I still need to update this to reflect some API changes in log4j-2.0-rc2...)
UPDATE
A different approach is to have a custom implementation of the Message interface defined in the log4j2 api module. Your custom message would have a constructor with all fields you define as required, and the toString method (and perhaps some other methods too) would format these fields as you require into key-value pairs.