rails/rails — pull request #11933 by gaurish (2013-08-19 02:19:39+00:00)
Title: Add option `sorted: true` to ActiveModel::Serializators#as_json

After much back(#11812) & fourth(90c450f), I think this is a good solution for people who would like to have a consistent order across various implementations .

By default `as_json` keeps the order by ruby engine which may be different on jruby vs mri. If you need to be fully sure that you always need a sorted hash whose order is consistent across all ruby implementations, use `sorted: true`.

Example:
```ruby
class Person
include ActiveModel::Serialization
attr_accessor :name, :age
def attributes
{'name' => nil, 'age' => nil}
end
def capitalized_name
name.capitalize
end
end
```

```ruby
person.serializable_hash # => {"name"=>"bob", "age"=>22}
person.serializable_hash(sorted: true) # => {"age"=>22, "name"=>"bob"}
```

so basically, with `sorted` option we will get a alphabetically sorted hash which lot of people will find useful.

cc: @guilleiguaran @spastorino