Class: ForestLiana::SerializerFactory

Inherits:
Object
  • Object
show all
Defined in:
app/serializers/forest_liana/serializer_factory.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(is_smart_collection = false) ⇒ SerializerFactory

Returns a new instance of SerializerFactory.



125
126
127
# File 'app/serializers/forest_liana/serializer_factory.rb', line 125

def initialize(is_smart_collection = false)
  @is_smart_collection = is_smart_collection
end

Class Method Details

.define_serializer(active_record_class, serializer) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
# File 'app/serializers/forest_liana/serializer_factory.rb', line 6

def self.define_serializer(active_record_class, serializer)
  serializer_name = self.build_serializer_name(active_record_class)

  if ForestLiana::UserSpace.const_defined?(serializer_name, false)
    ForestLiana::UserSpace.send(:remove_const, serializer_name)
  end

  # NOTICE: Create the serializer in the UserSpace to avoid conflicts with
  # serializer created from integrations, actions, segments, etc.
  ForestLiana::UserSpace.const_set(serializer_name, serializer)
end

.get_serializer_name(active_record_class) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'app/serializers/forest_liana/serializer_factory.rb', line 18

def self.get_serializer_name(active_record_class)
  if defined?(::Intercom::Conversation) &&
    active_record_class == ::Intercom::Conversation
    "ForestLiana::IntercomConversationSerializer"
  elsif defined?(::Intercom::User) &&
    active_record_class == ::Intercom::User
    "ForestLiana::IntercomAttributeSerializer"
  elsif defined?(::Stripe::Charge) &&
    active_record_class == ::Stripe::Charge
    "ForestLiana::StripePaymentSerializer"
  elsif defined?(::Stripe::Card) &&
    active_record_class == ::Stripe::Card
    "ForestLiana::StripeCardSerializer"
  elsif defined?(::Stripe::Invoice) &&
    active_record_class == ::Stripe::Invoice
    "ForestLiana::StripeInvoiceSerializer"
  elsif defined?(::Stripe::Subscription) &&
    active_record_class == ::Stripe::Subscription
    "ForestLiana::StripeSubscriptionSerializer"
  elsif defined?(::Stripe::BankAccount) &&
    active_record_class == ::Stripe::BankAccount
    "ForestLiana::StripeBankAccountSerializer"
  elsif active_record_class == ForestLiana::Model::Stat
    "ForestLiana::StatSerializer"
  elsif active_record_class == ForestLiana::MixpanelEvent
    "ForestLiana::MixpanelEventSerializer"
  else
    serializer_name = self.build_serializer_name(active_record_class)
    "ForestLiana::UserSpace::#{serializer_name}"
  end
end

Instance Method Details

#serializer_for(active_record_class) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'app/serializers/forest_liana/serializer_factory.rb', line 129

