Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to call method in property_of block #58

Open
Stratus3D opened this issue Dec 27, 2018 · 2 comments
Open

Unable to call method in property_of block #58

Stratus3D opened this issue Dec 27, 2018 · 2 comments

Comments

@Stratus3D
Copy link
Contributor

I have a property_of block that needs to contain some special logic I have for choosing a state and city. I need to make sure the city selected is within the chosen state. I want to do something like this:

properties = property_of do
    state = choose(*states)
    city = choose(*cities_within_state(state))

    [state, city]
end

This does not work because cities_within_state is a method defined in an included module, which doesn't seem to be available within the context of the property_of block (though it is available outside it). I need to invoke the method within the property_of block because that is the only scope in which the state variable exists.

I was able to come up with a workaround to invoke the the method within the block:

properties = property_of do
    state = choose(*states)
    cities = Class.new.extend(ModuleContainingMethod).cities_within_state(state)
    city = choose(*cities)

    [state, city]
end

Is there a better way of doing this?

@krishan
Copy link

krishan commented Jun 8, 2021

It seems that the property_of block is executed on a Rantly instance, which makes the "local" methods unavailable.

It might work to store the method inside a lambda in a local variable, like this:

cities_within_states_fn = -> { |state| cities_within_state(state) }

properties = property_of do
    state = choose(*states)
    cities = cities_within_states_fn.call(state)
    city = choose(*cities)

    [state, city]
end

@diasbruno
Copy link
Contributor

diasbruno commented May 28, 2022

You can also extend Rantly::Data.

require 'rantly/data'

module Rantly::Data
  def state_and_city
    state = choose(*states)
    city = choose(*cities_within_state(state))

    [state, city]
  end
end

property_of do
   state_and_city
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants