Module: HasCustomFields::Helpers

Defined in:
app/models/concerns/has_custom_fields.rb

Class Method Summary collapse

Class Method Details

.append_field(target, key, value, types) ⇒ Object



7
8
9
10
11
12
13
14
# File 'app/models/concerns/has_custom_fields.rb', line 7

def self.append_field(target, key, value, types)
  if target.has_key?(key)
    target[key] = [target[key]] if !target[key].is_a? Array
    target[key] << cast_custom_field(key, value, types, _return_array = false)
  else
    target[key] = cast_custom_field(key, value, types)
  end
end

.cast_custom_field(key, value, types, return_array = true) ⇒ Object



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

def self.cast_custom_field(key, value, types, return_array = true)
  return value unless type = get_custom_field_type(types, key)

  array = nil

  if Array === type
    type = type[0]
    array = true if return_array
  end

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

  array ? [result] : result
end

.get_custom_field_type(types, key) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'app/models/concerns/has_custom_fields.rb', line 18

def self.get_custom_field_type(types, key)
  return unless types

  sorted_types = types.keys.select { |k| k.end_with?("*") }.sort_by(&:length).reverse

  sorted_types.each { |t| return types[t] if key =~ /\A#{t}/i }

  types[key]
end

.parse_json_value(value, key) ⇒ Object



53
54
55
56
57
58
59
60
# File 'app/models/concerns/has_custom_fields.rb', line 53

def self.parse_json_value(value, key)
  ::JSON.parse(value)
rescue JSON::ParserError
  Rails.logger.warn(
    "Value '#{value}' for custom field '#{key}' is not json, it is being ignored.",
  )
  {}
end