trailblazer / representable

Maps representation documents from and to Ruby objects. Includes JSON, XML and YAML support, plain properties and compositions.
http://trailblazer.to/2.1/docs/representable.html
MIT License
689 stars 108 forks source link

Parsing null values results in property being set despite `reader` property present #234

Open oliverguenther opened 5 years ago

oliverguenther commented 5 years ago

The reader: option is documented as follows:

With :reader, parsing is completely up to you. Representable will only invoke the function and do nothing else.

I have the following representer that sets a different property on represented after processing it. I do not want to have status_code being set automatically by representable, which is why I'm using a reader. Actually, I could have lived with a setter: but that again is not called when passing { status: nil } into the representer.

class MyRepresenter < Representable::Decorator
        property :status,
                 getter: ->(*) { status&.code },
                 reader: ->(doc:, represented:, **) {
                   status = doc['status']
                   # (omitted custom processing of status)
                   represented.status = status
                 }  
end

I would suspect the following code:

object = OpenStruct.new
hash = { status: nil }
MyRepresenter.new(object).from_hash(hash)

to output

{ status_code: "whatever is being returned by my reader function" }

But actually the call outputs

{ status_code: "whatever is being returned by my reader function", status: nil }

How should one avoid the status property being written and bypassing any setter / reader ?