Class: Formalist::Form::Result::Field

Inherits:
Object
  • Object
show all
Defined in:
lib/formalist/form/result/field.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(definition, input, rules, errors) ⇒ Field

Returns a new instance of Field.



10
11
12
13
14
15
16
17
18
19
# File 'lib/formalist/form/result/field.rb', line 10

def initialize(definition, input, rules, errors)
  rules_compiler = Validation::ValueRulesCompiler.new(definition.name)
  predicates_compiler = Validation::PredicateListCompiler.new

  @definition = definition
  @input = input[definition.name]
  @rules = rules_compiler.(rules)
  @predicates = predicates_compiler.(@rules)
  @errors = errors[definition.name].to_a[0] || []
end

Instance Attribute Details

#definition ⇒ Object (readonly)

Returns the value of attribute definition.



8
9
10
# File 'lib/formalist/form/result/field.rb', line 8

def definition
  @definition
end

#errors ⇒ Object (readonly)

Returns the value of attribute errors.



8
9
10
# File 'lib/formalist/form/result/field.rb', line 8

def errors
  @errors
end

#input ⇒ Object (readonly)

Returns the value of attribute input.



8
9
10
# File 'lib/formalist/form/result/field.rb', line 8

def input
  @input
end

#predicates ⇒ Object (readonly)

Returns the value of attribute predicates.



8
9
10
# File 'lib/formalist/form/result/field.rb', line 8

def predicates
  @predicates
end

#rules ⇒ Object (readonly)

Returns the value of attribute rules.



8
9
10
# File 'lib/formalist/form/result/field.rb', line 8

def rules
  @rules
end

Instance Method Details

#to_ast ⇒ Array

Converts the field into an array format for including in a form's abstract syntax tree.

The array takes the following format:

[:field, [params]]

With the following parameters:

  1. Field name
  2. Field type
  3. Display variant name
  4. Input data
  5. Validation rules (if any)
  6. Validation error messages (if any)
  7. Field configuration

Examples:

"email" field

field.to_ast # =>
# [:field, [
#   :email,
#   "string",
#   "default",
#   "invalid email value",
#   [
#     [:and, [
#       [:predicate, [:filled?, []]],
#       [:predicate, [:format?, [/\s+@\s+\.\s+/]]]
#     ]]
#   ],
#   ["email is in invalid format"],
#   [
#     [:some_config_name, :some_config_value]
#   ]
# ]]

Returns:

  • (Array) —

    the field as an array.



60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/formalist/form/result/field.rb', line 60

def to_ast
  # errors looks like this
  # {:field_name => [["pages is missing", "another error message"], nil]}

  [:field, [
    definition.name,
    definition.type,
    definition.display_variant,
    input,
    predicates,
    errors,
    definition.config.to_a,
  ]]
end