Sha256: 906e03647685c77ce079b00d58a19bdd454db1659f8411e8c451a88e8e1a0898

Contents?: true

Size: 1.92 KB

Versions: 1

Compression:

Stored size: 1.92 KB

Contents

require "erb"
require "active_support/inflector"
require "active_support/core_ext/array/access"
require "pp"

class String
  def to_method_name
    underscore.split(" ").join("_")
  end
  def to_class_type
    case self
    when "integer"
      "Fixnum"
    else
      classify
    end
  end
end

def rb_primitive_types
  [Fixnum, String]
end
def as_primitive_types
  ["int", "String", "Number", "uint", "Boolean"]
end

module Peto
  class Generator
    def initialize(contract)
      @contract = contract
    end
    attr_reader :contract

    def generate_procedure(template_filename)
      erb = ERB.new(IO.read(template_filename), nil, "-")
      { "#{@contract["name"]}" => erb.result(binding) }
    end

    def generate_class(template_filename, type)
      erb = ERB.new(IO.read(template_filename), nil, "-")
      @target = {:name => type.first, :args => args(type.second)}
      { "#{@target[:name]}" => erb.result(binding) }
    end

    def class_name
      @contract["name"].to_class_type
    end

    def args(string_args)
      string_args.map do |str|
        splitted = str.split(":")
        arg(splitted.first, splitted.second, :array_type => splitted.third)
      end
    end

    def arg(name, type, options={})
      array_type = options.delete(:array_type)
      {
        :name => name,
        :type => type.to_class_type,
        :array_type => array_type.nil? ? nil : array_type.to_class_type,
      }
    end

    def each_types
      @contract["types"].each do |name, args|
        yield name.to_class_type, args(args)
      end
    end

    def each_procedures
      (@contract["procedures"]||[]).each do |name, procedure|
        yield name.to_method_name, args(procedure["args"])
        yield "#{name} response".to_method_name, args(procedure["returns"])
        (procedure["errors"]||[]).each do |error|
          yield "#{name} error #{error}".to_method_name, [arg("message", "string")]
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
peto-0.2.6 lib/peto/generator.rb