TL/DR: What's a good way to use an underscored naming convention serverside (RoR) with a camelCased naming convention clientside (JS)
Server-side programming environments like Ruby on Rails use underscored variables. Conventionally, JavaScript uses camelCased variables. This is problematic when sending data from the client to the server.
For example, consider sending user information to the client. There may be a property in the database called num_times_ordered, yet in JavaScript you'd traditionally want to refer to this as numTimesOrdered.
Has anyone come up with an elegant way of dealing with this? Here are some options, none particularly nice:
I'm leaning towards #3, and using underscores in my JavaScript. It'll look weird when I use camelCased third party libraries, though.
camelCase is used by JavaScript itself, by jQuery, and other JavaScript libraries. Do not start names with a $ sign. It will put you in conflict with many JavaScript library names.
When multiple words are used to form a variable, camel case joins those words together, without any white space, and delineates the start of each new word with a capital letter.
CamelCase is a way to separate the words in a phrase by making the first letter of each word capitalized and not using spaces. It is commonly used in web URLs, programming and computer naming conventions. It is named after camels because the capital letters resemble the humps on a camel's back.
I believe ember.js (via Ember Data) takes approach #1: converting underscored JSON to camelCase on the client-side when fetched; and doing the reverse before posting back to the server.
I've been working on a small library that performs these conversions: https://github.com/domchristie/humps, allowing you to do things like:
// GET
$.ajax({
url: '/posts',
dataType: 'json',
success: function(data, status, xhr) {
data = humps.camelizeKeys(data);
}
});
// POST
$.ajax({
type: 'POST',
url: '/posts'
dataType: 'json',
data: humps.decamelizeKeys({
title: "Foo",
publishedAt: "2012-09-03T21:35:46.068Z"
})
});
// Sends: { title: "Foo", published_at: "2012-09-03T21:35:46.068Z" }
I should add, it has not been heavily tested, but contributions welcome!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With