Class: RadioGroupComponent

Inherits:
Object
  • Object
show all
Includes:
HTMLComponent
Defined in:
lib/html-native/collections.rb

Overview

RadioGroupComponent represents an HTML radio button group generated from an Enumerable collection.

Each item has a unique id of the form of ‘“#name-choice”`, where name is the provided name option, and choice is value of that button.

Each item produces a button and a label.

Attributes in an RadioGroupComponent are separated into multiple groups since there are multiple kinds of tags. These groups are:

  • button - The attributes associated with the <input type: “radio”> elements.

  • label - The attributes associated with <label> elements.

Constant Summary

Constants included from HTMLComponent

HTMLComponent::FORBIDDEN_ATTRIBUTES, HTMLComponent::LIMITED_ATTRIBUTES, HTMLComponent::TAG_LIST

Instance Method Summary collapse

Methods included from HTMLComponent

#_if, #_label, #_unless, #doctype, singleton, #valid_attribute?

Constructor Details

#initialize(choices, name, attributes: {}, labelled: true, &block) ⇒ RadioGroupComponent

Creates a new instance of RadioGroupComponent from the values of choices.

If a block is given, each item in choices is passed to it to render the label. If no block is given, choices is used directly.



363
364
365
366
367
368
369
370
# File 'lib/html-native/collections.rb', line 363

def initialize(choices, name, attributes: {}, labelled: true, &block)
  @choices = choices
  @name = name
  @button_attributes = attributes[:button]
  @label_attributes = attributes[:label]
  @labelled = labelled
  @block = block
end

Instance Method Details

#renderObject

Converts the RadioGroupComponent instance to the equivalent HTML.

render can be called directly, but that usually isn’t necessary. HTMLComponent::Builder handles this automatically, so it only needs to be done if there is no prior instance of one.



377
378
379
380
381
382
383
# File 'lib/html-native/collections.rb', line 377

def render
  @choices.component_map do |c|
    id = "#{@name}-#{c}" 
    input({type: "radio", id: id, name: @name, value: c}) +
      (@labelled ? (label({for: id}) {@block ? @block.call(c) : c}) : nil)
  end
end