technoweenie / serialized_attributes

kind of a bridge between using AR and a full blown schema-free db
MIT License
61 stars 32 forks source link

serializing a hash with array values converts them to strings #2

Closed tribalvibes closed 14 years ago

tribalvibes commented 14 years ago

serialize_attributes do hash h end

h = { a: 1, b: %w{ foo bar bletch } } save reload puts h.b.class => String

Oops.

tribalvibes commented 14 years ago

Could you please provide a use example of the options: { types: {} } if that is a way to get the encoding of nested types correct? I picked this up because it looked hip but now I'm wasting half a day on it trying to get my job done for something simple.

technoweenie commented 14 years ago

Yea, you can't do nested values. You'd need something like:

serialize_attributes do
  hash :foo do
    array :b
  end
end

I wasn't too stoked about doing that, so hashes only support string values.

tribalvibes commented 14 years ago

That's cool I thought about that nested block form. How silly as the data originates from SOAP. I'm actually a bit surprised. I see with the types option you could specify the types for the first layer of hash keys, but I was expecting something completely unstructured. Am I missing it or could I remove some features and get it to just write and retrieve a nested hash of hashes, numbers, arrays, strings and datetimes?

Actually I think the trouble I was having was due to a config with ActiveSupport::JSON using the json_pure gem. Now that it's set to Yajl seems we're getting somewhere.

technoweenie commented 14 years ago

Well, it's impossible to serialize datetimes because there's no literal format for them in JSON. I think that's the main reason I added schemas.

I don't wan't a nested hash syntax option at all. Maybe if no schema is specified, it stops after parsing the JSON (which should be what you want).

Or, maybe you don't use this plugin. I built it for a very specific use case. You could easily just have some getter and setter for storing compresses JSON.

tribalvibes commented 14 years ago

Yep, I was trying to figure out why you built it like this. I see the BERT encoding, that's cool. I basically forked and added a 'skip_encoding' option to the schema. Our use case is that we want a bunch of model-level named serialized attributes which happen to be the keys of a blob hash from a SOAP source. Actually some are arrays and scalars, so your syntax is perfect for this. However, all the values are unstructured and nested, so we just want a straight JSON serialisation. The problem with DateTime noted, but we will be cautious that the data source is never from user, so not worry about trojan ISO8601 strings being reconstituted as DateTimes. Also see Lighthouse 2182.

Changed your encoding also to call type_for on the nested elements of Arrays and Hashes. This slows down performance somewhat but should stay compatible. I'll commit this stuff in a bit after I get my app working.