Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change the get function to let user find country by name #56

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

pedromcorreia
Copy link

Description

Change the function get to use guard, this allows users to find countries by name and returning only one record.

lib/countries.ex Outdated
"""

def get(country_code) do
[country] = filter_by(:alpha2, country_code)
def get(attrs) when bit_size(attrs) == 16 do
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you rename this function to get_by_alpha2

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@steffenix sure!


case length(country) do
0 ->
[]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The returned value is not consistent and breaking the current API.

We could update it to adopt the following pattern:

{:ok, country}
:not_found pattern

And also add a get! function that breaks if country does not exist.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure! I will do ASAP

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed, you can change the whole case in this way:

case country do
  [] -> []
  [country_info | _] -> country_info
end

iex> name
"Poland"

"""

def get(country_code) do
[country] = filter_by(:alpha2, country_code)
def get_by_alpha2(attrs) when bit_size(attrs) == 16 do

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

because you're using a strong match, you should add a ! indicating that if the country isn't found it's going to fail.

def get_by_alpha2!(<<_ :: binary-size(16)>> = attrs) do
  hd(filter_by(:alpha2, attrs))
end

def get_by_alpha2(<<_ :: binary-size(16)>> = attrs) do
  case filter_by(:alpha2, attrs) do
    [] -> nil
    [country] -> country
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants