A gem which uses the ‘mechanize` gem to make it easier to execute remote requests that require an authenticated session. It allows the programmer to provide a `:login` action callback which is executed whenever mechanized_session determines that the session has gone bad or authentication is required. The programmer also provides other actions which perform useful tasks.
To use this with rails, check out ‘acts_as_other_website`.
class SomeSiteSession < MechanizedSession
action :login do |session, options| session.get('http://www.google.com/login') do |page| next_page = page.form_with(:action =>"/login") do |form| form["email"] = options[:username] form["password"] = options[:password] end.click_button return false if next_page.uri.path.include?("/login") end true end action :get_widgets do |session| links = [] session.get('http://www.google.com/ig") do |page| # might throw InvalidSession if not logged in links += page.links end links end def self.requires_login?(page) # explaining to mechanized_session when a page was a redirect to the login page page.uri.path.downcase.include?("/login") end
end
@session = SomeSiteSession.new begin
@session.get_widgets
rescue InvalidSession => e
# deal with invalid session, ask the user for credentials @session = SomeSiteSession.new(:username => "bob", :password => "password") retry
end
-
mechanize gem
-
sudo gem install mechanized_session
See blog post at: flouri.sh/2009/12/7/introducing-mechanized_session-and-acts_as_other_website
(The MIT License)
Copyright © 2009 David Stevenson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.