Sha256: f137fc4a28c33e08d20c53804d14d0629ab048aae253f016f64bcbedf8371b53

Contents?: true

Size: 1.08 KB

Versions: 2

Compression:

Stored size: 1.08 KB

Contents

module Strain
  class Article < ActiveRecord::Base
    belongs_to :variant, inverse_of: :articles

    self.inheritance_column = :strain_type

    delegate :schema, to: :variant
    delegate :name, to: :variant, prefix: true

    before_validation :set_defaults_from_schema

    validates_presence_of :slug, :variant, :body, :title
    validates :slug, format: {
      with: /\A[a-z0-9-]+\z/,
      message: "must contain only letters, numbers, and hyphens."}
    validates :slug, uniqueness: { case_sensitive: false }
    validate :body_must_conform_to_variant_schema

    private

    def set_defaults_from_schema
      return if variant.nil?
      return if body.nil?
      return if title.nil?
      self.body = Strain::SchemaTools::Defaults.new(schema, body).data_with_defaults
    end

    def body_must_conform_to_variant_schema
      return if variant.nil?
      # JSON::Validator.fully_validate(schema, body.to_h, errors_as_objects: true)
      unless JSON::Validator.validate(schema, body.to_h)
        errors.add(:body, "does not conform to #{variant.name} schema.")
      end
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
strain-0.0.2 app/models/strain/article.rb
strain-0.0.1 app/models/strain/article.rb