Class: RailsAutodoc::StrongParamsParser

Inherits:
Object
  • Object
show all
Includes:
AstTraversal
Defined in:
lib/rails_autodoc/strong_params_parser.rb

Defined Under Namespace

Classes: ParamsResult

Instance Method Summary collapse

Constructor Details

#initialize(source_path:, class_name:) ⇒ StrongParamsParser

Returns a new instance of StrongParamsParser.



11
12
13
14
15
# File 'lib/rails_autodoc/strong_params_parser.rb', line 11

def initialize(source_path:, class_name:)
  @source_path = source_path
  @class_name = class_name
  @buffer, = Parser::CurrentRuby.parse_file(source_path)
end

Instance Method Details

#param_methodsObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rails_autodoc/strong_params_parser.rb', line 17

def param_methods
  methods = {}
  each_method_definition(class_node) do |child|
    method_name = method_name_for(child)
    next unless method_name.end_with?("_params")

    schema = extract_permit_schema(child)
    next if schema.nil?

    methods[method_name] = ParamsResult.new(
      root_key: schema[:root_key],
      schema: schema[:properties],
      method_name: method_name
    )
  end
  methods
end

#params_for_action(action_name) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rails_autodoc/strong_params_parser.rb', line 35

def params_for_action(action_name)
  action_node = find_action_node(action_name)
  return nil unless action_node

  called_methods = extract_called_param_methods(action_node)
  called_methods.each do |method_name|
    result = param_methods[method_name]
    return result if result
  end

  param_methods.values.first
end

#query_params_for_action(action_name) ⇒ Object



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
# File 'lib/rails_autodoc/strong_params_parser.rb', line 48

def query_params_for_action(action_name)
  action_node = find_action_node(action_name)
  return [] unless action_node

  params = []
  walk_nodes(action_node) do |node|
    next unless node.type == :send

    method_name = node.children[1]
    case method_name
    when :[]
      param_name = literal_value(node.children[2])
      if param_name && node.children[0]&.type == :send && node.children[0].children[1] == :params
        params << param_name.to_s
      end
    when :fetch
      param_name = literal_value(node.children[2])
      if param_name && node.children[0]&.type == :send && node.children[0].children[1] == :params
        params << param_name.to_s
      end
    end
  end

  params.uniq.map do |name|
    { name: name, type: "string", required: false }
  end
end