Last active
September 16, 2017 12:28
-
-
Save studioTeaTwo/799fdae46c5e22bb8a8169352eda2846 to your computer and use it in GitHub Desktop.
rake task to generate json shema document for swaggard from ActiveRecord Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
namespace :json_params do | |
desc "create the definitions of json params" | |
task :generate => :environment do | |
# Custom Definitions | |
create('Session', "#{Rails.root}/app/controllers/params/session.rb", | |
nil, | |
{email: 'string', password: 'string'} | |
) | |
# ActiveRecord Object | |
create(Chat, "#{Rails.root}/app/controllers/params/chat.rb", | |
[:id, :user_id, :created_at, :updated_at], | |
{item_list: 'hash'} | |
) | |
end | |
private | |
def create(object, file_path, exclusion_list, special_case_list=nil) | |
val = '' | |
if (object.instance_of?(String)) | |
# Custom Definitions | |
special_case_list.each do |k, v| | |
val << "# @attr [#{v}] #{k.to_s.camelize(:lower)}\n" | |
end | |
else | |
# ActiveRecord Object | |
object.attribute_types.map do |key, active_model_type| | |
next if exclusion_list.include? key | |
type = special_case_list && special_case_list.keys.include?(key.to_sym) ? | |
special_case_list[key.to_sym] : adjust(active_model_type) | |
val << "# @attr [#{type}] #{key.camelize(:lower)}\n" | |
end | |
end | |
str = <<EOS | |
# This was generated by `rails json_params:generate` | |
# | |
# @name #{object}StrongParameter | |
# | |
#{val.chomp} | |
class Params::#{object}; end | |
EOS | |
File.open(file_path,"w") {|file| file.puts str} | |
end | |
def adjust(model) | |
case model.type | |
when :text | |
type = 'string' | |
when :time | |
when :datetime | |
type = 'date-time' | |
when :decimal | |
type = 'float' # 'string' | |
else | |
type = model.type | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment