0

To test image urls in a ruby project I can call a function as follows

validate_url("some_valid_url", "valid")
validate_url("inv#alid-url", "invalid")

The function looks like this:

def validate_url(image_url, state)
    assert state === 'valid' ? new_product(image_url).valid? : new_product(image_url).invalid?,
       "#{image_url} should always be " + state.upcase
end

is there a way to rewrite the line:

assert state === 'valid' ? new_product(image_url).valid? : new_product(image_url).invalid?

to something like

assert new_product(image_url).state.What-To-Do-Here?

which would then be equals to the following if state contains the string "valid"

assert new_product(image_url).valid?
7
  • can the new_product(image_url) return a state already? not sure I understood correctly: you method should return valid if URL is valid or "#{image_url} should always be " + state.upcase if it's invalid? - state being the argument that determining the validation of the URL? Commented Apr 8, 2021 at 11:53
  • 1
    I'd create a method that returns a boolean value instead of a string one valid_url?(image_url). Commented Apr 8, 2021 at 11:56
  • This seems weird to me. You already have validation methods, you already know which one to call, what's gained here? Commented Apr 8, 2021 at 12:42
  • @DaveNewton the gain is to not use the unnecessary if..else Commented Apr 8, 2021 at 12:45
  • In the code that calls this function you already have all the information needed--and you only need one of the "valid?"/"invalid?" methods becaise you can negate either's value. Commented Apr 8, 2021 at 12:53

1 Answer 1

2

You can do....

assert new_product(image_url).send(state + '?'), "#{image_url} should always be #{state.upcase}"

It would be prudent to ensure that state can only contain "valid" or "invalid"

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @Steve, after I figured out the 2 typos it did work :-)
There's no need to use send here. public_send should be enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.