codenoble / cache-crispies

Speedy Rails JSON serialization with built-in caching
MIT License
156 stars 14 forks source link

Ability To Provide Options Alongside Nested Serializes #41

Open Seacant opened 2 years ago

Seacant commented 2 years ago

When using nested serializers (serialize :thing, with: ThingSerializer), handling all the options that need to be passed in at the top level can quickly become tedious and prone to mistakes. It would be helpful if we could specify options alongside the nested attribute.

class ThingSerializer < CacheCrispies::Base
  ...

  # top-level options overrides what we specify here
  serialize :thing, with: ThingSerializer, with_options: { 
    | model, options |  ({
      foo: true,
      bar: get_default_bar_for(model),
      baz: !options[:anti_baz],
      **options
    })
  }

  # these options are forced overrides no matter what is passed in up top
  serialize :other_thing: with: OtherSerializer, with_options: {
    | model, options | ({
      **options,
      foo_author: model.foo.author
    })
  }
sander-deryckere commented 2 years ago

We would also want this feature, But I find this a bit over-engineered.

If it depends on the model, or the existing options, you can use a custom defined function already. But for adding a simple option, having to define a custom function seems overkill.

So we would prefer something like this, where the existing options just get augmented with default new options

class ThingSerializer < CacheCrispies::Base
  serialize :thing, with: ThingSerializer, with_options: {
      foo: true,
      bar: "baz",
    }
end

It's especially useful to serialize a common object (i.e. a user), that has an option to switch between a basic and a full serializer.

kyleyardlink commented 2 years ago

Any update on this? we would find it useful too.

adamcrown commented 1 year ago

Sorry for sitting on this one for so long. I remember reading it earlier, but for some reason didn't comment.

This makes sense to me. Although, I'm not sure I'm 100% happy with either approach. If I have time I'll try to poke around a bit in the code and see what I can come up with.