Commit 25037d0f by liyijie

feat: 升级simple_controller 脚手架生成的代码

parent a701ca29
......@@ -154,9 +154,19 @@ class SimpleControllerGenerator < Rails::Generators::NamedBase
resource_class&.model_name&.collection
end
def attributes_names
# mod: 'all', 'only_json', 'without_json'
def attributes_names(mod: 'all')
begin
resource_class.columns.map(&:name) - %w(id created_at updated_at)
_attributes =
case mod.to_s
when 'only_json'
resource_class.columns.select { |column| column.type.in?([:json, :jsonb])}
when 'without_json'
resource_class.columns.select { |column| !column.type.in?([:json, :jsonb])}
else
resource_class.columns
end
_attributes.map(&:name) - %w(id created_at updated_at)
rescue NameError
[]
rescue
......@@ -164,6 +174,10 @@ class SimpleControllerGenerator < Rails::Generators::NamedBase
end
end
def belongs_to_refs
resource_class.reflections.values.select { |ref| ref.belongs_to? && !ref.polymorphic? }
end
def filename_with_extensions(name)
[name, :json, :jbuilder] * '.'
end
......@@ -173,6 +187,10 @@ class SimpleControllerGenerator < Rails::Generators::NamedBase
end
def attributes_list(attributes = attributes_names)
attributes.map { |a| ":#{a}"} * ', '
attributes.map { |a| ":#{a}"} * ", "
end
def json_attributes_list(attributes = attributes_names(mod: :only_json))
attributes.map { |a| "#{a}: {}" } * ", "
end
end
......@@ -10,9 +10,15 @@ class <%= controller_class_name %>Controller < SimpleController::BaseController
<% end -%>
private
def <%= resource_singular %>_params
params.require(:<%= resource_singular %>).permit(
<%= attributes_list(attributes_names) %>
<%- attributes_names(mod: :without_json).each do |attribute_name| -%>
:<%= attribute_name %>,
<%- end -%>
<%- attributes_names(mod: :only_json).each do |attribute_name| -%>
<%= attribute_name %>: {},
<%- end -%>
)
end
end
json.partial! "simple", <%= resource_singular %>: <%= resource_singular %>
json.partial! "<%= view_path %>/simple", <%= resource_singular %>: <%= resource_singular %>
json.partial! "single", <%= resource_singular %>: <%= resource_singular %>
json.partial! "<%= view_path %>/single", <%= resource_singular %>: <%= resource_singular %>
<%- belongs_to_refs.each do |ref| -%>
json.<%= ref.name.to_s %> <%= resource_singular %>.<%= ref.name.to_s %>, partial: '<%= File.join(ref.klass.name.underscore.pluralize, 'single') %>', as: :<%= ref.name %>
<%- end -%>
json.extract! <%= resource_singular %>, <%= attributes_list_with_timestamps %>
json.extract!(
<%= resource_singular %>,
:id,
:created_at,
:updated_at,
<%- attributes_names.each do |attribute_name| -%>
:<%= attribute_name %>,
<%- end -%>
)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment