Module: StandardAPI::Helpers

Defined in:
lib/standard_api/helpers.rb

Instance Method Summary collapse

Instance Method Details

#association_cache_key(record, relation, subincludes) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/standard_api/helpers.rb', line 93

def association_cache_key(record, relation, subincludes)
  timestamp = ["#{relation}_cached_at"] + cached_at_columns_for_includes(subincludes).map {|c| "#{relation}_#{c}"}
  timestamp = (timestamp & record.class.column_names).map! { |col| record.send(col) }
  timestamp = timestamp.max

  case association = record.class.reflect_on_association(relation)
  when ActiveRecord::Reflection::HasManyReflection, ActiveRecord::Reflection::HasAndBelongsToManyReflection, ActiveRecord::Reflection::HasOneReflection, ActiveRecord::Reflection::ThroughReflection
    "#{record.model_name.cache_key}/#{record.id}/#{includes_to_cache_key(relation, subincludes)}-#{timestamp.utc.to_s(record.cache_timestamp_format)}"
  when ActiveRecord::Reflection::BelongsToReflection
    klass = association.options[:polymorphic] ? record.send(association.foreign_type).constantize : association.klass
    if subincludes.empty?
      "#{klass.model_name.cache_key}/#{record.send(association.foreign_key)}-#{timestamp.utc.to_s(klass.cache_timestamp_format)}"
    else
      "#{klass.model_name.cache_key}/#{record.send(association.foreign_key)}/#{digest_hash(sort_hash(subincludes))}-#{timestamp.utc.to_s(klass.cache_timestamp_format)}"
    end
  else
    raise ArgumentError, 'Unkown association type'
  end
end

#cache_key(record, includes) ⇒ Object



73
74
75
76
77
78
79
80
81
# File 'lib/standard_api/helpers.rb', line 73

def cache_key(record, includes)
  timestamp_keys = ['cached_at'] + record.class.column_names.select{|x| x.ends_with? "_cached_at"}
  if includes.empty?
    record.cache_key(*timestamp_keys)
  else
    timestamp = timestamp_keys.map { |attr| record[attr]&.to_time }.compact.max
    "#{record.model_name.cache_key}/#{record.id}-#{digest_hash(sort_hash(includes))}-#{timestamp.utc.to_s(record.cache_timestamp_format)}"
  end
end

#cached_at_columns_for_includes(includes) ⇒ Object



113
114
115
116
117
# File 'lib/standard_api/helpers.rb', line 113

def cached_at_columns_for_includes(includes)
  includes.select { |k,v| !['when', 'where', 'limit', 'order', 'distinct', 'distinct_on'].include?(k) }.map do |k, v|
    ["#{k}_cached_at"] + cached_at_columns_for_includes(v).map { |v2| "#{k}_#{v2}" }
  end.flatten
end

#can_cache?(klass, includes) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
67
68
69
70
71
# File 'lib/standard_api/helpers.rb', line 64

def can_cache?(klass, includes)
  cache_columns = ['cached_at'] + cached_at_columns_for_includes(includes)
  if (cache_columns - klass.column_names).empty?
    true
  else
    false
  end
end

#can_cache_relation?(record, relation, subincludes) ⇒ Boolean

Returns:

  • (Boolean)


83
84
85
86
87
88
89
90
91
# File 'lib/standard_api/helpers.rb', line 83

def can_cache_relation?(record, relation, subincludes)
  return false if record.new_record?
  cache_columns = ["#{relation}_cached_at"] + cached_at_columns_for_includes(subincludes).map {|c| "#{relation}_#{c}"}
  if (cache_columns - record.class.column_names).empty?
    true
  else
    false
  end
end

#digest_hash(*hashes) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/standard_api/helpers.rb', line 138

def digest_hash(*hashes)
  hashes.compact!
  hashes.map! { |h| sort_hash(h) }

  digest =  Digest::MD5.new()
  hashes.each do |hash|
    hash.each do |key, value|
      digest << key.to_s
      if value.is_a?(Hash)
        digest << digest_hash(value)
      else
        digest << value.to_s
      end
    end
  end

  digest.hexdigest
end

#includes_to_cache_key(relation, subincludes) ⇒ Object



119
120
121
122
123
124
125
# File 'lib/standard_api/helpers.rb', line 119

def includes_to_cache_key(relation, subincludes)
  if subincludes.empty?
    relation.to_s
  else
    "#{relation}-#{digest_hash(sort_hash(subincludes))}"
  end
end

#json_column_type(sql_type) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/standard_api/helpers.rb', line 157

def json_column_type(sql_type)
  case sql_type
  when 'timestamp without time zone'
    'datetime'
  when 'time without time zone'
    'datetime'
  when 'text'
    'string'
  when 'json'
    'hash'
  when 'bigint'
    'integer'
  when 'integer'
    'integer'
  when 'jsonb'
    'hash'
  when 'inet'
    'string' # TODO: should be inet
  when 'hstore'
    'hash'
  when 'date'
    'datetime'
  when /numeric(\(\d+(,\d+)?\))?/
    'decimal'
  when 'double precision'
    'decimal'
  when 'ltree'
   'string'
  when 'boolean'
    'boolean'
  when 'uuid' # TODO: should be uuid
    'string'
  when /character varying(\(\d+\))?/
    'string'
  when /^geometry/
    'ewkb'
  end
end

#model_partial(record) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/standard_api/helpers.rb', line 56

def model_partial(record)
  if lookup_context.exists?(record.model_name.element, record.model_name.plural, true)
    [record.model_name.plural, record.model_name.element].join('/')
  else
    'application/record'
  end
end

#preloadables(record, includes) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/standard_api/helpers.rb', line 4

def preloadables(record, includes)
  preloads = {}

  includes.each do |key, value|
    if reflection = record.klass.reflections[key]
      case value
      when true
        preloads[key] = value
      when Hash, ActiveSupport::HashWithIndifferentAccess
        if !value.keys.any? { |x| ['when', 'where', 'limit', 'offset', 'order', 'distinct'].include?(x) }
          if !reflection.polymorphic?
            preloads[key] = preloadables_hash(reflection.klass, value)
          end
        end
      end
    end
  end

  preloads.empty? ? record : record.preload(preloads)
end

#preloadables_hash(klass, iclds) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/standard_api/helpers.rb', line 25

def preloadables_hash(klass, iclds)
  preloads = {}

  iclds.each do |key, value|
    if reflection = klass.reflections[key]
      case value
      when true
        preloads[key] = value
      when Hash, ActiveSupport::HashWithIndifferentAccess
        if !value.keys.any? { |x| ['when', 'where', 'limit', 'offset', 'order', 'distinct'].include?(x) }
          if !reflection.polymorphic?
            preloads[key] = preloadables_hash(reflection.klass, value)
          end
        end
      end
    end
  end

  preloads
end

#schema_partial(model) ⇒ Object



46
47
48
49
50
51
52
53
54
# File 'lib/standard_api/helpers.rb', line 46

def schema_partial(model)
  path = model.model_name.plural

  if lookup_context.exists?("schema", path, true)
    [path, "schema"].join('/')
  else
    'application/schema'
  end
end

#sort_hash(hash) ⇒ Object



127
128
129
130
131
132
133
134
135
136
# File 'lib/standard_api/helpers.rb', line 127

def sort_hash(hash)
  hash.keys.sort.reduce({}) do |seed, key|
    if seed[key].is_a?(Hash)
      seed[key] = sort_hash(hash[key])
    else
      seed[key] = hash[key]
    end
    seed
  end
end