Other articles in the series
The back-end related code for this post is available here.
In this post, we will refactor our Phoenix codebase and fix tests. So our step would be to adopt a consistent naming for database tables and column names. Currently we have camel case and snake case for our table column names. We will adopt the snake case style for our column names. The first step to achieve this would be to create a migration and then rename the required columns in that migration.
mix ecto.gen.migration rename_fields_snake_case
This will create a file in the priv/repo/migrations/ folder. Lets make the following changes there.
defmodule Ms.Repo.Migrations.RenameFieldsSnakeCase do use Ecto.Migration def change do rename table("orders"), :creationDate, to: :creation_date rename table("order_items"), :unitPrice, to: :unit_price rename table("deliveries"), :orderitem, to: :order_item end end
The change function will be executed when we apply the migration. The changes are self-explanatory. Now we need to rename all occurrences of unitPrices to unit_price and so on in all files. This is a simple search and replace operation. This results in changes in schema files inside ms/ directory. For example the ms/order_management/order_item.ex file becomes
defmodule Ms.OrderManagement.OrderItem do use Ecto.Schema import Ecto.Changeset schema "order_items" do field :amount, :integer field :unit_price, :float field :product, :id field :order, :id timestamps() end @doc false def changeset(order_item, attrs) do order_item |> cast(attrs, [:amount, :unit_price]) |> validate_required([:amount, :unit_price]) end end
This will also change some tests. But by running tests using,
MIX_ENV=test mix test
we can confirm that all tests are passing. MIX_ENV is an environment telling mix about the running context. For example to drop the test database from ecto, we can use
MIX_ENV=test mix ecto.drop
If we set MIX_ENV=prod, it will drop the production database.
Now lets fix another inconsistency in our naming conventions. All management modules like customer_management, order_management end with an _management, except inventory. In order to ensure consistency we will rename inventory to inventory_management. This is also pretty simple by replacing all occurrences of Inventory with InventoryManagement. Then rename inventory folder to inventory_management and we are done. Just like in previous case, it will also change some tests. By running tests again, we can confirm that things are working correctly.
In next post, we will add order handling functionality.