codenoble / cache-crispies

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

Reserved keywords in serializer #23

Open floriandejonckheere opened 4 years ago

floriandejonckheere commented 4 years ago

Due to the way the serialization mechanism is written, attributes in a serializer cannot be named either model or options, because these methods are already defined on CacheCrispies::Base. No warning or error is thrown either.

The following example demonstrates this:

#!/usr/bin/env ruby

require "cache_crispies"

class MySerializer < CacheCrispies::Base
  key :my_serializer

  serialize :id

  serialize :options do |model, options|
    # the passed `model` will not be the model, but rather the instance
    # of the serializer. To retrieve the model, we have to call
    # `model.model`.
    model.model.options
  end
end

model = OpenStruct.new(id: "my_id", options: { my_option: true })

puts MySerializer.new(model, {}).as_json

=> {:id=>"my_id", :options=>{}}

The logic that exhibits this can be found on https://github.com/codenoble/cache-crispies/blob/master/lib/cache_crispies/hash_builder.rb#L63.

adamcrown commented 4 years ago

That's a good point. Thanks for bringing that up. I'll see if I can come up with a fix for this, or at the very least a warning.