Class: JSONCop::Generator
- Inherits:
-
Object
- Object
- JSONCop::Generator
- Defined in:
- lib/jsoncop/generator.rb
Instance Attribute Summary collapse
-
#file_path ⇒ Object
readonly
Returns the value of attribute file_path.
-
#model ⇒ Object
readonly
Returns the value of attribute model.
Instance Method Summary collapse
- #generate! ⇒ Object
-
#initialize(file_path, model) ⇒ Generator
constructor
A new instance of Generator.
- #json_cop_template ⇒ Object
- #json_parsing_template ⇒ Object
Constructor Details
#initialize(file_path, model) ⇒ Generator
Returns a new instance of Generator.
10 11 12 13 |
# File 'lib/jsoncop/generator.rb', line 10 def initialize(file_path, model) @file_path = file_path @model = model end |
Instance Attribute Details
#file_path ⇒ Object (readonly)
Returns the value of attribute file_path.
7 8 9 |
# File 'lib/jsoncop/generator.rb', line 7 def file_path @file_path end |
#model ⇒ Object (readonly)
Returns the value of attribute model.
8 9 10 |
# File 'lib/jsoncop/generator.rb', line 8 def model @model end |
Instance Method Details
#generate! ⇒ Object
15 16 17 18 19 20 21 22 23 |
# File 'lib/jsoncop/generator.rb', line 15 def generate! jsoncop_generate_start = /jsoncop: generate\-start/ jsoncop_generate_end = /jsoncop: generate\-end/ content = File.read file_path if content.match(jsoncop_generate_start) && content.match(jsoncop_generate_end) content.gsub!(/\/\/ jsoncop: generate-start[^$]*jsoncop: generate\-end/, "") end File.write file_path, content + json_cop_template end |
#json_cop_template ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/jsoncop/generator.rb', line 25 def json_cop_template <<-JSONCOP // jsoncop: generate-start extension #{@model.name} { static func parse(json: [String: Any]) -> #{@model.name}? { guard #{json_parsing_template} else { return nil } return #{@model.name}(#{model.key_value_pair}) } static func parse(jsons: [[String: Any]]) -> [#{@model.name}] { return jsons.flatMap(parse) } } // jsoncop: generate-end JSONCOP end |
#json_parsing_template ⇒ Object
43 44 45 46 47 48 49 50 51 |
# File 'lib/jsoncop/generator.rb', line 43 def json_parsing_template @model.attributes.map do |attr| if @model.transformers.include? attr.name "let #{attr.name} = (json[\"#{@model.attr_json_hash[attr.name]}\"]).flatMap(#{attr.name}JSONTransformer)" else "let #{attr.name} = json[\"#{@model.attr_json_hash[attr.name]}\"] as? #{attr.type}" end end.join(",\n\t\t") end |