When submitting a login form using mechanize-ruby, Can I use variables to represent field names?

StackOverflow https://stackoverflow.com/questions/12938998

  •  07-07-2021
  •  | 
  •  

문제

I ran into a problem when using Mechanize to submit a login form. For example, if I need to log into bitbucket:

a = Mechanize.new
a.get('https://bitbucket.org/') do |page|
  login_page = a.click(page.link_with(text: 'Log In'))

  my_page = login_page.form_with(action: '/account/signin/') do |f|
    # The "username" and "password" below are the values of the "name" attribute of the two login form fields
    f.username = 'MY_ACCOUNT_NAME' 
    f.password = 'MY_PASSWORD' 
  end.click_button
end

That's pretty straight forward, however, not all login forms have the same "name" value on those two fields. WordPress' login form, for example, uses "log" and "pwd" . This would invalidate the above code.

I want to pass some parameters into this method so that it can be used on different login forms. I attempted to follow "How to convert from a string to object attribute name?" but was unsuccessful:

# auth_info is a hash
def website_login(auth_info) 
  a = Mechanize.new
  a.get(auth_info[:login_page_url]) do |page|
    land_page = page.form_with(action: auth_info[:login_form_action]) do |f|
      # Now I am stuck with these two lines
      ????????
      ????????
      # I tried to do it like this. Not working.
      f.instance_variable_set('@'+auth_info[:username_field_name], auth_info[:username])
      f.instance_variable_set('@'+auth_info[:password_field_name], auth_info[:password])
    end.click_button
  end
end

Really appreciate if someone can help out.

도움이 되었습니까?

해결책

Resolved. It's like this:

f.send(auth_info[:username_field_name] + '=', auth_info[:username])
f.send(auth_info[:password_field_name] + '=', auth_info[:password])
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top