Skip to content

Commit

Permalink
Update readme for release
Browse files Browse the repository at this point in the history
  • Loading branch information
kipcole9 committed Dec 8, 2018
1 parent da2d369 commit c5121ea
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,28 @@ iex> MyApp.Cldr.Unit.to_string 1234, unit: :foot, locale: "fr"
iex> MyApp.Cldr.Unit.to_string Cldr.Unit.new(:ampere, 42), locale: "fr"
{:ok, "42 ampères"}

```
### Unit decomposition

Sometimes its a requirement to decompose a unit into one or more subunits. For example, if someone is 6.3 feet heigh we would normally say "6 feet, 4 inches". This can be achieved with `Cldr.Unit.decompose/2`. Using our example:
```
iex(1)> height = Cldr.Unit.new(:foot, 6.3)
#Unit<:foot, 6.3>
iex(2)> Cldr.Unit.decompose height, [:foot, :inch]
[#Unit<:foot, 6.0>, #Unit<:inch, 4.0>]
```

A localised string representing this decomposition can also be produced. `Cldr.Unit.to_string/3` will process a unit list, using the function `Cldr.List.to_string/2` to perform the list combination. Again using the example:
```
iex(3)> c = Cldr.Unit.decompose height, [:foot, :inch]
[#Unit<:foot, 6.0>, #Unit<:inch, 4.0>]
iex(4)> Cldr.Unit.to_string c, TestBackend.Cldr
"6 feet and 4 inches"
iex(5)> Cldr.Unit.to_string c, TestBackend.Cldr, list_options: [format: :unit_short]
"6 feet, 4 inches"
# And of course full localisation is supported
iex> Cldr.Unit.to_string c, TestBackend.Cldr, locale: "fr"
"6 pieds et 4 pouces"
```

### Converting Units
Expand Down
15 changes: 11 additions & 4 deletions lib/cldr/unit.ex
Original file line number Diff line number Diff line change
Expand Up @@ -246,11 +246,18 @@ defmodule Cldr.Unit do
def to_string(list_or_number, backend, options \\ [])

def to_string(unit_list, backend, options) when is_list(unit_list) do
list_options = Keyword.get(options, :list_options, [])
with {locale, _style, options} <- normalize_options(backend, options),
{:ok, locale} <- backend.validate_locale(locale) do

unit_list
|> Enum.map(&to_string!(&1, backend, options))
|> Cldr.List.to_string!(backend, list_options)
list_options =
options
|> Keyword.get(:list_options, [])
|> Keyword.put(:locale, locale)

unit_list
|> Enum.map(&to_string!(&1, backend, options ++ [locale: locale]))
|> Cldr.List.to_string!(backend, list_options)
end
end

def to_string(%Unit{unit: unit, value: value}, backend, options) when is_list(options) do
Expand Down
1 change: 1 addition & 0 deletions test/cldr_units_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,5 @@ defmodule Cldr.UnitsTest do
unit = Cldr.Unit.new(23, :foot)
assert to_string(unit) == "23 feet"
end

end

0 comments on commit c5121ea

Please sign in to comment.