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])