### Run Custom Rails Generator
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
This command installs the 'view_component-contrib' gem, configures ViewComponent paths, adds base classes for components and previews, sets up the testing framework, and includes a custom generator for creating components. It simplifies the initial setup and component creation process.
```sh
rails app:template LOCATION="https://railsbytes.com/script/zJosO5"
```
--------------------------------
### Custom Example-Specific Preview Templates
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Explains how to use custom preview templates, either a general `preview.html.*` for all examples in a preview class or an example-specific `previews/example.html.*`.
```ruby
# For all examples in this preview class:
# previews/preview.html.erb
# For a specific example (e.g., 'mobile'):
# previews/mobile.html.erb
```
--------------------------------
### JavaScript Entry Point for Component
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Example of a JavaScript entry point for a component, which imports its associated CSS file. This is a common pattern when using sidecar assets.
```js
import "./index.css";
```
--------------------------------
### Install view_component-contrib Gem
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
This snippet shows how to add the 'view_component-contrib' gem to your Gemfile to use its extensions and patterns. It's the first step to integrating the library into your Rails application.
```ruby
gem "view_component-contrib"
```
--------------------------------
### StimulusJS Application Setup with Vite
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Configures and registers Stimulus controllers within a Stimulus application when using Vite as the module bundler. It dynamically loads controllers from component directories.
```javascript
import { Application } from "@hotwired/stimulus";
const application = Application.start();
// Configure Stimulus development experience
application.debug = false;
window.Stimulus = application;
// Generic controllers
const genericControllers = import.meta.globEager(
"../controllers/**/*_controller.js"
);
for (let path in genericControllers) {
let module = genericControllers[path];
let name = path
.match(/controllers\/(.+)_controller\.js$/)[1]
.replaceAll("/", "-")
.replaceAll("_", "-");
application.register(name, module.default);
}
// Controllers from components
const controllers = import.meta.globEager(
"./../../app/frontend/components/**/controller.js"
);
for (let path in controllers) {
let module = controllers[path];
let name = path
.match(/app\/frontend\/components\/(.+)\/controller\.js$/)[1]
.replaceAll("/", "-")
.replaceAll("_", "-");
application.register(name, module.default);
}
export default application;
```
--------------------------------
### Customizing Default Preview Template
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Example of how to set a custom default template path for previews in an `ApplicationViewComponentPreview` class.
```ruby
class ApplicationViewComponentPreview < ViewComponentContrib::Preview::Base
# ...
self.default_preview_template = "path/to/your/template.html.{erb,haml,slim}"
# ...
end
```
--------------------------------
### Example Scoped CSS
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
An example of CSS rules within a component's `index.css` file, demonstrating the use of simple class names that will be transformed into unique, scoped class names by `postcss-modules`.
```css
.container {
padding: 10px;
background: white;
border: 1px solid #333;
}
.body {
margin-top: 20px;
font-size: 24px;
}
```
--------------------------------
### Create a View Component using Custom Generator
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
This command utilizes the custom generator provided by 'view_component-contrib' to create a new ViewComponent named 'Example'. It generates all necessary files for the component.
```sh
bundle exec rails g view_component Example
```
--------------------------------
### Configuring Container Class and Rendering Options
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Demonstrates setting a default container class for all previews in a class and overriding it or providing content blocks within specific actions.
```ruby
class Banner::Preview < ApplicationViewComponentPreview
self.container_class = "absolute w-full"
def default
# This will use `absolute w-full` for the container class
render_component Banner::Component.new(text: "Welcome!")
# or even shorter
render_component(text: "Welcome!")
# you can also pass a content block
render_component(kind: :notice) do
"Some content"
end
end
def mobile
render_with(
component: Banner::Component.new(text: "Welcome!").with_variant(:mobile),
container_class: "w-25"
)
end
end
```
--------------------------------
### StimulusJS Application Setup with Webpack
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Configures and registers Stimulus controllers within a Stimulus application when using Webpack. It uses `require.context` to load controllers from component directories.
```javascript
import { Application } from "stimulus";
export const application = Application.start();
// ... other controllers
const context = require.context("./../../app/frontend/components/", true, /controllers.js$/)
context.keys().forEach((path) => {
const mod = context(path);
// Check whether a module has the Controller export defined
if (!mod.Controller) return;
// Convert path into a controller identifier:
// example/index.js -> example
// nav/user_info/index.js -> nav--user-info
const identifier = path
.match(/app\/frontend\/components\/(.+)\/controller\.js$/)[1]
.replaceAll("/", "-")
.replaceAll("_", "-");
application.register(identifier, mod.Controller);
});
```
--------------------------------
### Implicit Component Rendering in Preview
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Illustrates implicit component rendering where the preview class attempts to build the component automatically by calling `ComponentName::Component.new`.
```ruby
class LikeButton::Preview < ApplicationViewComponentPreview
def default
# Nothing here; the preview class would try to build a component automatically
# calling `LikeButton::Component.new`
end
end
```
--------------------------------
### View Generator Options
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
This command displays all available options and configurations for the custom 'view_component' generator. It helps users understand how to customize component generation.
```sh
bundle exec rails g view_component -h
```
--------------------------------
### Explicit Component Rendering in Preview
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Shows how to explicitly render a component instance within a preview action using `render_component`.
```ruby
class Banner::Preview < ApplicationViewComponentPreview
def default
render_component Banner::Component.new(text: "Welcome!")
end
end
```
--------------------------------
### I18n Namespaced Translations
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Demonstrates how to structure YML translation files for ViewComponents using a namespaced approach. This allows for isolated localization files per component, improving organization. The example shows the expected YML structure and how to access translations within component templates.
```yml
en:
view_components:
login_form:
submit: "Log in"
nav:
user_info:
login: "Log in"
logout: "Log out"
```
--------------------------------
### Asset Organization with Vite
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Demonstrates how to organize JS and CSS files in a sidecar folder and load all components using Vite's dynamic import feature. The `index.js` file imports the component's CSS.
```js
// With Vite
import.meta.glob("./**/index.js").forEach((path) => {
const mod = await import(path);
mod.default();
});
```
--------------------------------
### Multiple Style Sets and Custom Classes
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Illustrates how to define multiple, independent style sets within a single component and how to apply additional CSS classes using the `class:` variant in the `style` method.
```ruby
class ButtonComponent < ViewComponent::Base
include ViewComponentContrib::StyleVariants
# default component styles
style do
# ...
end
style :image do
variants {
orient {
portrait { "w-32 h-32" }
landscape { "w-64 h-32" }
}
}
end
end
```
```erb
```
```erb
```
--------------------------------
### StimulusJS Data Attribute Usage in Template
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Example of how to use the generated `controller_name` helper in an ERB template to associate a Stimulus controller with an HTML element.
```html
```
--------------------------------
### Asset Organization with Webpack
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Illustrates asset organization using Webpack, where JS and CSS files are co-located with components. The root `components/index.js` uses `require.context` to load all components.
```js
// components/index.js
const context = require.context(".", true, /index.js$/)
context.keys().forEach(context);
```
--------------------------------
### Style Variants Inheritance Strategies
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Explains and demonstrates the three inheritance strategies for Style Variants: `override` (default), `merge` (deep merge), and `extend` (shallow merge) when extending components.
```ruby
class Parent::Component < ViewComponent::Base
include ViewComponentContrib::StyleVariants
style do
variants do
size {
md { "text-md" }
lg { "text-lg" }
}
disabled {
yes { "opacity-50" }
}
end
end
end
# Using override strategy (default)
class Child::Component < Parent::Component
style do
variants do
size {
lg { "text-larger" }
}
end
end
end
# Using merge strategy
class Child::Component < Parent::Component
style do
variants(strategy: :merge) do
size {
lg { "text-larger" }
}
end
end
end
# Using extend strategy
class Child::Component < Parent::Component
style do
variants(strategy: :extend) do
size {
lg { "text-larger" }
}
end
end
end
```
--------------------------------
### Refactoring Initialize with dry-initializer
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Demonstrates refactoring a ViewComponent's `#initialize` method using the `dry-initializer` gem. This approach promotes a more declarative style for defining component attributes and their default values.
```ruby
class ApplicationViewComponent
extend Dry::Initializer
end
class FlashAlert::Component < ApplicationViewComponent
option :type, default: proc { "success" }
option :duration, default: proc { 3000 }
option :body
end
```
--------------------------------
### Custom Postprocessing with TailwindMerge
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Shows how to integrate a custom postprocessing step, such as using TailwindMerge, to optimize the generated CSS class list by removing redundant or conflicting classes.
```ruby
class ButtonComponent < ViewComponent::Base
include ViewComponentContrib::StyleVariants
# You can provide either a proc or any other callable object
style_config.postprocess_with do |classes|
# classes is an array of CSS classes
# NOTE: This is an abstract TailwindMerge class, not to be confused with existing libraries
TailwindMerge.call(classes).join(" ")
end
end
```
--------------------------------
### Component Sidecar Structure
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Shows the typical file structure for a component's sidecar assets, including the component file, CSS, and JavaScript entry point. The `index.js` imports the associated CSS.
```txt
components/
example/
component.html
component.rb
index.css
index.js
```
--------------------------------
### Scoped CSS Class Usage in Template
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Example of using the `class_for` helper in an ERB template to apply scoped CSS classes to HTML elements, ensuring unique class names generated by `postcss-modules`.
```html
">
"><%= text %>
```
--------------------------------
### Using the #wrapped Method for Component Wrapping
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Demonstrates a simplified approach to wrapping components using the `#wrapped` method, which is included via `ViewComponentContrib::WrappedHelper`. This method streamlines the process of applying custom HTML wrappers to components.
```erb
<%= render Example::Component.new.wrapped do |wrapper|
<%= wrapper.component %>
<%- end -%>
```
--------------------------------
### Abstract Base Class for Previews
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Demonstrates setting `abstract_class = true` to prevent a preview class from appearing in the previews index, useful for base classes.
```ruby
class ApplicationViewComponentPreview < ViewComponentContrib::Preview::Base
# Do not show this class in the previews index
self.abstract_class = true
end
```
--------------------------------
### Accessing I18n Translations in ViewComponents
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Shows how to access namespaced translations within ViewComponent templates using the `t` helper. The examples illustrate accessing translations relative to the component's scope.
```erb
<%= t(".logout") %>
```
--------------------------------
### Including ViewComponentContrib WrappedHelper
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Provides the Ruby code for including the `ViewComponentContrib::WrappedHelper` module into a base ViewComponent class. This adds the convenient `#wrapped` method for easily wrapping components.
```ruby
class ApplicationViewComponent < ViewComponent::Base
# adds #wrapped method
# NOTE: Already included into ViewComponentContrib::Base
include ViewComponentContrib::WrappedHelper
end
```
--------------------------------
### StimulusJS Controller Definition
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Defines a Stimulus controller within a component's `controller.js` file. This serves as the entry point for component-specific JavaScript behavior.
```javascript
import { Controller as BaseController } from "@hotwired/stimulus";
export class Controller extends BaseController {
connect() {
// ...
}
}
```
--------------------------------
### Configure ViewComponent Preview Paths
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
This snippet demonstrates how to configure the lookup paths for ViewComponent previews in a Rails application. It ensures that ViewComponent can find preview files organized in custom locations.
```ruby
# view_component >= v4
config.view_component.previews.paths << Rails.root.join("app", "frontend", "components")
# view_component <= v3
config.view_component.preview_paths << Rails.root.join("app", "frontend", "components")
```
--------------------------------
### Final HTML Output with Scoped CSS
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
The resulting HTML output after processing with `postcss-modules`, showing how the original CSS class names have been transformed into unique, scoped identifiers (e.g., `c-example-container`).
```html
Some text
```
--------------------------------
### TailwindCSS LSP Configuration
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Configures TailwindCSS LSP for autocompletion and other features within the view_component-contrib DSL. This configuration specifically targets Ruby and ERB files and uses a regex for word arrays.
```json
{
"tailwindCSS.includeLanguages": {
"erb": "html",
"ruby": "html"
},
"tailwindCSS.experimental.classRegex": [
"%w\[([^\]]*)\]"
]
}
```
--------------------------------
### Including ViewComponentContrib Translation Helper
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Provides the Ruby code for including the `ViewComponentContrib::TranslationHelper` module into a base ViewComponent class. This enables the namespaced I18n functionality for components inheriting from this base class.
```ruby
class ApplicationViewComponent < ViewComponent::Base
include ViewComponentContrib::TranslationHelper
end
```
--------------------------------
### Default Preview Template
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
The default ERB template used by ViewComponent Contrib for rendering previews. It displays the component or an error message if the component cannot be inferred.
```erb
<%- if component -%>
<%= render component %>
<%- else -%>
Failed to infer a component from the preview: <%= error %>
<%- end -%>
```
--------------------------------
### Define and Use Style Variants in a Button Component
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Demonstrates how to define base styles, variants (color, size, disabled), and defaults within a ViewComponent using Style Variants. It also shows how to apply these variants in the ERB template.
```ruby
class ButtonComponent < ViewComponent::Base
include ViewComponentContrib::StyleVariants
style do
base {
%w[
font-medium bg-blue-500 text-white rounded-full
]
}
variants {
color {
primary { %w[bg-blue-500 text-white] }
secondary { %w[bg-purple-500 text-white] }
}
size {
sm { "text-sm" }
md { "text-base" }
lg { "px-4 py-3 text-lg" }
}
disabled {
yes { "opacity-75" }
}
}
defaults { {size: :md, color: :primary} }
end
attr_reader :size, :color, :disabled
def initialize(size: nil, color: nil, disabled: false)
@size = size
@color = color
@disabled = disabled
end
end
```
```erb
```
```html
```
```erb
```
--------------------------------
### Dependent Styles with Ruby Blocks
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Defines complex styling rules using Ruby blocks, allowing dynamic styling based on variant arguments. This approach is useful for combinations of variants that require additional styles.
```ruby
style do
variants {
size {
sm { "text-sm" }
md { "text-base" }
lg { "px-4 py-3 text-lg" }
}
theme {
primary do |size:, **|
%w[bg-blue-500 text-white].tap do
_1 << "uppercase" if size == :lg
end
end
secondary { %w[bg-purple-500 text-white] }
}
}
end
```
--------------------------------
### Dependent Styles with Compound Directive
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Provides a declarative approach to defining complex styling rules using the 'compound' directive. This method achieves the same dynamic styling as Ruby blocks but in a more structured format.
```ruby
style do
variants {
size {
sm { "text-sm" }
md { "text-base" }
lg { "px-4 py-3 text-lg" }
}
theme {
primary { %w[bg-blue-500 text-white] }
secondary { %w[bg-purple-500 text-white] }
}
}
compound(size: :lg, theme: :primary) { %w[uppercase] }
end
```
--------------------------------
### Specifying Collection Parameter for .with_collection
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Explains how to explicitly define the collection parameter name when using `.with_collection` with ViewComponents, especially when component naming conventions differ from the default. This ensures correct parameter inference.
```ruby
class PostCard::Component < ApplicationViewComponent
with_collection_parameter :post
option :post
end
```
--------------------------------
### Overriding I18n Namespace and Scope
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Illustrates how to customize the default I18n namespace and component scope in ViewComponents. This allows for greater flexibility in organizing translation files beyond the default conventions.
```ruby
class ApplicationViewComponent < ViewComponentContrib::Base
self.i18n_namespace = "my_components"
end
class SomeButton::Component < ApplicationViewComponent
self.i18n_scope = %w[legacy button]
end
```
--------------------------------
### PostCSS Modules Configuration for Scoped CSS
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Configuration for the `postcss-modules` plugin to generate unique, scoped class names for CSS within components. It defines a naming convention that aligns with Stimulus controller identifiers.
```javascript
module.exports = {
plugins: {
'postcss-modules': {
generateScopedName: (name, filename, _css) => {
const matches = filename.match(//app\/frontend\/components\/?(.*)\/index.css$/);
// Do not transform CSS files from outside of the components folder
if (!matches) return name;
// identifier here is the same identifier we used for Stimulus controller (see above)
const identifier = matches[1].replace("/", "--");
// We also add the `c-` prefix to all components classes
return `c-${identifier}-${name}`;
},
// Do not generate *.css.json files (we don't use them)
getJSON: () => {}
},
/// other plugins
},
}
```
--------------------------------
### Patch ViewComponent::Preview for Sidecarable Previews
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
This code patches the ViewComponent::Preview class to enable the 'Sidecarable' functionality, allowing preview files to be organized alongside their components without the '_preview.rb' suffix. This is typically placed in an initializer file.
```ruby
# you can put this into an initializer
ActiveSupport.on_load(:view_component) do
ViewComponent::Preview.extend ViewComponentContrib::Preview::Sidecarable
end
```
--------------------------------
### Wrapping Components with ViewComponentContrib::WrapperComponent
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
Shows how to wrap a ViewComponent within a custom HTML container using `ViewComponentContrib::WrapperComponent`. This component ensures that the wrapper is only rendered if the inner component's `#render?` method returns true.
```erb
<%= render ViewComponentContrib::WrappedComponent.new(Example::Component.new) do |wrapper|
<%= wrapper.component %>
<%- end -%>
```
--------------------------------
### ViewComponent Helper for Stimulus Controller Identifier
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
A Ruby helper method within the base ViewComponent class to generate a Stimulus controller identifier based on the component's class name, following a specific naming convention.
```ruby
class ApplicationViewComponent
private
def identifier
@identifier ||= self.class.name.sub("::Component", "").underscore.split("/").join("--")
end
alias_method :controller_name, :identifier
end
```
--------------------------------
### ViewComponent Helper for Scoped CSS Class Generation
Source: https://github.com/palkan/view_component-contrib/blob/master/README.md
A Ruby helper method within the base ViewComponent class to generate scoped CSS class names using the `postcss-modules` naming convention. It ensures consistency between Stimulus controller identifiers and CSS class names.
```ruby
class ApplicationViewComponent
private
# the same as above
def identifier
@identifier ||= self.class.name.sub("::Component", "").underscore.split("/").join("--")
end
# We also add an ability to build a class from a different component
def class_for(name, from: identifier)
"c-#{from}-#{name}"
end
end
```
--------------------------------
### Push Code to GitHub
Source: https://github.com/palkan/view_component-contrib/blob/master/RELEASING.md
Pushes the local changes to the remote GitHub repository to ensure CI checks can be performed.
```sh
git push
```
--------------------------------
### Push Tags
Source: https://github.com/palkan/view_component-contrib/blob/master/RELEASING.md
Pushes all Git tags to the remote repository, ensuring that release tags are available remotely.
```sh
git push --tags
```
--------------------------------
### Publish Rails Bytes Template
Source: https://github.com/palkan/view_component-contrib/blob/master/RELEASING.md
Publishes a Rails Bytes template using a Rake task. This requires specific environment variables to be set.
```ruby
bundle exec rake publish_template
```
--------------------------------
### Release Gem
Source: https://github.com/palkan/view_component-contrib/blob/master/RELEASING.md
Releases a new version of the gem using the 'gem release' command. The '-t' flag typically indicates tagging the release.
```sh
gem release -t
```
--------------------------------
### Bump Version
Source: https://github.com/palkan/view_component-contrib/blob/master/RELEASING.md
Commits the version bump to the Git repository. This is typically done before releasing a new gem version.
```sh
git commit -m "Bump 1.."
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.