├── .gitignore ├── .rspec ├── .travis.yml ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── Gemfile ├── LICENSE.txt ├── README.md ├── Rakefile ├── bin ├── console └── setup ├── json_to_ruby_class.gemspec ├── lib ├── json_to_ruby_class.rb └── json_to_ruby_class │ ├── c_sharp_converter.rb │ ├── ruby_converter.rb │ ├── vb_dot_net_converter.rb │ └── version.rb └── spec ├── json_to_ruby_class_spec.rb └── spec_helper.rb /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /Gemfile.lock 4 | /_yardoc/ 5 | /coverage/ 6 | /doc/ 7 | /pkg/ 8 | /spec/reports/ 9 | /tmp/ 10 | 11 | # Ignore idea configuration. 12 | /.idea -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --format documentation 2 | --color 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | rvm: 3 | - 2.2.3 4 | before_install: gem install bundler -v 1.10.6 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 0.2.0 (2016-08-02) 2 | 3 | Features 4 | * C# classes are now supported 5 | * VB.Net classes are now supported 6 | 7 | ## 0.1.3 (2016-07-14) 8 | 9 | Bug fixes 10 | * class instead of Class 11 | * Added needed activesupport for various methods 12 | 13 | ## 0.1.2 (2016-07-12) 14 | 15 | Bug fixes 16 | * Don't break once given key is not a Hash or an Array. 17 | 18 | ## 0.1.1 (2016-07-09) 19 | 20 | Bug fixes 21 | * Remove duplicate attributes from the same model 22 | 23 | ## 0.1.0 (2016-07-09) 24 | 25 | * Initial commit -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Code of Conduct 2 | 3 | As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. 4 | 5 | We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion. 6 | 7 | Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct. 8 | 9 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team. 10 | 11 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. 12 | 13 | This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/) 14 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | # Specify your gem's dependencies in json_to_ruby_class.gemspec 4 | gemspec 5 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Vasilis Kalligas 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JsonToRubyClass 2 | 3 | [![Build Status](https://travis-ci.org/arcanoid/json_to_ruby_class.svg?branch=master)](https://travis-ci.org/arcanoid/json_to_ruby_class) 4 | [![Gem Version](https://badge.fury.io/rb/json_to_ruby_class.svg)](https://badge.fury.io/rb/json_to_ruby_class) 5 | 6 | JsonToRubyClass is a gem that converts a JSON to a list of Ruby classes and outputs it into a string. 7 | 8 | ## Installation 9 | 10 | Add this line to your application's Gemfile: 11 | 12 | ```ruby 13 | gem 'json_to_ruby_class' 14 | ``` 15 | 16 | And then execute: 17 | 18 | $ bundle 19 | 20 | Or install it yourself as: 21 | 22 | $ gem install json_to_ruby_class 23 | 24 | ## Usage 25 | 26 | ```ruby 27 | json = <<-JSON 28 | { 29 | "students": [ 30 | { 31 | "firstName": "John", 32 | "lastName": "Doe", 33 | "age": 15 34 | }, 35 | { 36 | "firstName": "Anna", 37 | "lastName": "Smith", 38 | "age": 16 39 | } 40 | ] 41 | } 42 | JSON 43 | 44 | puts JsonToRubyClass.produce_models(json) 45 | ``` 46 | 47 | This produces the following: 48 | 49 | ```ruby 50 | class Student 51 | attr_accessor :first_name, 52 | :last_name, 53 | :age 54 | end 55 | 56 | class Example 57 | attr_accessor :students 58 | end 59 | ``` 60 | 61 | Furthermore, the following types can be used to retrieve the proper classes in other languages: 62 | * 'c#', for C# classes 63 | * 'vb', for VB.net classes 64 | 65 | Example use: 66 | 67 | ```ruby 68 | puts JsonToRubyClass.produce_models(json, 'c#') 69 | 70 | public class Student 71 | { 72 | public string firstName { get; set; } 73 | public string lastName { get; set; } 74 | public int age { get; set; } 75 | } 76 | 77 | public class Example 78 | { 79 | public Student[] students { get; set; } 80 | } 81 | ``` 82 | 83 | ## Development 84 | 85 | After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. 86 | 87 | To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). 88 | 89 | ## Contributing 90 | 91 | Bug reports and pull requests are welcome on GitHub at https://github.com/arcanoid/json_to_ruby_class. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct. 92 | 93 | 94 | ## License 95 | 96 | The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). 97 | 98 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require "bundler/gem_tasks" 2 | require "rspec/core/rake_task" 3 | 4 | RSpec::Core::RakeTask.new(:spec) 5 | 6 | task :default => :spec 7 | -------------------------------------------------------------------------------- /bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require "bundler/setup" 4 | require "json_to_ruby_class" 5 | 6 | # You can add fixtures and/or initialization code here to make experimenting 7 | # with your gem easier. You can also use a different console, if you like. 8 | 9 | # (If you use this, don't forget to add pry to your Gemfile!) 10 | # require "pry" 11 | # Pry.start 12 | 13 | require "irb" 14 | IRB.start 15 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | IFS=$'\n\t' 4 | 5 | bundle install 6 | 7 | # Do any other automated setup that you need to do here 8 | -------------------------------------------------------------------------------- /json_to_ruby_class.gemspec: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | lib = File.expand_path('../lib', __FILE__) 3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) 4 | require 'json_to_ruby_class/version' 5 | 6 | Gem::Specification.new do |spec| 7 | spec.name = "json_to_ruby_class" 8 | spec.version = JsonToRubyClass::VERSION 9 | spec.authors = ["Vasilis Kalligas"] 10 | spec.email = ["billkall@gmail.com"] 11 | 12 | spec.summary = %q{This gem can be used in Rails apps to automatically convert a json to the relative model classes} 13 | spec.homepage = "https://rubygems.org/gems/json_to_ruby_class" 14 | spec.license = "MIT" 15 | 16 | spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } 17 | spec.bindir = "exe" 18 | spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } 19 | spec.require_paths = ["lib"] 20 | 21 | spec.add_dependency 'activesupport' 22 | spec.add_development_dependency "bundler", "~> 1.10" 23 | spec.add_development_dependency "rake", "~> 10.0" 24 | spec.add_development_dependency "rspec" 25 | end 26 | -------------------------------------------------------------------------------- /lib/json_to_ruby_class.rb: -------------------------------------------------------------------------------- 1 | require "json_to_ruby_class/version" 2 | require "json_to_ruby_class/ruby_converter" 3 | require "json_to_ruby_class/c_sharp_converter" 4 | require "json_to_ruby_class/vb_dot_net_converter" 5 | require 'active_support' 6 | require 'active_support/core_ext' 7 | 8 | module JsonToRubyClass 9 | VB_DOT_NET_LANGUAGE_TYPE = 'vb' 10 | C_SHARP_LANGUAGE_TYPE = 'c#' 11 | RUBY_LANGUAGE_TYPE = 'ruby' 12 | 13 | def self.produce_models(hash, language = 'ruby') 14 | models_array = collect_info_from_json(hash, nil) 15 | 16 | case language 17 | when C_SHARP_LANGUAGE_TYPE then CSharpConverter.prepare_c_sharp_models_from_hash models_array 18 | when VB_DOT_NET_LANGUAGE_TYPE then VBDotNetConverter.prepare_vb_dot_net_models_from_hash models_array 19 | else RubyConverter.prepare_ruby_models_from_hash models_array 20 | end 21 | end 22 | 23 | ####### 24 | private 25 | ####### 26 | 27 | def self.collect_info_from_json(hash, model_name, existing_models_array = []) 28 | unless hash.is_a? Hash 29 | hash = ActiveSupport::JSON.decode(hash) 30 | end 31 | accessors = [] 32 | 33 | hash.each do |key, value| 34 | # In some cases you have a parent called Resources and inside has an array of models Resource 35 | constructed_model_name = (key.to_s == model_name.to_s ? "#{model_name}_#{key}" : key) 36 | 37 | if value.class == Hash 38 | collect_info_from_json(value, constructed_model_name, existing_models_array) 39 | elsif value.class == Array 40 | value.each do |array_element| 41 | if array_element.class == Hash || array_element.class == Array 42 | collect_info_from_json(array_element, constructed_model_name, existing_models_array) 43 | end 44 | end 45 | end 46 | 47 | accessors << { :key => "#{key.to_s}", :type => value.class } 48 | end 49 | 50 | model_name_to_be_used = (model_name.nil? ? 'Example' : model_name.to_s.camelcase) 51 | 52 | if (hash = existing_models_array.find { |model| model[:name] == model_name_to_be_used }) 53 | hash[:accessors].push(accessors).flatten!.uniq! 54 | else 55 | existing_models_array << { 56 | :name => (model_name.nil? ? 'Example' : model_name.to_s.camelcase), 57 | :accessors => accessors 58 | } 59 | end 60 | 61 | existing_models_array 62 | end 63 | 64 | private_class_method :collect_info_from_json 65 | end 66 | -------------------------------------------------------------------------------- /lib/json_to_ruby_class/c_sharp_converter.rb: -------------------------------------------------------------------------------- 1 | module JsonToRubyClass 2 | class CSharpConverter 3 | ####### 4 | private 5 | ####### 6 | 7 | def self.prepare_c_sharp_models_from_hash(models_array) 8 | model_string = '' 9 | 10 | models_array.each do |model| 11 | model_string << "public class #{model[:name].singularize}\n" 12 | model_string << "{\n" 13 | 14 | model[:accessors].each do |accessor| 15 | type = case accessor[:type].to_s 16 | when 'String' then 'string' 17 | when 'Fixnum' then 'int' 18 | when 'Float' then 'decimal' 19 | when 'Array' then "#{accessor[:key].singularize.camelcase}[]" 20 | when 'TrueClass' then 'bool' 21 | when 'FalseClass' then 'bool' 22 | when 'Hash' then "#{accessor[:key].singularize.camelcase}" 23 | # TODO: How could you cover an array of integers? 24 | else accessor[:type].to_s 25 | end 26 | 27 | model_string << " public #{type} #{accessor[:key]} { get; set; }\n" 28 | end 29 | model_string << "}\n\n" 30 | end 31 | 32 | model_string 33 | end 34 | end 35 | end -------------------------------------------------------------------------------- /lib/json_to_ruby_class/ruby_converter.rb: -------------------------------------------------------------------------------- 1 | module JsonToRubyClass 2 | class RubyConverter 3 | ####### 4 | private 5 | ####### 6 | 7 | def self.prepare_ruby_models_from_hash(models_array) 8 | model_string = '' 9 | 10 | models_array.each do |model| 11 | model_string << "class #{model[:name].singularize}\n" 12 | model_string << ' attr_accessor ' 13 | model_string << model[:accessors].map { |accessor| ":#{accessor[:key].underscore}" }.join(",\n ") 14 | model_string << "\nend\n\n" 15 | end 16 | 17 | model_string 18 | end 19 | end 20 | end -------------------------------------------------------------------------------- /lib/json_to_ruby_class/vb_dot_net_converter.rb: -------------------------------------------------------------------------------- 1 | module JsonToRubyClass 2 | class VBDotNetConverter 3 | ####### 4 | private 5 | ####### 6 | 7 | def self.prepare_vb_dot_net_models_from_hash(models_array) 8 | model_string = '' 9 | 10 | models_array.each do |model| 11 | model_string << "Public Class #{model[:name].singularize}\n" 12 | 13 | model[:accessors].each do |accessor| 14 | type = case accessor[:type].to_s 15 | when 'String' then 'String' 16 | when 'Fixnum' then 'Integer' 17 | when 'Float' then 'Decimal' 18 | when 'Array' then "#{accessor[:key].singularize.camelcase}()" 19 | when 'TrueClass' then 'Boolean' 20 | when 'FalseClass' then 'Boolean' 21 | when 'Hash' then "#{accessor[:key].singularize.camelcase}" 22 | # TODO: How could you cover an array of integers? 23 | else accessor[:type].to_s 24 | end 25 | 26 | model_string << " Public Property #{accessor[:key]} As #{type}\n" 27 | end 28 | model_string << "End Class\n\n" 29 | end 30 | 31 | model_string 32 | end 33 | end 34 | end -------------------------------------------------------------------------------- /lib/json_to_ruby_class/version.rb: -------------------------------------------------------------------------------- 1 | module JsonToRubyClass 2 | VERSION = "0.2.0" 3 | end 4 | -------------------------------------------------------------------------------- /spec/json_to_ruby_class_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe JsonToRubyClass do 4 | subject { JsonToRubyClass } 5 | 6 | describe ".produce_models" do 7 | context "Given a JSON without a type" do 8 | let(:json) do 9 | <<-JSON 10 | { 11 | "students": [ 12 | { 13 | "firstName": "Json", 14 | "lastName": "Doe", 15 | "age": 15 16 | }, 17 | { 18 | "firstName": "Anna", 19 | "lastName": "Smith", 20 | "age": 22 21 | } 22 | ] 23 | } 24 | JSON 25 | end 26 | 27 | before do 28 | str_class = subject.produce_models(json) 29 | eval(str_class) 30 | end 31 | 32 | it 'defines the classes correctly' do 33 | example = Example.new 34 | student = Student.new 35 | 36 | expect(example).to respond_to(:students) 37 | expect(student).to respond_to(:age) 38 | expect(student).to respond_to(:first_name) 39 | expect(student).to respond_to(:last_name) 40 | end 41 | end 42 | 43 | context "Given a JSON for Ruby" do 44 | let(:json) do 45 | <<-JSON 46 | { 47 | "students": [ 48 | { 49 | "firstName": "Json", 50 | "lastName": "Doe", 51 | "age": 15 52 | }, 53 | { 54 | "firstName": "Anna", 55 | "lastName": "Smith", 56 | "age": 22 57 | } 58 | ] 59 | } 60 | JSON 61 | end 62 | 63 | before do 64 | str_class = subject.produce_models(json) 65 | eval(str_class) 66 | end 67 | 68 | it 'defines the classes correctly' do 69 | example = Example.new 70 | student = Student.new 71 | 72 | expect(example).to respond_to(:students) 73 | expect(student).to respond_to(:age) 74 | expect(student).to respond_to(:first_name) 75 | expect(student).to respond_to(:last_name) 76 | end 77 | end 78 | 79 | context "Given a JSON for C#" do 80 | let(:json) do 81 | <<-JSON 82 | { 83 | "students": [ 84 | { 85 | "firstName": "Json", 86 | "lastName": "Doe", 87 | "age": 15 88 | }, 89 | { 90 | "firstName": "Anna", 91 | "lastName": "Smith", 92 | "age": 22 93 | } 94 | ] 95 | } 96 | JSON 97 | end 98 | 99 | let(:result) { subject.produce_models(json, 'c#') } 100 | let(:expected_result) do 101 | <<-TEXT 102 | public class Student 103 | { 104 | public string firstName { get; set; } 105 | public string lastName { get; set; } 106 | public int age { get; set; } 107 | } 108 | 109 | public class Example 110 | { 111 | public Student[] students { get; set; } 112 | } 113 | 114 | TEXT 115 | end 116 | 117 | it 'defines the classes correctly' do 118 | expect(result).to eq(expected_result) 119 | end 120 | end 121 | 122 | context "Given a JSON for VB.net" do 123 | let(:json) do 124 | <<-JSON 125 | { 126 | "students": [ 127 | { 128 | "firstName": "Json", 129 | "lastName": "Doe", 130 | "age": 15 131 | }, 132 | { 133 | "firstName": "Anna", 134 | "lastName": "Smith", 135 | "age": 22 136 | } 137 | ] 138 | } 139 | JSON 140 | end 141 | 142 | let(:result) { subject.produce_models(json, 'vb') } 143 | let(:expected_result) do 144 | <<-TEXT 145 | Public Class Student 146 | Public Property firstName As String 147 | Public Property lastName As String 148 | Public Property age As Integer 149 | End Class 150 | 151 | Public Class Example 152 | Public Property students As Student() 153 | End Class 154 | 155 | TEXT 156 | end 157 | 158 | it 'defines the classes correctly' do 159 | expect(result).to eq(expected_result) 160 | end 161 | end 162 | end 163 | end 164 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) 2 | require 'json_to_ruby_class' 3 | 4 | --------------------------------------------------------------------------------