File: method_stringifier.rb

package info (click to toggle)
ruby-bogus 0.1.6-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 860 kB
  • sloc: ruby: 4,219; makefile: 8; sh: 2
file content (53 lines) | stat: -rw-r--r-- 1,301 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
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
module Bogus
  class MethodStringifier

    def stringify(method, body)
      <<-RUBY
      def #{method.name}(#{arguments_as_string(method.parameters)})
        #{body}
      end
      RUBY
    end

    def arguments_as_string(arguments)
      stringify_arguments(arguments, DefaultValue)
    end

    def argument_values(arguments)
      stringify_arguments(arguments)
    end

    private

    def stringify_arguments(arguments, default = nil)
      fill_in_missing_names(arguments).map do |type, name|
        argument_to_string(name, type, default)
      end.join(', ')
    end

    def argument_to_string(name, type, default)
      case type
      when :block then "&#{name}"
      when :key then default ? "#{name}: #{default}" : "#{name}: #{name}"
      when :keyreq then default ? "#{name}:" : "#{name}: #{name}"
      when :opt then default ? "#{name} = #{default}" : name
      when :req then name
      when :rest then "*#{name}"
      when :keyrest then "**#{name}"
      else raise "unknown argument type: #{type}"
      end
    end

    def fill_in_missing_names(arguments)
      noname_count = 0
      arguments.map do |type, name|
        unless name
          name = "_noname_#{noname_count}"
          noname_count += 1
        end
        [type, name]
      end
    end

  end
end