Method: ActiveComponent::Base#init_component

Defined in:
lib/active_component/base.rb

#init_component(args, var_names = [:content, :title, :attributes], &content_block) ⇒ Object

Initializes component by fetching arguments of a flexible method call as well as initializing the node and buffer Example

def initialize(*args, &content_block)
  fetch_args(args, [:content, :title, :special_param, :attributes], &content_block)

  # Set defaults afterwards
  @attributes ||= {:class => @title}
end

Arguments may be non-hash objects with certain order. Then, the arguments will be set to instance variables with the var_names entry at the same index. Though, it is always possible use a hash for assigning parameters to keywords (e.g. :title => “Blumenkübel”); As always, parenthesis can be omitted for this last hash.

The list of variable names will be iterated in order. The first element becomes an instance variable that gets the block assigned (if passed along). If the list of variable names iteration is complete, remaining key-value pairs of the Hash part of the arguments list are merged into @attributes.

Thus, all of the following signatures are legal for the **sender of fetch_args**: *Example 1*

new("content", "title", :class => "api")

*Example 2*

new(:class => "api", :title => "title") { content }

*Example 3*

new("content", {:attributes => {:class => "api"}, :title => "title"})

Parameters:

  • args (Array<Object>)

    Argument list where to fetch from

  • var_names (Array<Symbol>) (defaults to: [:content, :title, :attributes])

    Ordered list of instance variables to fetch. First one gets assigned to block (if given).

  • &content_block (#to_proc)

    The given block; will be assigned to variable named first in var_names.



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/active_component/base.rb', line 47

def init_component(args, var_names = [:content, :title, :attributes], &content_block)

  init_node
  init_buffer

  # Fetch arguments
  non_hash_args = []
  args_hash     = {}
  # Collect all non-hash args and merge all hashs together
  for arg in args
    arg.is_a?(Hash) ? args_hash.merge!(arg) : non_hash_args << arg
  end

  # var_names.first is set to block if block given
  send(var_names.shift.to_s + "=", content_block.call) if content_block

  for var_name in var_names
    # Each value is extracted from args_hash, if resp. var_name present, otherwise the next non-hash argument is taken
    send var_name.to_s + "=", (args_hash.delete(var_name) or non_hash_args.shift)
  end

  @attributes ||= {}
  # All args in args_hash that have not been used for setting an instance variable become attributes.
  @attributes.set_defaults!(args_hash)
  # The class attribute will contain the component title and class_name (unless component is a html tag wrapper)
  @attributes[:class] = (html_class + [@attributes[:class]].flatten).compact.uniq
end