Ruby 1.9 without variables

I am updating the code from 1.8 to 1.9. I meet a couple of places in my code (specifications only, not sure if this is a match) where there are problems with blocks that don't have a variable. Providing them with a dummy variable fixes the problem. Here is an example:

In factory to factory girl, this works under 1.8:

Factory.define :thing do |t| t.price { 1 - 0.01*rand(10) } end 

In section 1.9, rand(10) returns nil . Very strange. I had a brain why the environment would be different inside the block. The fact is that rand is not even from the standard library - from the main language! Thus, in fact, there is no way in which the medium will matter.

Then I remembered that some other places in my specifications were breaking due to non-variable blocks, so I threw it there on a whim, and now it worked.

 Factory.define :thing do |t| t.price { |dummy| 1 - 0.01*rand(10) } end 

What's going on here?

+4
source share
1 answer

In recent versions of factory_girl, an attribute definition without a block argument uses instance_eval, and it is assumed that method-based calls look for previous attribute definitions, methods of your model, or syntax methods such as "create" or "build".

To make attributes such as "open" or "file" work correctly, the proxy object does not define most private methods, including "rand". This means that you need to use "Kernel.rand" instead of "rand".

You can see the corresponding source here: https://github.com/thoughtbot/factory_girl/blob/master/lib/factory_girl/evaluator.rb#L16

+2
source

Source: https://habr.com/ru/post/1401065/


All Articles