Skip to content

Instantly share code, notes, and snippets.

@simonfranzen
Last active June 26, 2019 09:04
Show Gist options
  • Save simonfranzen/b65a75ed9e91e008f8f1b2b7d746440b to your computer and use it in GitHub Desktop.
Save simonfranzen/b65a75ed9e91e008f8f1b2b7d746440b to your computer and use it in GitHub Desktop.
RubyOnRails GraphQL Type Generator
# lib/generators/rails/graphql/graphql_generator.rb
# run with "rails generate graphql my_model"
class Rails::GraphqlGenerator < Rails::Generators::NamedBase
def create_graphql_type_file
attributes = ""
begin
klass = Object.const_get(class_name)
obj = klass.new
obj.attributes.each do |attr, i|
if attr != "id"
attr_type = klass.columns_hash[attr].type.to_s.capitalize
attr_type = 'DateTime' if attr_type == 'Datetime'
attr_type = 'String' if attr_type == 'Binary'
attributes += "field :#{attr}, #{attr_type}\n "
end
end
rescue
end
create_file "app/graphql/types/#{file_name}_type.rb", <<-FILE
module Types
class #{class_name}Type < BaseObject
field :id, ID, null: false
#{ attributes }
end
end
FILE
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment