Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby API response as lower camel case

I'm trying to return the API response as lowerCamelCase but it is not working, I need to do this for all my Controllers/fields so I need a solution for entire project.

I've tried a lot of stuff, including this (http://brentvatne.ca/automatic-casing-activemodel-serializer/) who tells me to configure Activemodel to lower_camel as following

ActiveModel::Serializer.config.key_format = :lower_camel

But that is not working, it is returning the following json

{
    "users": [{
        "id": "56b110089c28691b84a3bd73",
        "first_name": "Lucas"
    }]
}

I need to transform the first_name into firstName.

Versions:

rails -v
Rails 4.2.5

ruby -v
ruby 2.2.3p173 (2015-08-18 revision 51636) [i386-mingw32]

And the gems

active_model_serializers (0.10.0.rc4)
rails-api (0.4.0)

My ember App recognize the JSON but I don't want to use snake case variables on JS

like image 904
Saliba Avatar asked Feb 16 '16 16:02

Saliba


People also ask

How do you change Camelcase to snake case in Ruby?

Method: String#snakecase Underscore a string such that camelcase, dashes and spaces are replaced by underscores. This is the reverse of #camelcase, albeit not an exact inverse. Note, this method no longer converts `::` to `/`, in that case use the #pathize method instead.

How do you convert a string to a camel case in Ruby?

permalink #camelcase(*separators) ⇒ Object Converts a string to camelcase. This method leaves the first character as given. This allows other methods to be used first, such as #uppercase and #lowercase.

What is snake case in Ruby?

Snake case is a naming convention in which a developer replaces spaces between words with an underscore. Most object-oriented programming languages don't allow variable, method, class and function names to contain spaces.


2 Answers

Boom! I found it! I had to dig through the AMS repo (and eventually stumbled upon a helpful readme) but here it is for v0.10:

ActiveModelSerializers.config.key_transform = :camel_lower

Put that in an initializer.

There are also other options: :dash, :camel, :underscore, and :unaltered, and nil

https://github.com/rails-api/active_model_serializers/blob/a032201a91cbca407211bca0392ba881eef1f7ba/docs/general/configuration_options.md

like image 57
Aaron Krauss Avatar answered Sep 23 '22 12:09

Aaron Krauss


The problem was on the version of Active Model Serializer (0.10.0rc2).

On the last stable version (0.9) there was an issue that has been merged to fix the camelCase but this same PR is not present on the 0.10 RC versions.

So after I have downgraded the gem it worked :)

like image 24
Saliba Avatar answered Sep 22 '22 12:09

Saliba