Module: WCC::Contentful::ModelValidators

Included in:
Model
Defined in:
lib/wcc/contentful/model_validators.rb,
lib/wcc/contentful/model_validators/dsl.rb

Defined Under Namespace

Classes: FieldDsl, ProcDsl

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.transform_content_types_for_validation(content_types) ⇒ Object

Accepts a content types response from the API and transforms it to be acceptible for the validator.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/wcc/contentful/model_validators.rb', line 48

def self.transform_content_types_for_validation(content_types)
  if !content_types.is_a?(Array) && items = content_types.try(:[], 'items')
    content_types = items
  end

  # Transform the array into a hash keyed by content type ID
  content_types.each_with_object({}) do |ct, ct_hash|
    # Transform the fields into a hash keyed by field ID
    ct['fields'] =
      ct['fields'].each_with_object({}) do |f, f_hash|
        f_hash[f['id']] = f
      end

    ct_hash[ct.dig('sys', 'id')] = ct
  end
end

Instance Method Details

#schemaObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/wcc/contentful/model_validators.rb', line 8

def schema
  return if @field_validations.nil? || @field_validations.empty?
  field_validations = @field_validations

  # "page": {
  #   "sys": { ... }
  #   "fields": {
  #     "title": { ... },
  #     "sections": { ... },
  #     ...
  #   }
  # }

  fields_schema =
    Dry::Validation.Schema do
      # Had to dig through the internals of Dry::Validation to find
      # this magic incantation
      field_validations.each { |dsl| instance_eval(&dsl.to_proc) }
    end

  Dry::Validation.Schema do
    required('fields').schema(fields_schema)
  end
end

#validate_field(field, type, *options) ⇒ Object



40
41
42
43
44
# File 'lib/wcc/contentful/model_validators.rb', line 40

def validate_field(field, type, *options)
  dsl = FieldDsl.new(field, type, options)

  (@field_validations ||= []) << dsl
end

#validate_fields(&block) ⇒ Object

Raises:

  • (ArgumentError)


33
34
35
36
37
38
# File 'lib/wcc/contentful/model_validators.rb', line 33

def validate_fields(&block)
  raise ArgumentError, 'validate_fields requires a block' unless block_given?
  dsl = ProcDsl.new(Proc.new(&block))

  (@field_validations ||= []) << dsl
end