I have a hash that looks something like this:
{ :a => "some string", :b => "another string", :c => "yet another string" }
I wan’t to call to_jsonon it eventually, but the resulting json-string cannot be longer than n bytes.
If the string is too big, then first :c should be truncated first. If that’s not enough, :b should be truncated. Finally :a. Also the strings can contain multi-byte characters like German umlauts and the Ruby version is 1.8.7. (The umlauts first take 2 bytes, but as json they are 5 bytes long.)
What I wrote was a loop that converts the hash to_json and checks the length. If its less or equal n it’s returned, otherwise I concat the values of :a + :b + :c and shorten by half. If the new hash is too big(small), I shorten(extend) by 1/4th, 1/8th, 1/16th of the original string. Finally I get length of hash.as_json == n.
It all feels very hackish and although all tests check out I’m not sure that’s even stable.
Does anyone have a good suggestion how to solve this properly?
How about: