Module: Serde::SerializerGenerator
- Defined in:
- lib/serde/serializer_generator.rb
Class Method Summary collapse
-
.call(dir, klass) ⇒ Object
rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity.
Class Method Details
.call(dir, klass) ⇒ Object
rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/serde/serializer_generator.rb', line 10 def call(dir, klass) FileUtils.cp_r(Dir.glob(File.('../../templates/extension/*', __dir__)), '.') schema = klass.instance_variable_get(:@schema) name = underscore(klass.name) fields = schema.map do |k, v| v = v.to_s type = case v when 'Integer' then 'i64' when 'Float' then 'f64' else v end ctype = case v when 'Integer' then 'int' when 'String' then 'char*' end cdecl = case v when 'Integer' then "int c_#{k} = NUM2INT(#{k});" when 'String' then "char* c_#{k} = StringValueCStr(#{k});" end rctype = case v when 'String' then '*const c_char' when 'Integer' then 'i64' when 'Float' then 'f64' else v end { name: k, type: type, rctype: rctype, cdecl: cdecl, ctype: ctype } end rust_extras = [] schema.each do |k, v| next unless v.to_s == 'String' rust_extras.push(<<~RUST) let #{k} = unsafe { CStr::from_ptr(#{k}).to_string_lossy().into_owned() }; RUST end serializer = { class_name: klass.name, name: name, fields: fields, joint_fields: fields.map do |field| "#{field[:name]}: #{field[:type]}" end.join(', '), joint_fields_rctype: fields.map do |field| "#{field[:name]}: #{field[:rctype]}" end.join(', '), joint_fields_c: fields.map do |field| "#{field[:ctype]} #{field[:name]}" end.join(', '), rust_extras: rust_extras, } mod_template = ERB.new(File.read(File.('../../templates/rust/mod.rs', __dir__))) compiled_template = mod_template.result(binding) File.write(File.("../../rust/src/#{name}.rs", __dir__), compiled_template) c_template = ERB.new(File.read(File.('../../templates/c/serde_rb.c', __dir__))) compiled_template = c_template.result(binding) File.write('./serde_rb/serde_rb.c', compiled_template) lib_template = ERB.new(File.read(File.('../../templates/rust/lib.rs', __dir__))) compiled_template = lib_template.result(binding) File.write(File.('../../rust/src/lib.rs', __dir__), compiled_template) end |