Elixir &引用;案例“做”;有一些长生不老药的条件

Elixir &引用;案例“做”;有一些长生不老药的条件,elixir,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 cust = Repo.get(Customer, id) mon

我想这样做:

  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
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

如果客户不存在,或者他们存在但未激活,并且他们的注册日期超过1个月-->请采取措施1。如果存在客户-->请执行某些操作2。我如何通过“case”对其进行编码,可能吗?

假设您有一个
Customer
结构,这就是
Repo.get(Customer,id)
将返回的内容(或
nil
)。你要的是这样的:

  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
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
这是一种不自然的感觉,因为您正在以相同的方式处理
nil
和非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
如果您真正想要的是测试一组复杂的条件,那么您可能需要一组嵌套的
If
s或
cond

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

提供了更多关于这种区别的示例和解释。

case
用于模式匹配(+guard),而不是您正在做的。为什么不使用
cond