Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mantle property class based on another property?

How can I use Github Mantle to choose a property class based on another property in the same class? (or in the worse case another part of the JSON object).

For example if i have an object like this:

{
  "content": {"mention_text": "some text"},
  "created_at": 1411750819000,
  "id": 600,
  "type": "mention"
}

I want to make a transformer like this:

+(NSValueTransformer *)contentJSONTransformer {
    return [MTLValueTransformer transformerWithBlock:^id(NSDictionary* contentDict) {
          return [MTLJSONAdapter modelOfClass:ETMentionActivityContent.class fromJSONDictionary:contentDict error:nil];
    }];
}

But the dictionary passed to the transformer only includes the 'content' piece of the JSON, so I don't have access to the 'type' field. Is there anyway to access the rest of the object? Or somehow base the model class of 'content' on the 'type'?

I have previously been forced to do hack solutions like this:

+(NSValueTransformer *)contentJSONTransformer {
    return [MTLValueTransformer transformerWithBlock:^id(NSDictionary* contentDict) {
        if (contentDict[@"mention_text"]) {
            return [MTLJSONAdapter modelOfClass:ETMentionActivityContent.class fromJSONDictionary:contentDict error:nil];
        } else {
            return [MTLJSONAdapter modelOfClass:ETActivityContent.class fromJSONDictionary:contentDict error:nil];
        }
    }];
}
like image 580
pj4533 Avatar asked Sep 30 '14 13:09

pj4533


1 Answers

You can pass the type information by modifying the JSONKeyPathsByPropertyKey method:

+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
    return @{
        NSStringFromSelector(@selector(content)) : @[ @"type", @"content" ],
    };
}

Then in contentJSONTransformer, you can access the "type" property:

+ (NSValueTransformer *)contentJSONTransformer 
{
    return [MTLValueTransformer ...
        ...
        NSString *type = value[@"type"];
        id content = value[@"content"];
    ];
}
like image 54
chourobin Avatar answered Oct 06 '22 15:10

chourobin