Class: ActiveComponent::Base

Inherits:
Mustache
  • Object
show all
Includes:
ActionView::Helpers::DateHelper, Renderable
Defined in:
lib/active_component/base.rb

Overview

We inherit from mustache to have a default template engine for the application, we might add more templating options in the future.

Direct Known Subclasses

ApplicationComponent

Instance Method Summary collapse

Methods included from Renderable

#render_component

Constructor Details

#initialize(args = {}) ⇒ Base

Whenever the user creates a new object from a class inherited from ActiveComponent::Base it needs to define its attributes as ‘attr_accessor :var` in order to be able to initialize the object with specific values.

class ViewComponent < ActiveComponent::Base

attr_accessor :var

end

The values shall be provided as hash, active component automatically will know who’s going to receive the value otherwise raise an error.

component = ViewComponent.new(var: var)

In addition to this we provide the controller context from where the view component is called.

self.controller from anywhere in the inherited classes.



37
38
39
40
# File 'lib/active_component/base.rb', line 37

def initialize(args = {})
  assign_variables args
  @controller = ActiveComponent.get_controller if defined?(Rails)
end

Instance Method Details

#assign_variables(args) ⇒ Object



42
43
44
45
46
47
48
49
50
# File 'lib/active_component/base.rb', line 42

def assign_variables(args)
  if args.kind_of? Hash
    args.each do |key, value|
      self.send("#{key}=", value)
    end
  else
    raise ArgumentError, "Expected: Hash. Received: #{args.class.name}"
  end
end

#controllerObject



52
53
54
# File 'lib/active_component/base.rb', line 52

def controller
  @controller
end

#renderObject



56
57
58
# File 'lib/active_component/base.rb', line 56

def render
  super.html_safe
end