Hello everyone! I’m excited to share my first Hex package: Morpheus.
What is Morpheus?
Morpheus is a lightweight library designed to seamlessly convert between snake_case
and camelCase
in Phoenix projects. It’s particularly useful when your Phoenix API needs to communicate with frontend JavaScript code, where camelCase is the common convention.
This library was inspired by proper_case, which hasn’t been updated since May 2020. I decided to create a new library that:
- Works with the latest Elixir (1.17)
- Has minimal dependencies (only Jason)
- Focuses on the most common use case: converting between snake_case and camelCase
- Maintains a lightweight and simple API
Features
- Convert map keys from
snake_case
tocamelCase
and vice versa - Handle nested maps and lists
- Preserve atom and string key types
- Seamless integration with Phoenix for automatic conversion of JSON responses
Quick Start
Add morpheus
to your dependencies in mix.exs
:
def deps do
[
{:morpheus, "~> 0.1.0"}
]
end
In your config/config.exs
, add the following after Jason config:
config :phoenix, :format_encoders, json: Morpheus.Encoder
Now your Phoenix controllers will automatically convert snake_case keys to camelCase in JSON responses:
def show(conn, %{"id" => id}) do
user = %{
user_id: id,
first_name: "John",
last_name: "Doe",
email_address: "john@example.com"
}
json(conn, user) # Will be converted to camelCase automatically
end
For incoming requests, add the plug to your router:
pipeline :api do
plug :accepts, ["json"]
plug Morpheus.Plugs.SnakeCaseParams
end
Links
This is my first contribution to the Elixir ecosystem. Feedback, suggestions, and contributions are welcome! Let me know if you find it useful or have any ideas for improvement.