Skip to content

Instantly share code, notes, and snippets.

@scottwater
Created March 14, 2023 00:58
Show Gist options
  • Save scottwater/da78cdf4d8bf5031b8bc3fc8d9d248b9 to your computer and use it in GitHub Desktop.
Save scottwater/da78cdf4d8bf5031b8bc3fc8d9d248b9 to your computer and use it in GitHub Desktop.
Quick Ruby implementation of https://www.npmjs.com/package/clsx
module Clsx
def clsx(*args)
process_args = args.map do |arg|
if arg.is_a?(Array)
clsx(*arg)
elsif arg.is_a?(Hash)
arg.map do |key, value|
key if value
end
else
arg
end
end
process_args
.flatten
.compact
.keep_if { |arg| arg && arg.to_s.strip != "" }
.join(" ")
end
end
require "minitest/autorun"
require "./clsx"
class TestClsx < Minitest::Test
include Clsx
def test_a_simple_list
assert_equal "foo bar baz", clsx("foo", "bar", "baz")
end
def test_a_hash_of_items
assert_equal "foo baz", clsx("foo" => true, "bar" => false, "baz" => true)
assert_equal "foo baz", clsx(foo: true, bar: false, baz: true)
end
def test_an_array
assert_equal "foo bar baz", clsx(["foo", "bar", "baz"])
end
def test_an_array_with_falsey_things
assert_equal "foo bar baz", clsx(["foo", nil, false, "bar", "", "baz"])
end
def test_a_variadic_array_of_trash
# The javascript version evaluates 0 as falsey
assert_equal "foo bar baz hello there", clsx(["foo"], ["", false, "bar"], [["baz", [["hello"], "there"]]])
end
def test_the_kitchen_sync
assert_equal "foo bar hello world cya", clsx("foo", [1 && "bar", {baz: false, bat: nil}, ["hello", ["world"]]], "cya")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment