Class: ViewComponent::Base
- Inherits:
-
ActionView::Base
- Object
- ActionView::Base
- ViewComponent::Base
- Includes:
- ActiveSupport::Configurable, Previewable, SlotableV2, WithContentHelper
- Defined in:
- lib/view_component/base.rb
Constant Summary collapse
- ViewContextCalledBeforeRenderError =
Class.new(StandardError)
- RESERVED_PARAMETER =
:content
Class Attribute Summary collapse
-
.source_location ⇒ Object
Returns the value of attribute source_location.
-
.virtual_path ⇒ Object
Returns the value of attribute virtual_path.
Class Method Summary collapse
-
._after_compile ⇒ Object
EXPERIMENTAL: This API is experimental and may be removed at any time.
-
._sidecar_files(extensions) ⇒ Object
EXPERIMENTAL: This API is experimental and may be removed at any time.
- .collection_counter_parameter ⇒ Object
- .collection_parameter ⇒ Object
-
.compile(raise_errors: false) ⇒ Object
Compile templates to instance methods, assuming they haven't been compiled already.
- .compiled? ⇒ Boolean
- .compiler ⇒ Object
- .counter_argument_present? ⇒ Boolean
- .format ⇒ Object
- .identifier ⇒ Object
- .inherited(child) ⇒ Object
-
.short_identifier ⇒ Object
Provide identifier for ActionView template annotations.
-
.type ⇒ Object
we'll eventually want to update this to support other types.
-
.validate_collection_parameter!(validate_default: false) ⇒ Object
Ensure the component initializer accepts the collection parameter.
-
.validate_initialization_parameters! ⇒ Object
Ensure the component initializer does not define invalid parameters that could override the framework's methods.
-
.with_collection(collection, **args) ⇒ Object
Render a component collection.
-
.with_collection_parameter(param) ⇒ Object
Support overriding collection parameter name.
- .with_content_areas(*areas) ⇒ Object
Instance Method Summary collapse
- #before_render ⇒ Object
- #before_render_check ⇒ Object
- #controller ⇒ Object
-
#format ⇒ Object
For caching, such as #cache_if.
-
#helpers ⇒ Object
Provides a proxy to access helper methods from the context of the current controller.
-
#initialize ⇒ Base
constructor
A new instance of Base.
-
#render(options = {}, args = {}, &block) ⇒ Object
Re-use original view_context if we're not rendering a component.
- #render? ⇒ Boolean
-
#render_in(view_context, &block) ⇒ Object
Entrypoint for rendering components.
-
#request ⇒ Object
Exposes the current request to the component.
-
#view_cache_dependencies ⇒ Object
For caching, such as #cache_if.
-
#virtual_path ⇒ Object
Exposes .virtual_path as an instance method.
-
#with(area, content = nil, &block) ⇒ Object
Assign the provided content to the content area accessor.
- #with_variant(variant) ⇒ Object
Methods included from WithContentHelper
Methods included from SlotableV2
Constructor Details
#initialize ⇒ Base
Returns a new instance of Base.
112 |
# File 'lib/view_component/base.rb', line 112 def initialize(*); end |
Class Attribute Details
.source_location ⇒ Object
Returns the value of attribute source_location.
213 214 215 |
# File 'lib/view_component/base.rb', line 213 def source_location @source_location end |
.virtual_path ⇒ Object
Returns the value of attribute virtual_path.
213 214 215 |
# File 'lib/view_component/base.rb', line 213 def virtual_path @virtual_path end |
Class Method Details
._after_compile ⇒ Object
EXPERIMENTAL: This API is experimental and may be removed at any time. Hook for allowing components to do work as part of the compilation process.
For example, one might compile component-specific assets at this point.
33 34 35 |
# File 'lib/view_component/base.rb', line 33 def self._after_compile # noop end |
._sidecar_files(extensions) ⇒ Object
EXPERIMENTAL: This API is experimental and may be removed at any time. Find sidecar files for the given extensions.
The provided array of extensions is expected to contain strings starting without the “dot”, example: `[“erb”, “haml”]`.
For example, one might collect sidecar CSS files that need to be compiled.
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 |
# File 'lib/view_component/base.rb', line 222 def _sidecar_files(extensions) return [] unless source_location extensions = extensions.join(",") # view files in a directory named like the component directory = File.dirname(source_location) filename = File.basename(source_location, ".rb") component_name = name.demodulize.underscore # Add support for nested components defined in the same file. # # e.g. # # class MyComponent < ViewComponent::Base # class MyOtherComponent < ViewComponent::Base # end # end # # Without this, `MyOtherComponent` will not look for `my_component/my_other_component.html.erb` nested_component_files = if name.include?("::") && component_name != filename Dir["#{directory}/#{filename}/#{component_name}.*{#{extensions}}"] else [] end # view files in the same directory as the component sidecar_files = Dir["#{directory}/#{component_name}.*{#{extensions}}"] sidecar_directory_files = Dir["#{directory}/#{component_name}/#{filename}.*{#{extensions}}"] (sidecar_files - [source_location] + sidecar_directory_files + nested_component_files).uniq end |
.collection_counter_parameter ⇒ Object
389 390 391 |
# File 'lib/view_component/base.rb', line 389 def collection_counter_parameter "#{collection_parameter}_counter".to_sym end |
.collection_parameter ⇒ Object
381 382 383 384 385 386 387 |
# File 'lib/view_component/base.rb', line 381 def collection_parameter if provided_collection_parameter provided_collection_parameter else name && name.demodulize.underscore.chomp("_component").to_sym end end |
.compile(raise_errors: false) ⇒ Object
Compile templates to instance methods, assuming they haven't been compiled already.
Do as much work as possible in this step, as doing so reduces the amount of work done each time a component is rendered.
296 297 298 |
# File 'lib/view_component/base.rb', line 296 def compile(raise_errors: false) compiler.compile(raise_errors: raise_errors) end |
.compiled? ⇒ Boolean
288 289 290 |
# File 'lib/view_component/base.rb', line 288 def compiled? compiler.compiled? end |
.compiler ⇒ Object
300 301 302 |
# File 'lib/view_component/base.rb', line 300 def compiler @_compiler ||= Compiler.new(self) end |
.counter_argument_present? ⇒ Boolean
393 394 395 |
# File 'lib/view_component/base.rb', line 393 def counter_argument_present? initialize_parameter_names.include?(collection_counter_parameter) end |
.format ⇒ Object
309 310 311 |
# File 'lib/view_component/base.rb', line 309 def format :html end |
.identifier ⇒ Object
313 314 315 |
# File 'lib/view_component/base.rb', line 313 def identifier source_location end |
.inherited(child) ⇒ Object
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 |
# File 'lib/view_component/base.rb', line 266 def inherited(child) # Compile so child will inherit compiled `call_*` template methods that # `compile` defines compile # If Rails application is loaded, add application url_helpers to the component context # we need to check this to use this gem as a dependency if defined?(Rails) && Rails.application child.include Rails.application.routes.url_helpers unless child < Rails.application.routes.url_helpers end # Derive the source location of the component Ruby file from the call stack. # We need to ignore `inherited` frames here as they indicate that `inherited` # has been re-defined by the consuming application, likely in ApplicationComponent. child.source_location = caller_locations(1, 10).reject { |l| l.label == "inherited" }[0].absolute_path # Removes the first part of the path and the extension. child.virtual_path = child.source_location.gsub(%r{(.*app/components)|(\.rb)}, "") super end |
.short_identifier ⇒ Object
Provide identifier for ActionView template annotations
262 263 264 |
# File 'lib/view_component/base.rb', line 262 def short_identifier @short_identifier ||= defined?(Rails.root) ? source_location.sub("#{Rails.root}/", "") : source_location end |
.type ⇒ Object
we'll eventually want to update this to support other types
305 306 307 |
# File 'lib/view_component/base.rb', line 305 def type "text/html" end |
.validate_collection_parameter!(validate_default: false) ⇒ Object
Ensure the component initializer accepts the collection parameter. By default, we do not validate that the default parameter name is accepted, as support for collection rendering is optional.
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 |
# File 'lib/view_component/base.rb', line 347 def validate_collection_parameter!(validate_default: false) parameter = validate_default ? collection_parameter : provided_collection_parameter return unless parameter return if initialize_parameter_names.include?(parameter) # If Ruby cannot parse the component class, then the initalize # parameters will be empty and ViewComponent will not be able to render # the component. if initialize_parameters.empty? raise ArgumentError.new( "#{self} initializer is empty or invalid." ) end raise ArgumentError.new( "#{self} initializer must accept " \ "`#{parameter}` collection parameter." ) end |
.validate_initialization_parameters! ⇒ Object
Ensure the component initializer does not define invalid parameters that could override the framework's methods.
371 372 373 374 375 376 377 378 379 |
# File 'lib/view_component/base.rb', line 371 def validate_initialization_parameters! return unless initialize_parameter_names.include?(RESERVED_PARAMETER) raise ViewComponent::ComponentError.new( "#{self} initializer cannot contain " \ "`#{RESERVED_PARAMETER}` since it will override a " \ "public ViewComponent method." ) end |
.with_collection(collection, **args) ⇒ Object
Render a component collection.
257 258 259 |
# File 'lib/view_component/base.rb', line 257 def with_collection(collection, **args) Collection.new(self, collection, **args) end |
.with_collection_parameter(param) ⇒ Object
Support overriding collection parameter name
338 339 340 |
# File 'lib/view_component/base.rb', line 338 def with_collection_parameter(param) @provided_collection_parameter = param end |
.with_content_areas(*areas) ⇒ Object
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
# File 'lib/view_component/base.rb', line 317 def with_content_areas(*areas) ActiveSupport::Deprecation.warn( "`with_content_areas` is deprecated and will be removed in ViewComponent v3.0.0.\n" \ "Use slots (https://viewcomponent.org/guide/slots.html) instead." ) if areas.include?(:content) raise ArgumentError.new ":content is a reserved content area name. Please use another name, such as ':body'" end areas.each do |area| define_method area.to_sym do content unless content_evaluated? # ensure content is loaded so content_areas will be defined instance_variable_get(:"@#{area}") if instance_variable_defined?(:"@#{area}") end end self.content_areas = areas end |
Instance Method Details
#before_render ⇒ Object
100 101 102 |
# File 'lib/view_component/base.rb', line 100 def before_render before_render_check end |
#before_render_check ⇒ Object
104 105 106 |
# File 'lib/view_component/base.rb', line 104 def before_render_check # noop end |
#controller ⇒ Object
127 128 129 130 |
# File 'lib/view_component/base.rb', line 127 def controller raise ViewContextCalledBeforeRenderError, "`controller` can only be called at render time." if view_context.nil? @controller ||= view_context.controller end |
#format ⇒ Object
For caching, such as #cache_if
149 150 151 152 153 154 |
# File 'lib/view_component/base.rb', line 149 def format # Ruby 2.6 throws a warning without checking `defined?`, 2.7 does not if defined?(@variant) @variant end end |
#helpers ⇒ Object
Provides a proxy to access helper methods from the context of the current controller
133 134 135 136 |
# File 'lib/view_component/base.rb', line 133 def helpers raise ViewContextCalledBeforeRenderError, "`helpers` can only be called at render time." if view_context.nil? @helpers ||= controller.view_context end |
#render(options = {}, args = {}, &block) ⇒ Object
Re-use original view_context if we're not rendering a component.
This prevents an exception when rendering a partial inside of a component that has also been rendered outside of the component. This is due to the partials compiled template method existing in the parent `view_context`,
and not the component's `view_context`.
119 120 121 122 123 124 125 |
# File 'lib/view_component/base.rb', line 119 def render( = {}, args = {}, &block) if .is_a? ViewComponent::Base super else view_context.render(, args, &block) end end |
#render? ⇒ Boolean
108 109 110 |
# File 'lib/view_component/base.rb', line 108 def render? true end |
#render_in(view_context, &block) ⇒ Object
Entrypoint for rendering components.
view_context: ActionView context from calling view block: optional block to be captured within the view context
returns HTML that has been escaped by the respective template handler
Example subclass:
app/components/my_component.rb: class MyComponent < ViewComponent::Base
def initialize(title:)
@title = title
end
end
app/components/my_component.html.erb <span title=“<%= @title %>”>Hello, <%= content %>!</span>
In use: <%= render MyComponent.new(title: “greeting”) do %>world<% end %> returns: <span title=“greeting”>Hello, world!</span>
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/view_component/base.rb', line 61 def render_in(view_context, &block) self.class.compile(raise_errors: true) @view_context = view_context @lookup_context ||= view_context.lookup_context # required for path helpers in older Rails versions @view_renderer ||= view_context.view_renderer # For content_for @view_flow ||= view_context.view_flow # For i18n @virtual_path ||= virtual_path # For template variants (+phone, +desktop, etc.) @variant ||= @lookup_context.variants.first # For caching, such as #cache_if @current_template = nil unless defined?(@current_template) old_current_template = @current_template @current_template = self raise ArgumentError.new("Block provided after calling `with_content`. Use one or the other.") if block && defined?(@_content_set_by_with_content) @_content_evaluated = false @_render_in_block = block before_render if render? render_template_for(@variant) else "" end ensure @current_template = old_current_template end |
#request ⇒ Object
Exposes the current request to the component. Use sparingly as doing so introduces coupling that inhibits encapsulation & reuse.
179 180 181 |
# File 'lib/view_component/base.rb', line 179 def request @request ||= controller.request end |
#view_cache_dependencies ⇒ Object
For caching, such as #cache_if
144 145 146 |
# File 'lib/view_component/base.rb', line 144 def view_cache_dependencies [] end |
#virtual_path ⇒ Object
Exposes .virtual_path as an instance method
139 140 141 |
# File 'lib/view_component/base.rb', line 139 def virtual_path self.class.virtual_path end |
#with(area, content = nil, &block) ⇒ Object
Assign the provided content to the content area accessor
157 158 159 160 161 162 163 164 165 166 167 168 |
# File 'lib/view_component/base.rb', line 157 def with(area, content = nil, &block) unless content_areas.include?(area) raise ArgumentError.new "Unknown content_area '#{area}' - expected one of '#{content_areas}'" end if block_given? content = view_context.capture(&block) end instance_variable_set("@#{area}".to_sym, content) nil end |
#with_variant(variant) ⇒ Object
170 171 172 173 174 |
# File 'lib/view_component/base.rb', line 170 def with_variant(variant) @variant = variant self end |