kgiszczak / shale

Shale is a Ruby object mapper and serializer for JSON, YAML, TOML, CSV and XML. It allows you to parse JSON, YAML, TOML, CSV and XML data and convert it into Ruby data structures, as well as serialize data structures into JSON, YAML, TOML, CSV or XML.
https://shalerb.org/
MIT License
618 stars 19 forks source link

render_nil as a global setting #17

Closed feliperaul closed 1 year ago

feliperaul commented 1 year ago

Hi! Thank you for this great gem. Would you consider making render_nil a global setting, like Shale.render_nil = true ?

kgiszczak commented 1 year ago

Hey, yeah, I'll do something like that, but instead of a global setting I was thinking about making it a field on a mapping, eg:

class Base < Shale::Mapper
  json do
    render_nil true
  end
end

# This class will inherit defaults from base
class Address < Base
end

That way you could have more fine grained control over what default you want to use and where you want to use it.

feliperaul commented 1 year ago

Makes sense!

kgiszczak commented 1 year ago

It's ready for testing on master branch. I'll do a new version release in a few weeks.

feliperaul commented 1 year ago

@kgiszczak I'm testing on master, but noticed that it still doesn't render nil values with the to_hash transform.

kgiszczak commented 1 year ago

Hey do you have an example? When I set it on hash mapping it seems to work correctly, e.g:

require 'shale'

class Person < Shale::Mapper
  attribute :first_name, Shale::Type::String
  attribute :last_name, Shale::Type::String

  hsh do
    render_nil true

    map 'first_name', to: :first_name
    map 'last_name', to: :last_name
  end
end

puts Person.new(first_name: 'John').to_hash

It gives me this output:

{"first_name"=>"John", "last_name"=>nil}