codenoble / cache-crispies

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

Add CacheCrispies::Base#transform_keys method #55

Open wujibear opened 1 year ago

wujibear commented 1 year ago

I was asking about being able to transform keys to something like camelcase and tried this out. Unsure of your needs for contributions, but let me know what you think of the idea.

With this I can now do the following:

# app/serializers/rest/v1_serializer.rb
class Rest::V1Serializer < CacheCrispies::Base
  transform_keys lambda { |key| key.to_s.camelize(:lower) }
end

# app/serializers/rest/v1/some_serializer.rb
class Rest::V1::SomeSerializer < Rest::V1Serializer
  serialize :id, :created_at, :some_thing
end

Serialized data will look like:

{
  "id": "123",
  "createdAt": "date",
  "someThing": "here"
}

I then have all my serializers inherit from this one and now all my keys will be transformed to lower camelcase

See: https://github.com/codenoble/cache-crispies/issues/52

wujibear commented 1 year ago

Actually, this only seems to work if I put the method in the serializer that is serializing. Doesn't seem to get inherited for some reason, investigating that.

wujibear commented 1 year ago

K. Fixed that, now it checks for parent definitions if no proc or existing instance var is supplied. This lets you write a pattern you can inherit from, but any serializer can explicitly set its own transform method for its attributes

adamcrown commented 1 year ago

Thanks for the PR. This seems reasonable. I know JS tends to lean towards snake-cased variables and having the JSON the same way can make things simpler with object deconstruction.

I would want to see some specs to cover this new functionality before I would merge it though.

wujibear commented 1 year ago

Any other thoughts on method naming, or implementation though?

wujibear commented 1 year ago

Added a spec and docs

wujibear commented 1 year ago

@adamcrown got those specs for you

wujibear commented 1 year ago

@adamcrown Any other thoughts? Would you want to merge this?