File: serializer_generator.rb

package info (click to toggle)
ruby-active-model-serializers 0.10.12-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,752 kB
  • sloc: ruby: 13,138; sh: 53; makefile: 6
file content (38 lines) | stat: -rw-r--r-- 1,051 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# frozen_string_literal: true

module Rails
  module Generators
    class SerializerGenerator < NamedBase
      source_root File.expand_path('../templates', __FILE__)
      check_class_collision suffix: 'Serializer'

      argument :attributes, type: :array, default: [], banner: 'field:type field:type'

      class_option :parent, type: :string, desc: 'The parent class for the generated serializer'

      def create_serializer_file
        template 'serializer.rb.erb', File.join('app/serializers', class_path, "#{file_name}_serializer.rb")
      end

      private

      def attributes_names
        [:id] + attributes.reject(&:reference?).map! { |a| a.name.to_sym }
      end

      def association_names
        attributes.select(&:reference?).map! { |a| a.name.to_sym }
      end

      def parent_class_name
        if options[:parent]
          options[:parent]
        elsif 'ApplicationSerializer'.safe_constantize
          'ApplicationSerializer'
        else
          'ActiveModel::Serializer'
        end
      end
    end
  end
end