def serializer_for(active_record_class)
  serializer = Class.new {
    include ForestAdmin::JSONAPI::Serializer

    def self_link
      "/forest#{super.underscore}"
    end

    def type
      ForestLiana.name_for(object.class).demodulize
    end

    def format_name(attribute_name)
      attribute_name.to_s
    end

    def unformat_name(attribute_name)
      attribute_name.to_s
    end

    def relationship_self_link(attribute_name)
      nil
    end

    def relationship_related_link(attribute_name)
      ret = {}

      # Has many smart field
      current = self.has_many_relationships[attribute_name]
      if current.try(:[], :options).try(:[], :name) == attribute_name
        ret[:href] = "/forest/#{ForestLiana.name_for(object.class)}/#{object.id}/#{attribute_name}"
        return ret
      end

      if intercom_integration?
        case attribute_name
        when :intercom_conversations
          ret[:href] = "/forest/#{ForestLiana.name_for(object.class)}/#{object.id}/intercom_conversations"
        when :intercom_attributes
          ret[:href] = "/forest/#{ForestLiana.name_for(object.class)}/#{object.id}/intercom_attributes"
        end
      end

      if stripe_integration?
        case attribute_name
        when :stripe_payments
          ret[:href] = "/forest/#{ForestLiana.name_for(object.class)}/#{object.id}/stripe_payments"
        when :stripe_invoices
          ret[:href] = "/forest/#{ForestLiana.name_for(object.class)}/#{object.id}/stripe_invoices"
        when :stripe_cards
          ret[:href] = "/forest/#{ForestLiana.name_for(object.class)}/#{object.id}/stripe_cards"
        when :stripe_subscriptions
          ret[:href] = "/forest/#{ForestLiana.name_for(object.class)}/#{object.id}/stripe_subscriptions"
        when :stripe_bank_accounts
          ret[:href] = "/forest/#{ForestLiana.name_for(object.class)}/#{object.id}/stripe_bank_accounts"
        end
      end

      if mixpanel_integration?
        case attribute_name
        when :mixpanel_last_events
          ret[:href] = "/forest/#{ForestLiana.name_for(object.class)}/#{object.id}/mixpanel_last_events"
        end
      end

      if ret[:href].blank?
        begin
          SchemaUtils.many_associations(object.class).each do |a|
            if a.name == attribute_name
              ret[:href] = "/forest/#{ForestLiana.name_for(object.class)}/#{object.id}/relationships/#{attribute_name}"
            end
          end
        rescue TypeError, ActiveRecord::StatementInvalid, NoMethodError => exception
          FOREST_LOGGER.warn "Cannot load the association #{attribute_name} on #{object.class.name} #{object.id}.\n#{exception&.backtrace&.join("\n\t")}"
        end
      end

      ret
    end

    def has_one_relationships
      return {} if self.class.to_one_associations.nil?
      data = {}
      self.class.to_one_associations.each do |attribute_name, attr_data|
        relation = object.class.reflect_on_all_associations.find { |a| a.name == attribute_name }
        next if !should_include_attr?(attribute_name, attr_data)

        if relation && relation.belongs_to? && relation.polymorphic?.nil?
          reflection_primary_key = relation.options[:primary_key]&.to_sym || :id
          klass_primary_key = relation.klass.primary_key.to_sym

          if reflection_primary_key != klass_primary_key
            data[attribute_name] = attr_data.merge({
                                                     attr_or_block: proc {
                                                       relation.klass.find_by(reflection_primary_key => object.send(relation.foreign_key))
                                                     }
                                                   })
            next
          end
        end

        data[attribute_name] = attr_data
      end

      data
    end

    def should_include_attr?(attribute_name, attr_data)
      collection = self.type

      unless @options.dig(:context, :unoptimized)
        return false unless @options[:fields][collection]&.include?(attribute_name.to_sym)
      end

      # Allow "if: :show_title?" and "unless: :hide_title?" attribute options.
      if_method_name = attr_data[:options][:if]
      unless_method_name = attr_data[:options][:unless]
      formatted_attribute_name = format_name(attribute_name).to_sym
      show_attr = true
      show_attr &&= send(if_method_name) if if_method_name
      show_attr &&= !send(unless_method_name) if unless_method_name
      show_attr &&= @_fields[type.to_s].include?(formatted_attribute_name) if @_fields[type.to_s]
      show_attr
    end

    private

    def intercom_integration?
      ForestLiana.integrations
        .try(:[], :intercom)
        .try(:[], :mapping)
        .try(:include?, object.class.name)
    end

    def stripe_integration?
      mapping = ForestLiana.integrations
        .try(:[], :stripe)
        .try(:[], :mapping)

      if mapping
        collection_names = mapping.map do |collection_name_and_field|
          collection_name_and_field.split('.')[0]
        end
        collection_names.include?(object.class.name)
      else
        false
      end
    end

    def mixpanel_integration?
      mapping = ForestLiana.integrations
        .try(:[], :mixpanel)
        .try(:[], :mapping)

      if mapping
        collection_names = mapping.map do |collection_name_and_field|
          collection_name_and_field.split('.')[0]
        end
        collection_names.include?(object.class.name)
      else
        false
      end
    end
  }

  unless @is_smart_collection
    attributes(active_record_class).each do |attribute|
      serializer.attribute(attribute) do |x|
        begin
          object.send(attribute)
        rescue
          nil
        end
      end
    end

    # NOTICE: Format time type fields during the serialization.
    attributes_time(active_record_class).each do |attribute|
      serializer.attribute(attribute) do |x|
        begin
          value = object.send(attribute)
          if value
            match = /(\d{2}:\d{2}:\d{2})/.match(value.to_s)
            (match && match[1]) ? match[1] : nil
          else
            nil
          end
        rescue
          nil
        end
      end
    end

    # NOTICE: Format serialized fields.
    attributes_serialized(active_record_class).each do |attr, serialization|
      serializer.attribute(attr) do |x|
        begin
          value = object.send(attr)
          value ? value.to_json : nil
        rescue
          nil
        end
      end
    end

    # NOTICE: Format CarrierWave url attribute
    if active_record_class.respond_to?(:mount_uploader)
      active_record_class.uploaders.each do |key, value|
        serializer.attribute(key) do |x|
          begin
            object.send(key).try(:url)
          rescue
            nil
          end
        end
      end
    end

    # NOTICE: Format Paperclip url attribute
    if active_record_class.respond_to?(:attachment_definitions)
      active_record_class.attachment_definitions.each do |key, value|
        serializer.attribute(key) do |x|
          begin
            object.send(key)
          rescue
            nil
          end
        end
      end
    end

    # NOTICE: Format ActsAsTaggable attribute
    if active_record_class.try(:taggable?) &&
      active_record_class.respond_to?(:acts_as_taggable) &&
      active_record_class.acts_as_taggable.respond_to?(:to_a)
      active_record_class.acts_as_taggable.to_a.each do |key, value|
        serializer.attribute(key) do |x|
          begin
            object.send(key).map(&:name)
          rescue
            nil
          end
        end
      end
    end

    # NOTICE: Format Devise attributes
    if active_record_class.respond_to?(:devise_modules?)
      serializer.attribute('password') do |x|
        '**********'
      end
    end

    SchemaUtils.associations(active_record_class).each do |a|
      begin
        if SchemaUtils.polymorphic?(a)
          serializer.send(serializer_association(a), a.name) {
            if [:has_one, :belongs_to].include?(a.macro)
              begin
                object.send(a.name)
              rescue ActiveRecord::RecordNotFound
                nil
              end
            else
              []
            end
          }
        elsif SchemaUtils.model_included?(a.klass)
          serializer.send(serializer_association(a), a.name) {
            if [:has_one, :belongs_to].include?(a.macro)
              begin
                object.send(a.name)
              rescue ActiveRecord::RecordNotFound
                nil
              end
            else
              []
            end
          }
        end
      rescue NameError
        # NOTICE: Let this error silent, a bad association warning will be
        # displayed in the schema adapter.
      end
    end
  end

  # Intercom
  if has_intercom_integration?(active_record_class.name)
    serializer.send(:has_many, :intercom_conversations) { }
    serializer.send(:has_many, :intercom_attributes) { }
  end

  # Stripe
  if has_stripe_integration?(active_record_class.name)
    serializer.send(:has_many, :stripe_payments) { }
    serializer.send(:has_many, :stripe_invoices) { }
    serializer.send(:has_many, :stripe_cards) { }
    serializer.send(:has_many, :stripe_subscriptions) { }
    serializer.send(:has_many, :stripe_bank_accounts) { }
  end

  # Mixpanel
  if has_mixpanel_integration?(active_record_class.name)
    serializer.send(:has_many, :mixpanel_last_events) { }
  end

  ForestLiana::SerializerFactory.define_serializer(active_record_class, serializer)

  serializer
end