4
우선 Java에서 강력한 배경을 가지고 있지만 Ruby를 처음 접했습니다. 첫 번째 Rails 애플리케이션을 만들었고 FactoryGirl을 사용하고 있습니다. 나는 이상한 것을 가로 질러왔다 (나를 위해). 그리고 나는 그것이 왜 이런 행동을하는지 알 수 없다. 물론factory_girl 및 sprintf
def fff(n)
sprintf('WWW Product %05d', n)
end
b1 = proc { |n| fff(n) }
b2 = proc { |n| sprintf('WWW Product %05d', n) }
FactoryGirl.define do
factory :product1, :class => Product do
sequence(:name) { |n| 'Product %05d' % "#{n}" }
end
factory :product2, :class => Product do
sequence(:name) { |n| sprintf('WWW Product %05d', n) }
end
factory :product3, :class => Product do
sequence(:name, 1, &b1)
end
factory :product4, :class => Product do
sequence(:name, 1, &b2)
end
factory :product5, :class => Product do
sequence(:name) { |n| fff(n) }
end
end
describe Test do
it "works with %" do
p = Factory.create(:product1)
puts p.inspect
end
it "does not work with sprintf" do
expect { Factory.create(:product2) }.to raise_error(ArgumentError)
end
it "works with a block with a function" do
p = Factory.create(:product3)
puts p.inspect
end
it "works with a block with sprintf" do
p = Factory.create(:product4)
puts p.inspect
end
it "does not work with a function with sprintf" do
expect { Factory.create(:product5) }.to raise_error(ArgumentError)
end
end
내가 %를 사용할 수 있습니다 여기에
Failures:
1) Test raises an ArgumentError
Failure/Error: sprintf('Product %05d', n)
ArgumentError:
wrong number of arguments (3 for 2)
# ./spec/models/fg_spec.rb:6:in `fff'
# ./spec/models/fg_spec.rb:31:in `block (3 levels) in <top (required)>'
# ./spec/models/fg_spec.rb:62:in `block (2 levels) in <top (required)>'
이 동작을 보여 전체 스펙이다 (마지막 시험 참조) 공장 내에서의 sprintf를 사용
다음과 같은 오류가 발생합니다 표기법 그러나 나는 이것에 관하여 정말로 흥미 롭다. 문제의 코드가 서로 다른 컨텍스트 내에서 호출되고 있기 때문에
b2 = proc { |n| Kernel.sprintf('WWW Product %05d', n) }
이것은 sprintf와는이다 :
감사합니다,
데이비드
감사합니다. 나는 커널이 자바에서 항상 임포트 될 필요가없는 java.lang. *과 같이 항상 범위 내에 있다고 가정했다; 이상한 :) – ddidier