Module: Customizable

Overview

This module provides tools to use customs fields and expect model has a column custom_fields (with JSONB type) TODO manage date types

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#custom_value(field) ⇒ Object

Returns the value of given custom_field


15
16
17
18
# File 'app/models/concerns/customizable.rb', line 15

def custom_value(field)
  return nil unless custom_fields
  custom_fields[field.column_name]
end

#set_custom_value(field, value) ⇒ Object


20
21
22
23
# File 'app/models/concerns/customizable.rb', line 20

def set_custom_value(field, value)
  self.custom_fields ||= {}
  self.custom_fields[field.column_name] = value
end

#validate_custom_fieldsObject


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'app/models/concerns/customizable.rb', line 25

def validate_custom_fields
  self.class.custom_fields.each do |custom_field|
    value = custom_value(custom_field)
    if value.blank?
      errors.add(:custom_fields, :blank, attribute: custom_field.name) if custom_field.required?
    else
      if custom_field.text?
        unless custom_field.maximal_length.blank? || custom_field.maximal_length <= 0
          errors.add(:custom_fields, :too_long, attribute: custom_field.name, count: custom_field.maximal_length) if value.length > custom_field.maximal_length
        end
        unless custom_field.minimal_length.blank? || custom_field.minimal_length <= 0
          errors.add(:custom_fields, :too_short, attribute: custom_field.name, count: custom_field.maximal_length) if value.length < custom_field.minimal_length
        end
      elsif custom_field.decimal?
        value = value.to_d unless value.is_a?(Numeric)
        if custom_field.minimal_value.present?
          errors.add(:custom_fields, :greater_than, attribute: custom_field.name, count: custom_field.minimal_value) if value < custom_field.minimal_value
        end
        if custom_field.maximal_value.present?
          errors.add(:custom_fields, :less_than, attribute: custom_field.name, count: custom_field.maximal_value) if value > custom_field.maximal_value
        end
      end
    end
  end
end