mfilimonov
mfilimonov

Reputation: 607

Ruby blocks to change scope to specific variable

I'm a complete newbie in ruby but I can feel that this code can be improved.

    class LoginPage < BasePage
       def initialize(session)
         @session = session
       end

       def login(params)
         @session.within '#login-form' do
           @session.fill_in 'Login', with: params[:login]
           @session.fill_in 'Password',with: params[:password]
         end
       @session.click_button 'Login'
       end
     end

I was thinking to do something like:

@session do 
  within '#login-form' do
    fill_in 'Login', with: params[:login]
    fill_in 'Password', with params[:password]
  end
  click_buttton 'Login'
end

But this code won't work. Any idea how to change scope of these method calls to make them calls to specific instance variable.

Upvotes: 1

Views: 315

Answers (1)

Don Cruickshank
Don Cruickshank

Reputation: 5948

You can do this with instance_eval.

@session.instance_eval do  
  within '#login-form' do 
    fill_in 'Login', with: params[:login] 
    fill_in 'Password', with params[:password] 
  end 
  click_buttton 'Login' 
end 

However I'd argue that this makes your code confusing to read since one could easily miss the instance_eval when scanning through the code.

Upvotes: 2

Related Questions