New Library for Rendering Colors in the Terminal

65 views
Skip to first unread message

Ryan Levick

unread,
Apr 13, 2014, 4:02:16 PM4/13/14
to elixir-l...@googlegroups.com
Hey all,

I just completed the first working version of a small library named Palette (https://github.com/rylev/palette) which allows you to easily render colors in the terminal. 

As it's my first library in Elixir, any feedback on style would be greatly appreciated. 

Thanks!

Alexei Sholik

unread,
Apr 14, 2014, 4:31:46 PM4/14/14
to elixir-l...@googlegroups.com
This looks nice, Ryan.

I've got a little nitpick regarding the API. Take this example

    iex> my_string = "This is my string."
    "This is my string."
    iex> my_string |> Palette.bg("#F60045") |> Palette.bright |> Palette.fg("#9967FD")
    "\e[38;5;99m\e[1m\e[48;5;197mThis is my string.\e[0m\e[0m\e[0m"

IMO this is not a functional style. It looks like it's composable, but in reality it's rather awkward to customize.

If I want to write a custom function that lets me set either of the three–bg color, fg color, and brightness–I'll have to come up with something like this:

    def colorful(str, opts) do
      if bg = opts[:bg], do: str = Palette.bg(str, bg)
      if fg = opts[:fg], do: str = Palette.fg(str, fg)
      if bright = opts[:bright], do: str = Palette.bright(str)
      str
    end

With this example you should be able to see where my "non-functional" argument comes from.

If Palette had initially been written with data-driven approach in mind, its API would be more like this:

    Palette.colorize(my_string, [flags: [:bright], bg: "#F60045", fg: "#9967FD"])

Then my custom function would look like this:

    def colorful(str, opts) do
      {bright?, opts} = Dict.pop(opts, :bright)
      if bright? do
        opts = opts ++ [flags: [:bright]]
      end
      Palette.colorize(str, opts)
    end

This new function is now free to do any preliminary processing of the options it wants and then call a single function from Palette to actually colorize the string. In other words, with this API style your library won't be imposing itself unto user code's logic that involves deciding what and how to colorize.

I hope this helps. Cheers.


--
You received this message because you are subscribed to the Google Groups "elixir-lang-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-ta...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Best regards
Alexei Sholik
Reply all
Reply to author
Forward
0 new messages