Sha256: f4dd85d9e45f47123a317b5e762bb3078636c8f00e3c449fcecdccf8c7d7d0d9

Contents?: true

Size: 1.71 KB

Versions: 3

Compression:

Stored size: 1.71 KB

Contents

module DevScripts
  module Support
    class MethodCall < String
      attr_reader :receiver, :invocation, :args, :ast_node

      def initialize(ast_node)
        @ast_node = ast_node
        current_receiver, @invocation, *@args = ast_node.children

        invocation_stack = [invocation_with_args]

        while Parser::AST::Node === current_receiver
          invocation_stack.unshift MethodCall.new(current_receiver).invocation_with_args

          current_receiver, invocation, *args = current_receiver&.children || []
        end

        invocation_stack.each_with_index do |invocation_string, index|
          self << '.' if index > 0
          self << invocation_string.to_s
        end
      end

      def invocation_with_args
        if args && args.size > 0
          args.each_with_object("#{invocation}(").with_index do |(arg, string), index|
            string << arg_string(arg)

            string << ', ' if index < args.size - 1
            string << ')' if index == args.size - 1
          end
        else
          invocation
        end
      end

      def arg_string(arg)
        case arg.type
        when :sym
          ":#{arg.children[0]}"
        when :str
          "'#{arg.children[0]}'"
        when :int
          "#{arg.children[0].to_i}"
        when :lvar
          "#{arg.children[0]}"
        when :send
          "#{arg.children[1]}"
        when :hash
          arg.children.each_with_object('').with_index do |(kwarg, string), index|
            string << arg_string(kwarg)

            string << ', ' if index < arg.children.size - 1
          end
        when :pair
          key, value = arg.children

          "#{key.children.first}: " + arg_string(value)
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
dev_scripts-0.2.1 lib/dev_scripts/support/method_call.rb
dev_scripts-0.2.0 lib/dev_scripts/support/method_call.rb
dev_scripts-0.1.9 lib/dev_scripts/support/method_call.rb