Class: Contracts::Formatters::ParamContracts

Inherits:
Object
  • Object
show all
Defined in:
lib/yard-contracts/formatters.rb

Instance Method Summary collapse

Constructor Details

#initialize(param_string, types_string) ⇒ ParamContracts


179
180
181
182
183
184
# File 'lib/yard-contracts/formatters.rb', line 179

def initialize(param_string, types_string)
  @params = ParamsAST.new(param_string).to_a
  types = TypesAST.new(types_string)
  @types = types.to_a
  @result = types.result
end

Instance Method Details

#paramsObject


186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/yard-contracts/formatters.rb', line 186

def params
  s = []
  i = named_count = 0
  @params.each do |param|
    param_type, param = param

    on_named = param_type == :named_arg ||
              (named_count > 0 && param_type == :ident)
    i -= named_count if on_named

    type, type_ast = @types[i]
    con = get_contract_value(type)
    type = TypeAST.new(type_ast).type

    # Ripper has :rest_param (splat) but nothing for doublesplat,
    # it's just called :ident the same as required positional params.
    # This is really annoying. So we have to figure it out.
    if on_named
      @named_con ||= con
      @named_type ||= type
      if @named_con.is_a? Hash
        if param_type == :named_arg
          con = @named_con.delete(param)
          type = @named_type.delete(param)
        else
          con = @named_con
          type = @named_type
        end
      else
        @named_con = con = '?'
        @named_type = type = []
      end
      named_count = 1
    end

    type = Contracts::Formatters::InspectWrapper.new(type)
    desc = Contracts::Formatters::Expected.new(con, false).contract
    # The pluses are to escape things like curly brackets
    desc = "#{desc}".empty? ? '' : "+#{desc}+"
    s << [param, type, desc]
    i += 1
  end
  s
end

#returnObject


231
232
233
234
235
236
237
238
239
240
# File 'lib/yard-contracts/formatters.rb', line 231

def return
  type, type_ast = @result
  con = get_contract_value(type)
  type = Contracts::Formatters::InspectWrapper.new(
    TypeAST.new(type_ast).type
  )
  desc = Contracts::Formatters::Expected.new(con, false).contract
  desc = "#{desc}".empty? ? '' : "+#{desc}+"
  [type, desc]
end