Skip to content

Instantly share code, notes, and snippets.

@KieranP
Last active June 18, 2019 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KieranP/93c06c031fb96c9e34b95bbf0e5f8a23 to your computer and use it in GitHub Desktop.
Save KieranP/93c06c031fb96c9e34b95bbf0e5f8a23 to your computer and use it in GitHub Desktop.
Simple Rails Component System
# frozen_string_literal: true
class ApplicationComponent
include ActiveModel::Validations
include ActionView::Helpers::TagHelper
attr_accessor :content
def initialize(*args)
end
end
# 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
# 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
<%= 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