Class: Superform::DOM

Inherits:
Object
  • Object
show all
Defined in:
lib/superform.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.



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

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.



28
29
30
# File 'lib/superform.rb', line 28

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

#inspectObject

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



42
43
44
# File 'lib/superform.rb', line 42

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”]}}`.



36
37
38
39
# File 'lib/superform.rb', line 36

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.



21
22
23
# File 'lib/superform.rb', line 21

def value
  @field.value.to_s
end