Sha256: 5784fe633cee499f06354e7357208559f75116d20c025fbdf0a76711bee3475d

Contents?: true

Size: 1.45 KB

Versions: 7

Compression:

Stored size: 1.45 KB

Contents

module SafeRuby
  PARSER_REGEX = /["'](?<path>\/.*)["']\.(?<method>[A-z]+)/
  QUERY_REGEX  = /query?.*\{(?<query>.*)\}/
  INPUT_REGEX  = /input?.*\{(?<input>.*)\}/
end

Toycol::Protocol.define(:safe_ruby) do |message|
  using Module.new {
    refine String do
      # Ex. '/posts'.get
      # Ex. (with query string) '/posts'.get(query: { user_id: 2 })
      def get(options = {})
        Toycol::Protocol.request.query { options[:query] } if options[:query]
        Toycol::Protocol.request.http_method { "GET" }
      end

      # Ex. '/posts'.post(input: { user_id: 1, body: 'This is a post request' })
      def post(options = {})
        Toycol::Protocol.request.input { options[:input] } if options[:input]
        Toycol::Protocol.request.http_method { "POST" }
      end

      def parse_as_queries
        split(",").map { |str| str.scan(/\w+/).join("=") }
      end

      def parse_as_inputs
        split(",").map { |str| str.split(":").map { |s| s.strip! && s.gsub(/['"]/, "") }.join("=") }
      end
    end
  }

  path, method = SafeRuby::PARSER_REGEX.match(message) { |m| [m[:path], m[:method]] }
  query = SafeRuby::QUERY_REGEX.match(message) { |m| m[:query].parse_as_queries }&.join("&")
  input = SafeRuby::INPUT_REGEX.match(message) { |m| m[:input].parse_as_inputs }&.join("&")
  args  = {}

  request.path { path }

  %i[query input].each do |k|
    if v = binding.local_variable_get(k)
      args[*k] = v
    end
  end

  request_path.public_send(method, args)
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
toycol-1.0.0 examples/safe_ruby/Protocolfile.safe_ruby
toycol-0.3.1 examples/safe_ruby/Protocolfile.safe_ruby
toycol-0.3.0 examples/safe_ruby/Protocolfile.safe_ruby
toycol-0.2.2 examples/safe_ruby/Protocolfile.safe_ruby
toycol-0.2.1 examples/safe_ruby/Protocolfile.safe_ruby
toycol-0.2.0 examples/safe_ruby/Protocolfile.safe_ruby
toycol-0.1.0 examples/safe_ruby/Protocolfile.safe_ruby