Elixir

时间:2016-12-31 04:04:38

标签: elixir

我想做这样的事情:

  cust = Repo.get(Customer, id)
  case cust do
    nil ??? or not nil but is_activated == false && registration_date is over 1 month ago?? -> # something1 .....

    custm1 -> # something2
  end

如果客户不存在或存在但未激活,则其注册日期超过1个月前 - >做某事1。如果客户存在 - >做点什么2。如何通过“case”对其进行编码,是否可能?

1 个答案:

答案 0 :(得分:1)

我们假设您有一个Customer结构,而Repo.get(Customer, id)将返回(或nil)。您要求的内容如下:

cust = Repo.get(Customer, id)
month_ago = (DateTime.utc_now |> DateTime.to_unix) - 60*60*24*30  # approx. 1 month before now
case cust do
  nil ->
    something1()
  %Customer{is_activated: false, registration_date: regged} when month_ago > regged ->
    something1()
  _ ->
    something2()
end

这是一种不自然的构建IMO的原因是你以相同的方式处理nil和非零数据的子集。通常情况下,您正在使用case因为您正在使用您匹配的数据某事。像:

case cust do
  %Customer{is_activated: false, registration_date: regged, email: email} when week_ago > regged ->
    send_reminder(email, regged)
  %Customer{is_activated: false, registration_date: regged} when month_ago > regged ->
    delete_account(cust)
  %Customer{is_activated: true, sent_thanks: false, email: email} ->
    send_thanks(email)
    Repo.update(Customer, %{cust | sent_thanks: true})
end

如果您真正想要的是测试一系列复杂条件,您可能需要一组嵌套ifcond

cust = Repo.get(Customer, id)
cond do
  cust == nil ->
    something1()
  !cust.is_activated && is_old(cust) ->
    something1()
  true ->
    something2()
end

The Elixir documentation提供了有关这种区别的更多示例和解释。

相关问题