Class: HasCustomFields::FieldDescriptor

Inherits:
Struct
  • Object
show all
Defined in:
app/models/concerns/has_custom_fields.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#max_lengthObject

Returns the value of attribute max_length

Returns:

  • (Object)

    the current value of max_length



10
11
12
# File 'app/models/concerns/has_custom_fields.rb', line 10

def max_length
  @max_length
end

#typeObject

Returns the value of attribute type

Returns:

  • (Object)

    the current value of type



10
11
12
# File 'app/models/concerns/has_custom_fields.rb', line 10

def type
  @type
end

Instance Method Details

#append_field(target, key, value) ⇒ Object



11
12
13
14
15
16
17
18
# File 'app/models/concerns/has_custom_fields.rb', line 11

def append_field(target, key, value)
  if target.has_key?(key)
    target[key] = [target[key]] if !target[key].is_a? Array
    target[key] << deserialize(key, value, false)
  else
    target[key] = deserialize(key, value, true)
  end
end

#array_type?Boolean

Returns:

  • (Boolean)


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

def array_type?
  Array === type
end

#deserialize(key, value, return_array) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'app/models/concerns/has_custom_fields.rb', line 61

def deserialize(key, value, return_array)
  return value unless type = self.type

  array = nil

  if array_type?
    type = type[0]
    array = true if return_array
  end

  result =
    case type
    when :boolean
      !!Helpers::CUSTOM_FIELD_TRUE.include?(value)
    when :integer
      value.to_i
    when :json
      parse_json_value(value, key)
    else
      value
    end

  array ? [result] : result
end

#serialize(value) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'app/models/concerns/has_custom_fields.rb', line 35

def serialize(value)
  base_type = Array === type ? type.first : type

  case base_type
  when :json
    value.to_json
  when :integer
    value.to_i.to_s
  when :boolean
    value = !!Helpers::CUSTOM_FIELD_TRUE.include?(value) if String === value

    value ? "t" : "f"
  else
    case value
    when Hash
      value.to_json
    when TrueClass
      "t"
    when FalseClass
      "f"
    else
      value.to_s
    end
  end
end

#validate(obj, name, value) ⇒ Object



24
25
26
27
28
29
30
31
32
33
# File 'app/models/concerns/has_custom_fields.rb', line 24

def validate(obj, name, value)
  return if value.nil?

  if serialize(value).bytesize > max_length
    obj.errors.add(
      :base,
      I18n.t("custom_fields.validations.max_value_length", max_value_length: max_length),
    )
  end
end