Class: Protoform::DOM

Inherits:
Object
  • Object
show all
Defined in:
lib/protoform/dom.rb

Overview

Generates DOM IDs, names, etc. for a Field, Namespace, or Node based on norms that were established by Rails. These can be used outsidef or Rails in other Ruby web frameworks since it has now dependencies on Rails.

Instance Method Summary collapse

Constructor Details

#initialize(field:) ⇒ DOM

Returns a new instance of DOM.



8
9
10
# File 'lib/protoform/dom.rb', line 8

def initialize(field:)
  @field = field
end

Instance Method Details

#idObject

Walks from the current node to the parent node, grabs the names, and seperates them with a ‘_` for a DOM ID. One limitation of this approach is if multiple forms exist on the same page, the ID may be duplicate.



22
23
24
# File 'lib/protoform/dom.rb', line 22

def id
  lineage.map(&:key).join("_")
end

#inspectObject

Emit the id, name, and value in an HTML tag-ish that doesnt have an element.



41
42
43
# File 'lib/protoform/dom.rb', line 41

def inspect
  "<id=#{id.inspect} name=#{name.inspect} value=#{value.inspect}/>"
end

#nameObject

The ‘name` attribute of a node, which is influenced by Rails (not sure where Rails got it from). All node names, except the parent node, are wrapped in a `[]` and collections are left empty. For example, `user[][street]` would be created for a form with data shaped like `{addresses: [{street: “Sesame Street”]}}`.



31
32
33
34
35
36
37
# File 'lib/protoform/dom.rb', line 31

def name
  root, *names = keys
  names
    .map { |name| "[#{name}]" }
    .unshift(root)
    .join
end

#valueObject

Converts the value of the field to a String, which is required to work with Phlex. Assumes that ‘Object#to_s` emits a format suitable for the web form.



15
16
17
# File 'lib/protoform/dom.rb', line 15

def value
  @field.value.to_s
end