Created
August 26, 2013 22:22
-
-
Save ToJans/6347376 to your computer and use it in GitHub Desktop.
Freakenstein code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Meetup do | |
defmacrop dayname_parts, do: %W(mon tues wednes thurs fri satur sun) | |
defmacrop dayname(range_id, dayname_part) do | |
if (range_id == :teenth) do | |
dayname_part <> "teenth" | |
else | |
bin = atom_to_binary(range_id) | |
bin <> "_" <> dayname_part <> "day" | |
end | |
|> binary_to_atom | |
end | |
defp range(:teenth,_month,_year), do: 13..19 | |
defp range(:first ,_month,_year), do: 1..7 | |
defp range(:second,_month,_year), do: 8..14 | |
defp range(:third ,_month,_year), do: 15..21 | |
defp range(:forth ,_month,_year), do: 22..28 | |
defp range(:last , month, year), do: last_7_days(month,year) | |
defp last_7_days(month,year) do | |
last_day = :calendar.last_day_of_the_month(year, month) | |
last_day-6..last_day | |
end | |
defp day_of_the_week(range_id,day_of_the_week,month,year) do | |
range(range_id,month,year) | |
|> Enum.map(&({year,month,&1})) | |
|> Enum.filter(&(:calendar.day_of_the_week(&1)==day_of_the_week)) | |
|> Enum.first() | |
end | |
defmacrop def_dates_for_range(range_id) do | |
dayname_parts() | |
|> Enum.with_index() | |
|> Enum.map(fn {index,dayname_part} -> {index+1,dayname(range_id,dayname_part)} end) | |
|> Enum.map(fn {day_index, function_name}-> | |
quote do | |
def unquote(function_name)(month, year) do | |
day_of_the_week(range_id, unquote(day_index), month, year) | |
end | |
end | |
end) | |
end | |
def_dates_for_range(:teenth) | |
def_dates_for_range(:first) | |
def_dates_for_range(:second) | |
def_dates_for_range(:third) | |
def_dates_for_range(:forth) | |
def_dates_for_range(:last) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment