diff --git a/app/components/label_component.rb b/app/components/label_component.rb new file mode 100644 index 000000000..6626399e1 --- /dev/null +++ b/app/components/label_component.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +class LabelComponent < ApplicationComponent + TYPES = %i[default primary success info warning danger] + + erb_template <<~ERB + + <%= content %> + + ERB + + def initialize(text = nil, type: :default) + @text = text + + @type = type.to_sym + raise ArgumentError, "'#{@type.inspect}' is not a valid type" unless TYPES.include?(@type) + end + + def css_classes + "label label-#{@type}" + end + + def content + super || @text + end +end diff --git a/spec/components/label_component_spec.rb b/spec/components/label_component_spec.rb new file mode 100644 index 000000000..3410cee29 --- /dev/null +++ b/spec/components/label_component_spec.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +require "rails_helper" + +RSpec.describe LabelComponent, type: :component do + context "with html content" do + let(:component) { described_class.new(text, **kwargs) } + let(:rendered_component) { render_inline(component, &block) } + let(:text) { "Text as argument" } + let(:kwargs) { {} } + let(:block) {} + + context "with text" do + it { expect(rendered_component.to_html).to have_tag("span.label.label-default", text: /Text as argument/) } + end + + context "with text as block" do + let(:block) { proc { "Text as block" } } + + it { expect(rendered_component.to_html).to have_tag("span.label.label-default", text: /Text as block/) } + end + + context "with type" do + let(:kwargs) { { type: :success } } + + it { expect(rendered_component.to_html).to have_tag("span.label.label-success", text: /Text as argument/) } + end + end +end