mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 07:16:49 +00:00
Add generators.
This seemed like the easiest place to start.
This commit is contained in:
6
lib/generators/serializer/USAGE
Normal file
6
lib/generators/serializer/USAGE
Normal file
@@ -0,0 +1,6 @@
|
||||
Description:
|
||||
Generates a serializer for the given resource with tests.
|
||||
|
||||
Example:
|
||||
`rails generate serializer Account name created_at`
|
||||
|
||||
37
lib/generators/serializer/serializer_generator.rb
Normal file
37
lib/generators/serializer/serializer_generator.rb
Normal file
@@ -0,0 +1,37 @@
|
||||
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', File.join('app/serializers', class_path, "#{file_name}_serializer.rb")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def attributes_names
|
||||
[:id] + attributes.select { |attr| !attr.reference? }.map { |a| a.name.to_sym }
|
||||
end
|
||||
|
||||
def association_names
|
||||
attributes.select { |attr| attr.reference? }.map { |a| a.name.to_sym }
|
||||
end
|
||||
|
||||
def parent_class_name
|
||||
if options[:parent]
|
||||
options[:parent]
|
||||
elsif defined?(::ApplicationSerializer)
|
||||
"ApplicationSerializer"
|
||||
else
|
||||
"ActiveModel::Serializer"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
8
lib/generators/serializer/templates/serializer.rb
Normal file
8
lib/generators/serializer/templates/serializer.rb
Normal file
@@ -0,0 +1,8 @@
|
||||
<% module_namespacing do -%>
|
||||
class <%= class_name %>Serializer < <%= parent_class_name %>
|
||||
attributes <%= attributes_names.map(&:inspect).join(", ") %>
|
||||
end
|
||||
<% association_names.each do |attribute| -%>
|
||||
has_one :<%= attribute %>
|
||||
<% end -%>
|
||||
<% end -%>
|
||||
Reference in New Issue
Block a user