Sha256: 079c74a0572071d4d8009f456edbf65305d08bf520f4cbcdf5a6156f14c62a1f

Contents?: true

Size: 1.26 KB

Versions: 1

Compression:

Stored size: 1.26 KB

Contents

class TextFieldType < FieldType
  attr_accessor :text
  jsonb_accessor :data, text: :string

  validates :text, presence: true, if: :validate_presence?
  validate :text_length, if: :validate_length?
  validate :text_unique, if: :validate_uniqueness?

  def data=(data_hash)
    @text = data_hash.deep_symbolize_keys[:text]
  end

  def field_item_as_indexed_json_for_field_type(field_item, options = {})
    json = {}
    json[mapping_field_name] = field_item.data['text']
    json
  end

  def mapping
    {name: mapping_field_name, type: :string, analyzer: :snowball}
  end

  private

  def mapping_field_name
    "#{field_name.parameterize(separator: '_')}_text"
  end

  def text_length
    validator = LengthValidator.new(validations[:length].merge(attributes: [:text]))
    validator.validate_each(self, :text, text)
  end

  def text_unique
    # TODO: This breaks when you try to update existing text
    unless metadata[:existing_data][:text] == text || field.field_items.jsonb_contains(:data, text: text).empty?
      errors.add(:text, "#{field.name} Must be unique")
    end
  end

  def validate_uniqueness?
    @validations.key? :uniqueness
  end

  def validate_presence?
    @validations.key? :presence
  end

  def validate_length?
    @validations.key? :length
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
cortex-plugins-core-0.12.4 app/models/text_field_type.rb