Skip to content

Instantly share code, notes, and snippets.

$gen = (function() {
yield 1;
yield 2;
// 3 is only returned after the generator has finished
return 3;
})();
foreach ($gen as $val) {
echo $val, PHP_EOL;
function printer() {
echo "I'm printer!". PHP_EOL;
while (true) {
$string = yield;
echo $string . PHP_EOL;
}
}
$printer = printer();
function counter($num) {
for ($i = 1; $i < $num; $i++) {
yield $i;
}
}
foreach (counter(PHP_INT_MAX) as $count) {
echo "Yield: " . $count . PHP_EOL;
}
function gen_one_to_three() {
for ( $i = 1; $i <= 3; $i++ ) {
yield $i;
yield 'abc';
}
}
$generator = gen_one_to_three();
foreach ( $generator as $value ) {
Class Person < ActiveRecord::ApplicationRecord
validates :name, presence: true
validates :date_of_birth, presence: true, if: create_stage > 1
validates :ni_number, presence: true, if: create_stage > 2
end
class PersonValidator < ActiveModel::Validator
def validate(record)
@record = record
__send__("validate_stage_#{@record.create_stage}")
end
private
def validate_stage_1
validate_present(:name)
end
class Person < ApplicationRecord
validates_with PersonValidator
end
Class Person < ActiveRecord::ApplicationRecord
validates :name, presence: true
validates :date_of_birth, presence: true, if: create_stage > 1
Validates :ni_number, presence: true, if: create_stage > 2
end
Class Person < ActiveRecord::ApplicationRecord
validates :name, date_of_birth, ni_number, presence: true
end
context 'stage 2' do
let(:person) { Person.new(create_stage: 2) }
context 'both name and date of birth supplied' do
it 'is valid' do
person.name = 'John Smith'
person.date_of_birth = Date.new(1990, 5, 12)
expect(person).to be_valid
end
end