Module: Formalist::Element::ClassInterface

Included in:
Formalist::Element
Defined in:
lib/formalist/element/class_interface.rb

Overview

Class-level API for form elements.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.attribute(name, type, default: nil) ⇒ Object

Define a form element attribute.

Form element attributes can be set when the element is defined, and can be further populated by the form element object itself, when the form is being built, using both the user input and any dependencies passed to the element via the form.

Attributes are the way to ensure the form renderer has all the information it needs to render the element appropriately. Attributes are type-checked in order to ensure they're being passed appropriate values. Attributes can hold any type of value as long as it can be reduced to an abstract syntax tree representation by Form::Element::Attributes#to_ast.

Parameters:

  • name (Symbol)

    attribute name

  • type (Dry::Data::Type, #call)

    value type coercer/checker

  • default (defaults to: nil)

    default value (applied when the attribute is not explicitly populated)

Returns:

  • void

See Also:



46
47
48
# File 'lib/formalist/element/class_interface.rb', line 46

def attribute(name, type, default: nil)
  attributes(name => {type: type, default: default})
end

.attributes_schemaHash<Symbol, Hash>

Returns the attributes schema for the form element.

Each item in the schema includes a type definition and a default value (nil if none specified).

Examples:

Formalist::Elements::Field.attributes_schema
# => {
  :name => {:type => #<Dry::Data::Type>, :default => "Default name"},
  :email => {:type => #<Dry::Data::Type>, :default => "default email"}
}

Returns:

  • (Hash<Symbol, Hash>)

    the attributes schema



64
65
66
67
# File 'lib/formalist/element/class_interface.rb', line 64

def attributes_schema
  super_schema = superclass.respond_to?(:attributes_schema) ? superclass.attributes_schema : {}
  super_schema.merge(@attributes_schema || {})
end

Instance Method Details

#typeObject

Returns the element's type, which is a symbolized, underscored representation of the element's class name.

This is important for form rendering when using custom form elements, since the type in this case will be based on the name of form element's sublass.

Examples:

Basic element Formalist::Elements::Field.type # => :field


Custom element class MyField < Formalist::Elements::Field end


MyField.type # => :my_field


21
22
23
# File 'lib/formalist/element/class_interface.rb', line 21

def type
  Inflecto.underscore(Inflecto.demodulize(name)).to_sym
end