Last active
June 18, 2019 11:45
-
-
Save KieranP/93c06c031fb96c9e34b95bbf0e5f8a23 to your computer and use it in GitHub Desktop.
Simple Rails Component System
This file contains 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
# frozen_string_literal: true | |
class ApplicationComponent | |
include ActiveModel::Validations | |
include ActionView::Helpers::TagHelper | |
attr_accessor :content | |
def initialize(*args) | |
end | |
end |
This file contains 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
# frozen_string_literal: true | |
class TestComponent < ApplicationComponent | |
attr_reader :id, :text | |
validates :id, presence: true | |
def initialize(id:, text: nil) | |
@id = id | |
@text = text | |
end | |
def render | |
content_tag(:h1, content || text, id: @id) | |
end | |
end |
This file contains 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
# frozen_string_literal: true | |
module ComponentsHelper | |
def component(klass, args = {}, &block) | |
klass = "#{klass.to_s.classify}Component".constantize | |
instance = klass.new(args) | |
instance.content = capture(&block) if block_given? | |
instance.validate! | |
instance.render | |
end | |
end |
This file contains 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
<%= component(:test, id: 'test123', text: 'Hello World!') %> | |
<%= component(:test, id: 'test123') do %> | |
Hello World! | |
<% end %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment