transit-ruby. Change casing between snake_case, hyphens when reading/writing

32 views
Skip to first unread message

Daniel Marjenburgh

unread,
Dec 7, 2015, 5:57:57 PM12/7/15
to transit-format
Hello,

Is there a way to make Transit emit the keys of hashes to use hyphens when it is a Symbol?
For example, the following happens:

w = Transit::Writer.new(:json, STDOUT)
w.write({a_b: 1})
# => ["^ ","~:a_b",1]

I would like to configure the writer to emit:
# => ["^ ","~:a-b",1]

Is there a way to do this without resorting to writing the hash as {:"a-b" => 1} ?

Alternatively, is there a way to configure the reader in transit-clj to convert keywords like :a_b to :a-b?

Thanks

David Chelimsky

unread,
Dec 7, 2015, 7:12:56 PM12/7/15
to transit-format
You can handle this in (at least) 3 ways:

1 - coerce transit-ruby to write ruby Symbols differently via a custom write handler
2 - coerce transit-clj to read transit keywords differently via a custom read handler
3 - introduce a new type in your Ruby app to wrap your map keys and add a custom write handler for that type

I'd probably lean toward the 3rd option, as that avoids the risk you'd be introducing by changing a core behavior in the 1st and 2nd options (akin to the risks of monkey patching).

Either way, take a look at http://blog.cognitect.com/blog/2015/9/10/extending-transit and http://www.rubydoc.info/gems/transit-ruby/Transit/WriteHandlers for more info about custom handlers. Feel free to post back to this thread if you have any questions about any of this.

Cheers,
David

Daniel Marjenburgh

unread,
Dec 7, 2015, 7:42:40 PM12/7/15
to transit-format
I have found the answer to the alternative, by passing:
{:handlers {":" (transit/read-handler
(fn [o] (keyword (.replaceAll ^String o "_" "-"))))}}

Daniel Marjenburgh

unread,
Dec 9, 2015, 5:14:19 AM12/9/15
to transit-format
Thank you David.
Reply all
Reply to author
Forward
0 new messages