Class: Contracts::Keys
- Inherits:
-
Object
- Object
- Contracts::Keys
- Defined in:
- lib/contracts/gen.rb
Class Method Summary collapse
Instance Method Summary collapse
- #generate ⇒ Object
-
#initialize(required, optional) ⇒ Keys
constructor
A new instance of Keys.
- #valid?(value) ⇒ Boolean
Constructor Details
#initialize(required, optional) ⇒ Keys
Returns a new instance of Keys.
15 16 17 18 |
# File 'lib/contracts/gen.rb', line 15 def initialize(required, optional) @required = required @optional = optional end |
Class Method Details
.[](spec) ⇒ Object
8 9 10 11 12 13 |
# File 'lib/contracts/gen.rb', line 8 def self.[](spec) if !spec.key?(:required) and !spec.key?(:optional) raise ':required or :optional keys must be specified' end new(spec[:required], spec[:optional]) end |
Instance Method Details
#generate ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/contracts/gen.rb', line 28 def generate h = {} unless @required.nil? or @required.empty? @required.each do |(k, contract)| h[k] = ::Gen.generate(contract) end end unless @optional.nil? or @optional.empty? n = Faker::Number.between(0, @optional.keys.length) keys = @optional.keys.sample(n) keys.each do |k| contract = @optional[k] h[k] = ::Gen.generate(contract) end end h end |
#valid?(value) ⇒ Boolean
20 21 22 23 24 25 26 |
# File 'lib/contracts/gen.rb', line 20 def valid?(value) if not value.respond_to?(:[]) false else @required.all? { |(k, v)| Contract.valid?(value[k], v) } end end |