evc_rails 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 703fa9100249c54f63c8e567d5d8cde7b3908b6777dfb555f2d2e72a949d4daa
4
+ data.tar.gz: f175e943945bc31a3d4da2be22290e7f843546c0bb6dc0426ad22d1433472fe6
5
+ SHA512:
6
+ metadata.gz: dcd338b43347af1e971b99d50298d425da85193856f0362a4b7358ad19fbe3b059b5808b6c7ba0bf0f53944244d2bf2a5a7fd8e2283d6d13912f138c683d6b36
7
+ data.tar.gz: c902814035da4a002d4006df67b07e8e71256084a9bc3585a256d1b14281eb5bee41c4941b0d7956f4c6d87330bf72cfdfb5edef2b03321a94e99c676af2e331
data/.rubocop.yml ADDED
@@ -0,0 +1,8 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.1
3
+
4
+ Style/StringLiterals:
5
+ EnforcedStyle: double_quotes
6
+
7
+ Style/StringLiteralsInInterpolation:
8
+ EnforcedStyle: double_quotes
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 scttymn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,153 @@
1
+ # EvcRails
2
+
3
+ EvcRails is a Rails gem that introduces a custom .evc template handler, allowing you to define your Rails View Components using a concise, HTML-like PascalCase tag syntax, reminiscent of React or other modern component-based UI frameworks. This gem seamlessly integrates your custom tags with Rails View Components, enabling a more declarative and readable approach to building UIs in Rails.
4
+
5
+ ## Features
6
+
7
+ PascalCase Component Tags: Define and use your View Components with <MyComponent> or self-closing <MyComponent /> syntax directly in your .evc templates.
8
+
9
+ Attribute Handling: Pass attributes to your components using standard HTML-like key="value", key='value', or Ruby expressions key={@variable}.
10
+
11
+ Content Blocks: Components can accept content blocks (<MyComponent>content</MyComponent>) which are passed to the View Component via a block.
12
+
13
+ Automatic Component Resolution: Automatically appends "Component" to your tag name if it's not already present (e.g., <Button> resolves to ButtonComponent).
14
+
15
+ Performance Optimized: Includes in-memory caching of compiled templates and memoization of component class lookups for efficient rendering in production.
16
+
17
+ ## Installation
18
+
19
+ Add this line to your application's Gemfile:
20
+
21
+ ```
22
+ gem 'evc_rails'
23
+ ```
24
+
25
+ And then execute:
26
+
27
+ ```
28
+ bundle install
29
+ ```
30
+
31
+ Or install it yourself as:
32
+
33
+ ```
34
+ gem install evc_rails
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ 1. Create a View Component
40
+ First, ensure you have a Rails View Component. For example, create app/components/my_component_component.rb:
41
+
42
+ ```ruby
43
+ # app/components/my_component_component.rb
44
+ class MyComponentComponent < ViewComponent::Base
45
+ def initialize(title:)
46
+ @title = title
47
+ end
48
+
49
+ def call
50
+ tag.div(class: "my-component") do
51
+ concat tag.h2(@title)
52
+ concat content # This renders the block content
53
+ end
54
+ end
55
+ end
56
+ ```
57
+
58
+ And its associated template app/components/my_component_component.html.erb (if you're using separate templates):
59
+
60
+ ```html
61
+ <!-- app/components/my_component_component.html.erb -->
62
+ <div class="my-component">
63
+ <h2><%= @title %></h2>
64
+ <%= content %>
65
+ </div>
66
+ ```
67
+
68
+ 2. Create an .evc Template
69
+ Now, create a template file with the .evc extension. For instance, app/views/pages/home.html.evc:
70
+
71
+ ```html
72
+ <!-- app/views/pages/home.html.evc -->
73
+ <h1>Welcome to My App</h1>
74
+
75
+ <MyComponent title="Hello World">
76
+ <p>This is some content passed to the component.</p>
77
+ <button text="Click Me" />
78
+ </MyComponent>
79
+
80
+ <%# A more concise way to render your DoughnutChartComponent %>
81
+ <DoughnutChart rings="{@progress_data}" />
82
+
83
+ <%# You can still use standard ERB within .evc files %>
84
+ <p><%= link_to "Go somewhere", some_path %></p>
85
+ ```
86
+
87
+ 3. Ensure Components are Autoloaded
88
+ Make sure your app/components directory is eager-loaded in production. In config/application.rb or an initializer:
89
+
90
+ ```ruby
91
+ # config/application.rb
92
+ config.eager_load_paths << Rails.root.join("app/components")
93
+ ```
94
+
95
+ ## How it Works
96
+
97
+ When Rails processes an .evc template, EvcRails intercepts it and performs the following transformations:
98
+
99
+ ```erb
100
+ <MyComponent title="Hello World">... </MyComponent>
101
+ ```
102
+
103
+ becomes:
104
+
105
+ ```ruby
106
+ <%= render MyComponentComponent.new(title: "Hello World") do %>
107
+ ... (processed content) ...
108
+ <% end %>
109
+ ```
110
+
111
+ ```erb
112
+ <%=<button text="Click Me" />
113
+ ```
114
+
115
+ becomes:
116
+
117
+ ```ruby
118
+ <%= render ButtonComponent.new(text: "Click Me") %>
119
+ ```
120
+
121
+ ```erb
122
+ <DoughnutChart rings={@progress_data} />
123
+ ```
124
+
125
+ becomes:
126
+
127
+ ```ruby
128
+ <%= render DoughnutChartComponent.new(rings: @progress_data) %>
129
+ ```
130
+
131
+ `attr={@variable}` becomes `attr: @variable` in the new() call.
132
+
133
+ The transformed content is then passed to the standard ERB handler for final rendering.
134
+
135
+ ## Configuration
136
+
137
+ Currently, EvcRails requires no specific configuration. Future versions might include options for:
138
+
139
+ Customizing the component suffix (e.g., if you don't want "Component" appended).
140
+
141
+ Defining custom component lookup paths.
142
+
143
+ ## Contributing
144
+
145
+ Bug reports and pull requests are welcome on GitHub at [your-gem-repo-link]. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.
146
+
147
+ ## License
148
+
149
+ The gem is available as open source under the terms of the MIT License
150
+
151
+ ```
152
+
153
+ ```
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rubocop/rake_task"
5
+
6
+ RuboCop::RakeTask.new
7
+
8
+ task default: :rubocop
@@ -0,0 +1,37 @@
1
+ # lib/evc_rails/railtie.rb
2
+ #
3
+ # This file defines a Rails::Railtie, which integrates the evc_rails gem
4
+ # with the Rails framework during its boot process.
5
+
6
+ require "evc_rails/template_handler"
7
+ require "action_view" # Ensure ActionView is loaded for handler registration
8
+
9
+ module EvcRails
10
+ class Railtie < Rails::Railtie
11
+ # Register MIME type and template handler early in the initialization process
12
+ initializer "evc_rails.register_template_handler", before: :load_config_initializers do
13
+ Rails.logger.info "Registering EVC template handler"
14
+ # Register a unique MIME type for .evc templates
15
+ Mime::Type.register "text/evc", :evc, %w[text/evc], %w[evc]
16
+
17
+ # Register the template handler
18
+ handler = EvcRails::TemplateHandlers::Evc.new
19
+ ActionView::Template.register_template_handler(:evc, handler)
20
+
21
+ Rails.logger.info "Template handler registered: #{handler.inspect}"
22
+ end
23
+
24
+ # Finalize configuration after Rails initialization
25
+ config.after_initialize do
26
+ Rails.logger.info "Configuring EVC template handlers"
27
+ # Ensure :evc is prioritized in default handlers
28
+ config.action_view.default_template_handlers ||= []
29
+ config.action_view.default_template_handlers.prepend(:evc)
30
+
31
+ # Verify handler registration (no re-registration)
32
+ unless ActionView::Template.handler_for_extension(:evc)
33
+ Rails.logger.warn "EVC template handler not registered; check initialization"
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,191 @@
1
+ # lib/evc_rails/template_handler.rb
2
+ #
3
+ # This file contains the core logic for the .evc template handler.
4
+ # It's part of the `EvcRails` module to keep it namespaced within the gem.
5
+ # Handles .evc templates, converting PascalCase tags (self-closing <MyComponent attr={value} />
6
+ # or container <MyComponent>content</MyComponent>) into Rails View Component renders.
7
+ # Supports string literals and Ruby expressions as attribute values. The handler is
8
+ # agnostic to specific component APIs, passing content as a block for the component
9
+ # to interpret via yield or custom methods.
10
+
11
+ module EvcRails
12
+ module TemplateHandlers
13
+ class Evc
14
+ # Regex to match opening or self-closing PascalCase component tags with attributes
15
+ TAG_REGEX = %r{<([A-Z][a-zA-Z_]*)([^>]*)/?>}
16
+
17
+ # Regex to match closing PascalCase component tags
18
+ CLOSE_TAG_REGEX = %r{</([A-Z][a-zA-Z_]*)>}
19
+
20
+ # Regex for attributes: Supports string literals (key="value", key='value')
21
+ # and Ruby expressions (key={@variable}).
22
+ # Group 1: Attribute key, Group 2: Double-quoted value, Group 3: Single-quoted value,
23
+ # Group 4: Ruby expression.
24
+ ATTRIBUTE_REGEX = /(\w+)=(?:\"([^"]*)\"|'([^']*)'|\{([^}]*)\})/
25
+
26
+ # Cache for compiled templates to improve performance.
27
+ # @cache will store { identifier: { source: original_source, result: compiled_result } }
28
+ # Note: In a production environment, a more robust cache store (e.g., Rails.cache)
29
+ # might be preferred for persistence and memory management, especially for large applications.
30
+ # This simple in-memory cache is effective for a single process.
31
+ @cache = {}
32
+
33
+ def self.clear_cache # Class method to allow clearing cache manually, if needed
34
+ @cache = {}
35
+ end
36
+
37
+ def call(template, source = nil)
38
+ identifier = template.identifier
39
+
40
+ # Only use cache in non-development environments
41
+ # Check if cache exists for this template and if the source hasn't changed.
42
+ # This prevents recompilation of unchanged templates.
43
+ if !Rails.env.development? && self.class.instance_variable_get(:@cache)[identifier] &&
44
+ source == self.class.instance_variable_get(:@cache)[identifier][:source]
45
+ return self.class.instance_variable_get(:@cache)[identifier][:result]
46
+ end
47
+
48
+ # Process the template source into an ERB-compatible string
49
+ processed_source = process_template(source, template)
50
+
51
+ # Get the standard ERB handler and pass the processed source to it
52
+ erb_handler = ActionView::Template.registered_template_handler(:erb)
53
+ result = erb_handler.call(template, processed_source)
54
+
55
+ # Cache the result for future requests, but only in non-development environments.
56
+ # In development, templates change frequently, so caching would hinder development flow.
57
+ unless Rails.env.development?
58
+ self.class.instance_variable_set(:@cache, self.class.instance_variable_get(:@cache).merge({
59
+ identifier => { source: source, result: result }
60
+ }))
61
+ end
62
+ result
63
+ end
64
+
65
+ private
66
+
67
+ # A memoization cache for resolved component classes within a single template processing.
68
+ # This prevents repeated `constantize` calls for the same component name within `process_template`.
69
+ attr_reader :component_class_memo
70
+
71
+ def initialize
72
+ @component_class_memo = {}
73
+ end
74
+
75
+ # Processes the .evc template source, converting custom tags into Rails View Component render calls.
76
+ # This method is recursive to handle nested components.
77
+ def process_template(source, template)
78
+ # Using an array for `parts` and then joining at the end is generally more efficient
79
+ # for building strings in Ruby than repeated string concatenations (`<<`).
80
+ parts = []
81
+ pos = 0
82
+ stack = [] # Track [component_class_name, render_params_str, start_pos_in_source]
83
+
84
+ # Initialize memoization cache for this processing run
85
+ @component_class_memo = {}
86
+
87
+ while pos < source.length
88
+ # Try to match an opening or self-closing tag
89
+ if (match = TAG_REGEX.match(source, pos))
90
+ # Append text before the current tag to the result parts
91
+ parts << source[pos...match.begin(0)]
92
+ pos = match.end(0) # Move position past the matched tag
93
+
94
+ is_self_closing = match[0].end_with?("/>")
95
+ tag_name = match[1]
96
+ attributes_str = match[2].strip
97
+
98
+ # Determine the full component class name
99
+ component_class_name = if tag_name.end_with?("Component")
100
+ tag_name
101
+ else
102
+ "#{tag_name}Component"
103
+ end
104
+
105
+ # Validate if the component class exists using memoization.
106
+ # The component class will only be constantized once per unique class name
107
+ # within a single template processing call.
108
+ component_class = @component_class_memo[component_class_name] ||= begin
109
+ component_class_name.constantize
110
+ rescue NameError
111
+ raise ArgumentError, "Component #{component_class_name} not found in template #{template.identifier}"
112
+ end
113
+
114
+ # Parse attributes and format them for the render call
115
+ params = []
116
+ attributes_str.scan(ATTRIBUTE_REGEX) do |key, quoted_value, single_quoted_value, ruby_expression|
117
+ # Basic validation for attribute keys
118
+ unless key =~ /\A[a-z_][a-z0-9_]*\z/i
119
+ raise ArgumentError, "Invalid attribute key '#{key}' in template #{template.identifier}"
120
+ end
121
+
122
+ formatted_key = "#{key}:"
123
+ if ruby_expression
124
+ # For Ruby expressions, directly embed the expression.
125
+ params << "#{formatted_key} #{ruby_expression}"
126
+ elsif quoted_value
127
+ # For double-quoted string literals, escape double quotes within the value.
128
+ params << "#{formatted_key} \"#{quoted_value.gsub('"', '\"')}\""
129
+ elsif single_quoted_value
130
+ # For single-quoted string literals, escape single quotes within the value
131
+ # and wrap in double quotes for Ruby string literal syntax.
132
+ params << "#{formatted_key} \"#{single_quoted_value.gsub("'", "\\'")}\""
133
+ end
134
+ end
135
+
136
+ render_params_str = params.join(", ")
137
+
138
+ if is_self_closing
139
+ # If it's a self-closing tag, generate a simple render call.
140
+ parts << "<%= render #{component_class_name}.new(#{render_params_str}) %>"
141
+ else
142
+ # If it's an opening tag, push it onto the stack to await its closing tag.
143
+ stack << [component_class_name, render_params_str, pos]
144
+ end
145
+
146
+ # Try to match a closing tag
147
+ elsif (match = CLOSE_TAG_REGEX.match(source, pos))
148
+ # Append text before the closing tag to the result parts
149
+ parts << source[pos...match.begin(0)]
150
+ pos = match.end(0) # Move position past the matched tag
151
+
152
+ closing_tag_name = match[1]
153
+
154
+ # Check for unmatched closing tags
155
+ if stack.empty?
156
+ raise ArgumentError, "Unmatched closing tag </#{closing_tag_name}> in template #{template.identifier}"
157
+ end
158
+
159
+ # Pop the corresponding opening tag from the stack
160
+ component_class_name, render_params_str, start_pos = stack.pop
161
+
162
+ # Check for mismatched tags (e.g., <div></p>)
163
+ if component_class_name != closing_tag_name
164
+ raise ArgumentError, "Mismatched tags: expected </#{component_class_name}>, got </#{closing_tag_name}> in template #{template.identifier}"
165
+ end
166
+
167
+ # Recursively process the content between the opening and closing tags.
168
+ # This is where nested components are handled.
169
+ content = process_template(source[start_pos...match.begin(0)], template)
170
+
171
+ # Generate the render call with a block for the content.
172
+ parts << "<%= render #{component_class_name}.new(#{render_params_str}) do %>#{content}<% end %>"
173
+
174
+ else
175
+ # If no tags are matched, append the rest of the source and break the loop.
176
+ parts << source[pos..-1]
177
+ break
178
+ end
179
+ end
180
+
181
+ # After parsing, if the stack is not empty, it means there are unclosed tags.
182
+ unless stack.empty?
183
+ raise ArgumentError, "Unclosed tag <#{stack.last[0]}> in template #{template.identifier}"
184
+ end
185
+
186
+ # Join all the collected parts to form the final ERB string.
187
+ parts.join("")
188
+ end
189
+ end
190
+ end
191
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EvcRails
4
+ VERSION = "0.1.0"
5
+ end
data/lib/evc_rails.rb ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails"
4
+ require "active_support/lazy_load_hooks"
5
+ require "action_view"
6
+ require_relative "evc_rails/version"
7
+ require_relative "evc_rails/template_handler"
8
+ require_relative "evc_rails/railtie"
9
+
10
+ module EvcRails
11
+ class Error < StandardError; end
12
+ end
data/sig/evc_rails.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module EvcRails
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,111 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: evc_rails
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - scttymn
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: actionview
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: activesupport
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '0'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '0'
40
+ - !ruby/object:Gem::Dependency
41
+ name: rails
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '6.0'
47
+ type: :runtime
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '6.0'
54
+ - !ruby/object:Gem::Dependency
55
+ name: view_component
56
+ requirement: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '2.0'
61
+ type: :runtime
62
+ prerelease: false
63
+ version_requirements: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '2.0'
68
+ description: A Rails engine that provides a custom template handler for .evc files,
69
+ allowing developers to use PascalCase ViewComponent tags (e.g., <MyComponent />)
70
+ directly in their HTML, similar to JSX.
71
+ email:
72
+ - scotty@hey.com
73
+ executables: []
74
+ extensions: []
75
+ extra_rdoc_files: []
76
+ files:
77
+ - ".rubocop.yml"
78
+ - LICENSE.txt
79
+ - README.md
80
+ - Rakefile
81
+ - lib/evc_rails.rb
82
+ - lib/evc_rails/railtie.rb
83
+ - lib/evc_rails/template_handler.rb
84
+ - lib/evc_rails/version.rb
85
+ - sig/evc_rails.rbs
86
+ homepage: https://github.com/scttymn/evc_rails
87
+ licenses:
88
+ - MIT
89
+ metadata:
90
+ allowed_push_host: https://rubygems.org
91
+ homepage_uri: https://github.com/scttymn/evc_rails
92
+ source_code_uri: https://github.com/scttymn/evc_rails
93
+ changelog_uri: https://github.com/scttymn/evc_rails/blob/main/CHANGELOG.md
94
+ rdoc_options: []
95
+ require_paths:
96
+ - lib
97
+ required_ruby_version: !ruby/object:Gem::Requirement
98
+ requirements:
99
+ - - ">="
100
+ - !ruby/object:Gem::Version
101
+ version: 3.1.0
102
+ required_rubygems_version: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - ">="
105
+ - !ruby/object:Gem::Version
106
+ version: '0'
107
+ requirements: []
108
+ rubygems_version: 3.6.9
109
+ specification_version: 4
110
+ summary: Enables JSX-like PascalCase component tags in Rails .evc view files.
111
+ test_files: []