From 170e66c3f8269191b059e35d5a0a64efc38fc135 Mon Sep 17 00:00:00 2001 From: Seth Horsley Date: Sun, 3 Mar 2024 01:03:10 +0100 Subject: [PATCH] add clsx class, railstie and tests --- CHANGELOG.md | 39 +++++++++++++++++++++ CODE_OF_CONDUCT.md | 84 --------------------------------------------- Gemfile.lock | 22 ++++++++++++ README.md | 57 ++++++++++++++++++++++++------ clsx.gemspec | 12 +++---- lib/clsx.rb | 21 +++++++++++- lib/clsx/railtie.rb | 18 ++++++++++ test/test_clsx.rb | 26 +++++++++++--- 8 files changed, 171 insertions(+), 108 deletions(-) delete mode 100644 CODE_OF_CONDUCT.md create mode 100644 Gemfile.lock create mode 100644 lib/clsx/railtie.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index d56512d..77b000d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,3 +3,42 @@ ## [0.1.0] - 2024-03-02 - Initial release + +These examples should be working + +Strings (variadic) +```ruby + clsx("foo", true && "bar", "baz") + #=> "foo bar baz" +``` + +Objects +```ruby + clsx({ foo:true, bar:false, baz:is_true? }) + #=> "foo baz" +``` + +Objects (variadic) +```ruby + clsx({ foo:true }, { bar:false }, null, { "--foobar":"hello" }) + #=> "foo --foobar" +``` + +Arrays +```ruby + clsx(["foo", 0, false, "bar"]) + #=> "foo bar" +``` + +Arrays (variadic) +```ruby + clsx(["foo"], ["", 0, false, "bar"], [["baz", [["hello"], "there"]]]) + #=> "foo bar baz hello there" +``` + +Kitchen sink (with nesting) +```ruby + clsx("foo", [1 && "bar", { baz:false, bat:null }, ["hello", ["world"]]], "cya") + #=> "foo bar hello world cya" +``` + diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index 30a70c9..0000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,84 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. - -## Our Standards - -Examples of behavior that contributes to a positive environment for our community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience -* Focusing on what is best not just for us as individuals, but for the overall community - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or - advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email - address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at isethi@me.com. All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series of actions. - -**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within the community. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, -available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. - -Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see the FAQ at -https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..897773a --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,22 @@ +PATH + remote: . + specs: + clsx (0.1.0) + +GEM + remote: https://rubygems.org/ + specs: + minitest (5.22.2) + rake (13.1.0) + +PLATFORMS + arm64-darwin-23 + ruby + +DEPENDENCIES + clsx! + minitest (~> 5.16) + rake (~> 13.0) + +BUNDLED WITH + 2.5.3 diff --git a/README.md b/README.md index 1b188db..85a03db 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,59 @@ # Clsx +## A gem for constructing HTML class strings conditionally -TODO: Delete this and the text below, and describe your gem - -Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/clsx`. To experiment with that code, run `bin/console` for an interactive prompt. +Ruby utility for constructing HTML class strings conditionally with the provided syntax, you can define a module named Clsx that includes a method to handle each case: strings, objects (hashes), arrays, and a combination of these with nested structures. This method will recursively process each argument, filter out falsy values, and concatenate the truthy values into a single string. ## Installation -TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org. - Install the gem and add to the application's Gemfile by executing: - $ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG - -If bundler is not being used to manage dependencies, install the gem by executing: + $ bundle add "clsx" - $ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG ## Usage +Strings (variadic) +```ruby + clsx("foo", true && "bar", "baz") + #=> "foo bar baz" +``` + +Objects +```ruby + clsx({ foo:true, bar:false, baz:is_true? }) + #=> "foo baz" +``` + +Objects (variadic) +```ruby + clsx({ foo:true }, { bar:false }, null, { "--foobar":"hello" }) + #=> "foo --foobar" +``` + +Arrays +```ruby + clsx(["foo", 0, false, "bar"]) + #=> "foo bar" +``` + +Arrays (variadic) +```ruby + clsx(["foo"], ["", 0, false, "bar"], [["baz", [["hello"], "there"]]]) + #=> "foo bar baz hello there" +``` + +Kitchen sink (with nesting) +```ruby + clsx("foo", [1 && "bar", { baz:false, bat:null }, ["hello", ["world"]]], "cya") + #=> "foo bar hello world cya" +``` + +You can also use clsx in rails views like this: +```ruby +
"> + +
+``` -TODO: Write usage instructions here ## Development @@ -28,7 +63,7 @@ To install this gem onto your local machine, run `bundle exec rake install`. To ## Contributing -Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/clsx. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/clsx/blob/main/CODE_OF_CONDUCT.md). +Bug reports and pull requests are welcome. Just fork this repo make the changes you want and submit a pull request back to this repo :) ## License diff --git a/clsx.gemspec b/clsx.gemspec index 60de7e0..5e3ff54 100644 --- a/clsx.gemspec +++ b/clsx.gemspec @@ -8,17 +8,15 @@ Gem::Specification.new do |spec| spec.authors = ["Seth Horsley"] spec.email = ["isethi@me.com"] - spec.summary = "TODO: Write a short summary, because RubyGems requires one." - spec.description = "TODO: Write a longer description or delete this line." - spec.homepage = "TODO: Put your gem's website or public repo URL here." + spec.summary = "A gem for constructing HTML class strings conditionally" + spec.description = "Ruby utility for constructing HTML class strings conditionally with the provided syntax, you can define a module named Clsx that includes a method to handle each case: strings, objects (hashes), arrays, and a combination of these with nested structures. This method will recursively process each argument, filter out falsy values, and concatenate the truthy values into a single string." + spec.homepage = "https://github.com/iseth/ruby-clsx" spec.license = "MIT" spec.required_ruby_version = ">= 2.6.0" - spec.metadata["allowed_push_host"] = "TODO: Set to your gem server 'https://example.com'" - spec.metadata["homepage_uri"] = spec.homepage - spec.metadata["source_code_uri"] = "TODO: Put your gem's public repo URL here." - spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here." + spec.metadata["source_code_uri"] = spec.homepage + spec.metadata["changelog_uri"] = "#{spec.homepage}/blob/main/CHANGELOG.md" # Specify which files should be added to the gem when it is released. # The `git ls-files -z` loads the files in the RubyGem that have been added into git. diff --git a/lib/clsx.rb b/lib/clsx.rb index 5d3119c..27b4146 100644 --- a/lib/clsx.rb +++ b/lib/clsx.rb @@ -1,8 +1,27 @@ # frozen_string_literal: true require_relative "clsx/version" +require "clsx/railtie" if defined?(Rails) module Clsx class Error < StandardError; end - # Your code goes here... + + def self.clsx(*args) + args.flat_map { |arg| parse(arg) }.compact.join(" ") + end + + private + + def self.parse(arg) + case arg + when String + arg unless arg.empty? + when Hash + arg.map { |k, v| k if v }.compact + when Array + arg.flat_map { |a| parse(a) } + else + nil + end + end end diff --git a/lib/clsx/railtie.rb b/lib/clsx/railtie.rb new file mode 100644 index 0000000..53955d5 --- /dev/null +++ b/lib/clsx/railtie.rb @@ -0,0 +1,18 @@ +require "clsx" +require "rails" + +module Clsx + class Railtie < Rails::Railtie + initializer "clsx.action_view" do + ActiveSupport.on_load :action_view do + ActionView::Base.send :include, Helper + end + end + end + + module Helper + def clsx(*args) + Clsx.clsx(*args) + end + end +end diff --git a/test/test_clsx.rb b/test/test_clsx.rb index d035100..04b060e 100644 --- a/test/test_clsx.rb +++ b/test/test_clsx.rb @@ -2,12 +2,28 @@ require "test_helper" -class TestClsx < Minitest::Test - def test_that_it_has_a_version_number - refute_nil ::Clsx::VERSION +class ClsxTest < Minitest::Test + def test_strings + assert_equal "foo bar baz", Clsx.clsx("foo", true && "bar", "baz") end - def test_it_does_something_useful - assert false + def test_objects + assert_equal "foo baz", Clsx.clsx({ foo: true, bar: false, baz: true }) + end + + def test_objects_variadic + assert_equal "foo --foobar", Clsx.clsx({ foo: true }, { bar: false }, nil, { "--foobar" => "hello" }) + end + + def test_arrays + assert_equal "foo bar", Clsx.clsx(["foo", 0, false, "bar"]) + end + + def test_arrays_variadic + assert_equal "foo bar baz hello there", Clsx.clsx(["foo"], ["", 0, false, "bar"], [["baz", [["hello"], "there"]]]) + end + + def test_kitchen_sink + assert_equal "foo bar hello world cya", Clsx.clsx("foo", [1 && "bar", { baz: false, bat: nil }, ["hello", ["world"]]], "cya") end end