egonSchiele / contracts.ruby

Contracts for Ruby.
http://egonschiele.github.com/contracts.ruby
BSD 2-Clause "Simplified" License
1.44k stars 82 forks source link

Puzzling Failure #303

Closed Z2Flow closed 4 months ago

Z2Flow commented 4 months ago

This works:

require "contracts"

class Person
  include Contracts

  Contract Symbol => Symbol
  def initialize(field:)
    @field = field
  end
end

person = Person.new(field: "field")

in that field passed as a String is detected and flagged as an error.

This does not:

require "contracts"

class Person
  include Contracts

  Contract String, Symbol, String => String
  def initialize(name:, field:, value:)
    @name = name
    @field = field
    @value = value
  end
end

person = Person.new(name: "Jane", field: "field", value: "value")

field: "field" is not detected.

PikachuEXE commented 4 months ago

Wrong contract?

class Person
  include Contracts::Core
  include Contracts::Builtin

  Contract KeywordArgs[name: String, field: Symbol, value: String] => Any
  def initialize(name:, field:, value:)
    @name = name
    @field = field
    @value = value
  end
end

Person.new(name: "Jane", field: "field", value: "value")
ParamContractError: Contract violation for argument 1 of 1:
        Expected: (KeywordArgs[{:name=>String, :field=>Symbol, :value=>String}]),
        Actual: {:name=>"Jane", :field=>"field", :value=>"value"}
        Value guarded in: Person::initialize
        With Contract: KeywordArgs => Any
        At: (pry):18
Z2Flow commented 4 months ago

That was it. Thanks @PikachuEXE