Class: YARD::Handlers::Ruby::ActiveRecord::Validate::ValidatesHandler

Inherits:
MethodHandler
  • Object
show all
Defined in:
lib/yard-activerecord/validations/validates_handler.rb

Overview

Document ActiveRecord validations. This handler handles the validates statement. It will parse the list of fields, the validation types and their options, and the optional :if/:unless clause. It only handles the newer Rails “:validates” syntax and does not recognize the older “validates_presence_of” type methods.

Instance Method Summary collapse

Instance Method Details

#processObject



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/yard-activerecord/validations/validates_handler.rb', line 53

def process

  validations = {}
  attributes  = []
  conditions  = {}

  # Read each parameter to the statement and parse out
  # it's type and intent
  statement.parameters(false).compact.map do |param|
    # list types are options
    if param.type == :list
      param.each do | n |
        kw = n.jump(:label, :symbol_literal ).source.gsub(/:/,'')
        # if/unless are conditions that apply to all the validations
        if ['if','unless','on'].include?(kw)
          conditions[ kw ] = n.children.last.source
        else # otherwise it's type specific
          opts = n.jump(:hash)
          value = ( opts != n ) ? opts.source : nil
          validations[ kw ] = value
        end
      end
    elsif param.type == :symbol_literal
      attributes << param.jump(:ident, :kw, :tstring_content).source
    end
  end

  # abort in case we didn't parse anything
  return if validations.empty?

  # Loop through each attribute and set a tag on each
  attributes.each do | attribute |
    method_definition = namespace.instance_attributes[attribute.to_sym] || {}
    method = method_definition[:read]
    if ! method
      meths = namespace.meths(:all => true)
      method = meths.find {|m| m.name == attribute.to_sym }
    end
    # If the method isn't defined yet, go ahead and create one
    if ! method
      method = register YARD::CodeObjects::MethodObject.new(namespace, attribute )
      method.scope = :instance
      method.explicit = false
      method_definition[:read] = method
      namespace.instance_attributes[attribute.to_sym] = method_definition
    end
    tag = YARD::Tags::OptionTag.new(:validates, '', conditions ) #, [] )
    tag.types = {} #[]
    validations.each{ |arg,options|
      tag.types[ arg ] = options
    }
    method.docstring.add_tag tag
  end

end