Class: GovukSchemas::RandomExample

Inherits:
Object
  • Object
show all
Defined in:
lib/govuk_schemas/random_example.rb

Class Method Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (GovukSchemas::RandomExample) initialize(schema:)

Returns a new GovukSchemas::RandomExample object.

For example:

schema = GovukSchemas::Schema.find("detailed_guide", schema_type: "frontend")
GovukSchemas::RandomExample.new(schema).payload

Parameters:

  • schema (Hash)

    A JSON schema.



17
18
19
20
# File 'lib/govuk_schemas/random_example.rb', line 17

def initialize(schema:)
  @schema = schema
  @random_generator = RandomItemGenerator.new(schema: schema)
end

Class Method Details

+ (GovukSchemas::RandomExample) for_schema(schema_name, schema_type:)

Returns a new GovukSchemas::RandomExample object.

For example:

generator = GovukSchemas::RandomExample.for_schema("detailed_guide", schema_type: "frontend")
generator.payload
# => {"base_path"=>"/e42dd28e", "title"=>"dolor est...", "publishing_app"=>"elit"...}


31
32
33
34
# File 'lib/govuk_schemas/random_example.rb', line 31

def self.for_schema(schema_name, schema_type:)
  schema = GovukSchemas::Schema.find(schema_name, schema_type: schema_type)
  GovukSchemas::RandomExample.new(schema: schema)
end

Instance Method Details

- (Hash) merge_and_validate(hash)

Return a content item merged with a hash. If the resulting content item isn't valid against the schema an error will be raised.

Example:

 random = GovukSchemas::RandomExample.for_schema("detailed_guide", schema_type: "frontend")
 random.merge_and_validate(base_path: "/foo")
 # => {"base_path"=>"/e42dd28e", "title"=>"dolor est...", "publishing_app"=>"elit"...}

Parameters:

  • hash (Hash)

    The hash to merge the random content with

Returns:

  • (Hash)

    A content item

Raises:

  • (GovukSchemas::InvalidContentGenerated)


67
68
69
70
71
72
73
74
75
76
# File 'lib/govuk_schemas/random_example.rb', line 67

def merge_and_validate(hash)
  item = payload.merge(Utils.stringify_keys(hash))
  errors = validation_errors_for(item)

  if errors.any?
    raise InvalidContentGenerated, error_message_custom(item, errors)
  end

  item
end

- (Hash) payload

Return a hash with a random content item

Example:

GovukSchemas::RandomExample.for_schema("detailed_guide", schema_type: "frontend").payload
# => {"base_path"=>"/e42dd28e", "title"=>"dolor est...", "publishing_app"=>"elit"...}

Returns:

  • (Hash)

    A content item



44
45
46
47
48
49
50
51
52
53
# File 'lib/govuk_schemas/random_example.rb', line 44

def payload
  item = @random_generator.payload
  errors = validation_errors_for(item)

  if errors.any?
    raise InvalidContentGenerated, error_message(item, errors)
  end

  item
end