简体   繁体   中英

switching between hosts on the basis of date elixir

we have three type of hosts on which we are running a file system and saving jpegs. at very start we had a host as localhost:8888 it was before {{2017, 10, 31}, {23, 59, 59}} and we start dealing with 2 hosts new one was localhost:8889 .

  def point_to_seaweed(request_date) do
    oct_date =
      {{2017, 10, 31}, {23, 59, 59}}
      |> Calendar.DateTime.from_erl!("UTC")

    case Calendar.DateTime.diff(request_date, oct_date) do
      {:ok, _, _, :after} -> "localhost:8889"
      _ -> "localhost:8888"
    end
  end

whenever the request date is greater than {{2017, 10, 31}, {23, 59, 59}} we switch to new host. but now on {{2018, 10, 31}, {23, 59, 59}} we are changing to a new host but need to handle all 2 old hosts as well.

I tried this.

  def point_to_seaweed(request_date) do
    oct_date =
      {{2017, 10, 31}, {23, 59, 59}}
      |> Calendar.DateTime.from_erl!("UTC")

    case Calendar.DateTime.diff(request_date, oct_date) do
      {:ok, secs, _, :after} ->
        case secs > 31536000 do
          true -> "localhost:8890"
          false -> "localhost:8889"
        end
      _ -> "localhost:8888"
    end
  end

Is this a better approach to do this? 31536000 is for a year. this can be done with another approach?

I'd use the built in NaiveDateTime module for this and define a helper function to check if an Erlang date is before another Erlang date:

def before?(date1, date2) do
  NaiveDateTime.diff(NaiveDateTime.from_erl!(date1), NaiveDateTime.from_erl!(date2)) < 0
end

and then use cond :

def point_to_seaweed(request_date) do
  port = cond do
    before?(request_date, {{2017, 10, 31}, {23, 59, 59}}) -> 8888
    before?(request_date, {{2018, 10, 31}, {23, 59, 59}}) -> 8889
    true -> 8890
  end
  "localhost:#{port}"
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM