Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a string to an object reference in ruby

I want to take in a page name in a gherkin step then set it as an object reference (I think that’s what it’s called.) Then I can use that to interact with page elements. Is there an easier way to do this in ruby?

When(/^I am on the (.*) page$/) do |page|
  case page
  when "home page"
  @current_page = @home_page
  when "my account page"
  @current_page = @my_account_page
  end
end

Then

When(/^I click the (.*)$/) do |element|
 @current_page.send(element).click
end

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use instance_variable_get:

When(/^I am on the (.*) page$/) do |page|
  @current_page = instance_variable_get("@#{page}")
end

This will work if the page values perfect match your instance variables, e.g.

page = "my_account_page"

# The following two lines are equivalent
instance_variable_get("@#{page}")
@my_account_page
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading