-
Notifications
You must be signed in to change notification settings - Fork 12
/
preference.ex
393 lines (316 loc) · 13.3 KB
/
preference.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
defmodule Cldr.Unit.Preference do
@moduledoc """
In many cultures, the common unit of measure for some
unit categories varies based upon the usage of the
unit.
For example, when describing unit length in the US, the
common use units vary based upon usage such as:
* road distance (miles for larger distances, feet for smaller)
* person height (feet and inches)
* snowfall (inches)
This module provides functions to introspect CLDRs
preference data for difference use cases in different
locales.
"""
alias Cldr.Unit
alias Cldr.Unit.Conversion
alias Cldr.Unit.Conversion.Options
@doc """
Returns a list of the preferred units for a given
unit, locale, territory and use case.
The units used to represent length, volume and so on
depend on a given territory, measurement system and usage.
For example, in the US, people height is most commonly
referred to in `inches`, or informally as `feet and inches`.
In most of the rest of the world it is `centimeters`.
## Arguments
* `unit` is any unit returned by `Cldr.Unit.new/2`.
* `backend` is any Cldr backend module. That is, any module
that includes `use Cldr`. The default is `Cldr.default_backend!/0`
* `options` is a keyword list of options or a
`t:Cldr.Unit.Conversion.Options` struct. The default
is `[]`.
## Options
* `:usage` is the unit usage. for example `;person` for a unit
of type `:length`. The available usage for a given unit category can
be seen with `Cldr.Unit.unit_category_usage/0`. The default is `nil`.
* `:scope` is either `:small` or `nil`. In some usage, the units
used are different when the unit size is small. It is up to the
developer to determine when `scope: :small` is appropriate.
* `:alt` is either `:informal` or `nil`. Like `:scope`, the units
in use depend on whether they are being used in a formal or informal
context.
* `:locale` is any locale returned by `Cldr.validate_locale/2`
## Returns
* `{:ok, unit_list}` or
* `{:error, {exception, reason}}`
## Examples
iex> meter = Cldr.Unit.new!(:meter, 1)
iex> many_meters = Cldr.Unit.new!(:meter, 10_000)
iex> Cldr.Unit.Preference.preferred_units meter, MyApp.Cldr, locale: "en-US", usage: :person
{:ok, [:inch], []}
iex> Cldr.Unit.Preference.preferred_units meter, MyApp.Cldr, locale: "en-AU", usage: :person
{:ok, [:centimeter], []}
iex> Cldr.Unit.Preference.preferred_units meter, MyApp.Cldr, locale: "en-US", usage: :road
{:ok, [:foot], [round_nearest: 1]}
iex> Cldr.Unit.Preference.preferred_units many_meters, MyApp.Cldr, locale: "en-US", usage: :road
{:ok, [:mile], []}
iex> Cldr.Unit.Preference.preferred_units meter, MyApp.Cldr, locale: "en-AU", usage: :road
{:ok, [:meter], [round_nearest: 1]}
iex> Cldr.Unit.Preference.preferred_units many_meters, MyApp.Cldr, locale: "en-AU", usage: :road
{:ok, [:kilometer], []}
## Notes
One common pattern is to convert a given unit into the unit
appropriate for a given locale and usage. This can be
accomplished with a combination of `Cldr.Unit.Preference.preferred_units/3`
and `Cldr.Unit.decompose/2`. For example:
iex> meter = Cldr.Unit.new!(:meter, 1)
iex> preferred_units = Cldr.Unit.Preference.preferred_units(meter,
...> MyApp.Cldr, locale: "en-US", usage: :person)
iex> with {:ok, preferred_units, _} <- preferred_units do
...> Cldr.Unit.decompose(meter, preferred_units)
...> end
[Cldr.Unit.new!(:inch, "39.37007874015748031496062992")]
"""
@spec preferred_units(Cldr.Unit.t(), Cldr.backend() | Keyword.t(), Keyword.t() | Options.t()) ::
{:ok, [atom(), ...], Keyword.t()} | {:error, {module, binary}}
def preferred_units(unit, backend, options \\ [])
def preferred_units(%Unit{} = unit, options, []) when is_list(options) do
with {:ok, options} <- validate_preference_options(options) do
preferred_units(unit, options.backend, options)
end
end
def preferred_units(%Unit{} = unit, backend, options) when is_list(options) do
options = Keyword.put_new(options, :usage, unit.usage)
with {:ok, options} <- validate_preference_options(backend, options) do
preferred_units(unit, backend, options)
end
end
def preferred_units(%Unit{} = unit, _backend, %Options{} = options) do
%{usage: usage, territory: territory} = options
{:ok, territory_chain} = Cldr.territory_chain(territory)
{:ok, category} = unit_preference_category(unit)
{:ok, base_unit} = Conversion.convert_to_base_unit(unit)
with {:ok, usage} <- validate_usage(category, usage) do
usage = usage_chain(usage)
geq = Unit.value(base_unit) |> Cldr.Unit.to_float()
preferred_units(category, usage, territory_chain, geq)
end
end
@doc false
@spec unit_preference_category(Unit.t() | String.t() | atom()) ::
{:ok, Unit.category()} | {:error, {module(), String.t()}}
def unit_preference_category(unit) do
with {:ok, _unit, conversion} <- Unit.validate_unit(unit) do
unit_preference_category(unit, conversion)
end
end
@doc false
def unit_preference_category(unit, conversion) do
with {:ok, base_unit} <- Unit.BaseUnit.canonical_base_unit(conversion),
{:ok, category} <- Map.fetch(Unit.base_unit_category_map(), Kernel.to_string(base_unit)) do
{:ok, category}
else
:error -> {:error, Unit.unknown_category_error(unit)}
other -> other
end
end
@doc """
Returns a list of the preferred units for a given
unit, locale, territory and use case.
The units used to represent length, volume and so on
depend on a given territory, measurement system and usage.
For example, in the US, people height is most commonly
referred to in `inches`, or `feet and inches`.
In most of the rest of the world it is `centimeters`.
## Arguments
* `unit` is any unit returned by `Cldr.Unit.new/2`.
* `backend` is any Cldr backend module. That is, any module
that includes `use Cldr`. The default is `Cldr.default_backend!/0`
* `options` is a keyword list of options or a
`t:Cldr.Unit.Conversion.Options` struct. The default
is `[]`.
## Options
* `:locale` is any valid locale name returned by `Cldr.known_locale_names/0`
or a `Cldr.LanguageTag` struct. The default is `backend.get_locale/0`
* `:territory` is any valid territory code returned by
`Cldr.known_territories/0`. The default is the territory defined
as part of the `:locale`. The option `:territory` has a precedence
over the territory in a locale.
* `:usage` is the way in which the unit is intended
to be used. The available `usage` varyies according
to the unit category. See `Cldr.Unit.unit_category_usage/0`.
## Returns
* `unit_list` or
* raises an exception
## Note
This function, unlike `Cldr.Unit.preferred_units/3` does not
return any available formatting hints.
## Examples
iex> meter = Cldr.Unit.new!(:meter, 1)
iex> Cldr.Unit.Preference.preferred_units! meter, MyApp.Cldr, locale: "en-US", usage: :person_height
[:foot, :inch]
iex> Cldr.Unit.Preference.preferred_units! meter, MyApp.Cldr, locale: "en-US", usage: :person
[:inch]
iex> Cldr.Unit.Preference.preferred_units! meter, MyApp.Cldr, locale: "en-AU", usage: :person
[:centimeter]
iex> Cldr.Unit.Preference.preferred_units! meter, MyApp.Cldr, locale: "en-US", usage: :road
[:foot]
iex> Cldr.Unit.Preference.preferred_units! meter, MyApp.Cldr, locale: "en-AU", usage: :road
[:meter]
"""
@spec preferred_units!(Cldr.Unit.t(), Cldr.backend() | Keyword.t(), Keyword.t() | Options.t()) ::
[atom(), ...] | no_return()
def preferred_units!(unit, backend, options \\ []) do
case preferred_units(unit, backend, options) do
{:ok, preferred_units, _} -> preferred_units
{:error, {exception, reason}} -> raise exception, reason
end
end
defp usage_chain(usage) when is_atom(usage) do
usage_chain()
|> Map.fetch!(usage)
end
# TR35 says that for a given usage, if it
# can't be found, split it at the last
# "_", take the head of the split and try
# again. Repeat until the usage is found or
# there is nothing more to try.
#
# The following precomputes these "usage chains"
# by taking each known usage and breaking it
# down as required by TR36.
@usage_chain Cldr.Unit.unit_category_usage()
|> Enum.map(fn {_category, usage} ->
Enum.map(usage, fn use ->
chain =
use
|> Atom.to_string()
|> String.split("_")
|> Cldr.Enum.combine_list()
|> Enum.map(&String.to_atom/1)
|> List.insert_at(0, :default)
|> Enum.reverse()
{use, chain}
end)
end)
|> List.flatten()
|> Map.new()
defp usage_chain do
@usage_chain
end
defp validate_preference_options(backend, options) when is_list(options) do
options
|> Keyword.put(:backend, backend)
|> validate_preference_options
end
defp validate_preference_options(options) when is_list(options) do
backend = Keyword.get_lazy(options, :backend, &Cldr.Unit.default_backend/0)
locale = Keyword.get_lazy(options, :locale, &backend.get_locale/0)
usage = Keyword.get(options, :usage, :default)
with {:ok, locale} <- backend.validate_locale(locale),
territory =
Keyword.get_lazy(options, :territory, fn ->
Cldr.Locale.territory_from_locale(locale)
end),
{:ok, territory} <- Cldr.validate_territory(territory) do
options = [locale: locale, territory: territory, usage: usage, backend: backend]
{:ok, struct(Options, options)}
end
end
def validate_usage(category, usage) do
if get_in(Unit.unit_preferences(), [category, usage]) do
{:ok, usage}
else
{:error, unknown_usage_error(category, usage)}
end
end
for {category, usages} <- Unit.unit_preferences() do
for {usage, preferences} <- usages do
for preference <- preferences do
%{geq: geq, regions: regions, units: units, skeleton: skeleton} = preference
if geq == 0 do
def preferred_units(unquote(category), unquote(usage), region, _value)
when is_atom(region) and region in unquote(regions) do
# debug(unquote(category), unquote(usage), region, value, 0)
{:ok, unquote(units), unquote(skeleton)}
end
else
def preferred_units(unquote(category), unquote(usage), region, value)
when is_atom(region) and region in unquote(regions) and value >= unquote(geq) do
# debug(unquote(category), unquote(usage), region, value, unquote(geq))
{:ok, unquote(units), unquote(skeleton)}
end
end
end
end
end
# First we process the potential usage we were offered
def preferred_units(category, [usage], region, value) do
# debug(category, usage, region, value)
preferred_units(category, usage, region, value)
end
def preferred_units(category, [usage | other_usage], region, value) do
# debug(category, usage, region, value)
case preferred_units(category, usage, region, value) do
{:ok, units, skeleton} -> {:ok, units, skeleton}
_other -> preferred_units(category, other_usage, region, value)
end
end
# Second we walk the territory chain with the usage
# we were provided
def preferred_units(category, usage, [region], value) do
# debug(category, usage, region, value)
preferred_units(category, usage, region, value)
end
def preferred_units(category, usage, [region | other_regions], value) do
# debug(category, usage, region, value)
case preferred_units(category, usage, region, value) do
{:ok, units, skeleton} -> {:ok, units, skeleton}
_other -> preferred_units(category, usage, other_regions, value)
end
end
# If we get here then try with the default case
# Which should basically always work
# def preferred_units(category, usage, region, value) when usage != :default do
# preferred_units(category, :default, region, value)
# end
# And it we get here it's game over
def preferred_units(category, usage, region, value) do
{:error, unknown_preferences_error(category, usage, region, value)}
end
@doc false
def debug(category, usage, region, value) do
IO.inspect(
"""
Category: #{inspect(category)} with usage #{inspect(usage)} for
region #{inspect(region)} and value #{inspect(value)}
"""
|> String.replace("\n", " ")
)
end
def debug(category, usage, region, value, geq) do
IO.inspect(
"""
Preference: #{inspect(category)} with usage #{inspect(usage)} for
region #{inspect(region)} and value #{inspect(value)} with >= #{inspect(geq)}
"""
|> String.replace("\n", " ")
)
end
def unknown_preferences_error(category, usage, regions, value) do
{
Cldr.Unit.UnknownUnitPreferenceError,
"No preferences found for #{inspect(category)} " <>
"with usage #{inspect(usage)} " <>
"for region #{inspect(regions)} and " <>
"value #{inspect(value)}"
}
end
def unknown_usage_error(category, usage) do
{
Cldr.Unit.UnknownUsageError,
"The unit category #{inspect(category)} does not define a usage #{inspect(usage)}"
}
end
end