ismasan / hash_mapper

DSL for mapping between data structures

Home Page:http://ismasan.github.com/hash_mapper/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Include missing values in output

iainbeeston opened this issue · comments

Sometimes it'd be nice to include missing values in the output hash. For example, if you have:

map from('/a') to('/b')

and a is not present in the input hash, right now b will not be present in the output hash. I'd like to have the option to make b appear in the output, in this case, but have it be nil.

I've had a quick try at adding this, but haven't got a solution yet. But in any case I'm not totally sure where the best place to put this functionality would be (in the HashMapper? or the Map?) or if there's already a way of doing this?

In a sense what I think should be possible, is to have an option so that if there is a mapping defined, then that column should be present in the output. Perhaps like a required mapping or required field

The behaviour you suggest makes loads of sense, as in I'd like my output hash to have a pre-defined set of fields whose existence I can rely on. However, null doesn't always make sense as a default value (ie. maybe [] would make more sense for an array property) so I think it'd be sensible to make this an op-in option as you suggest.

The #map DSL method could take extra options for this, so the signature could be expanded to

def map(from, to, options = {}, &filter)
 ...
end

The current using optional argument would now be part of the options hash.

So the client code could look something like

map form('/a'), to('/b'), default: nil

So, if a :default is given, and /a doesn't exist, the output property /b is populated with nil.

This would be a backwards incompatible change because of making the using argument a hash value.

Incidentally Parametric has similar behaviour with a :default option that will populate the field if it's not present in the input hash.

There's considerable overlap between the two gems but they could be used in conjunction to solve this problem, too. HashMapper as a mapping layer and then Parametric to fill in defaults for missing fields.

Can parametric handle nested parameters though? (for example, in my
example, setting the default value for /foo/bar/abc to nil)

Could this be made backwards compatibly by making the using method return a
hash? (I'm not really sure how using is used right now)

I'm closing this because defaults can do this