Skip to content

Instantly share code, notes, and snippets.

@beccasaurus
Created November 21, 2010 22:19
Show Gist options
  • Save beccasaurus/709213 to your computer and use it in GitHub Desktop.
Save beccasaurus/709213 to your computer and use it in GitHub Desktop.
%w[ rubygems nokogiri open-uri ].each {|lib| require lib }
# Usage:
# MyClass = make_me_a_class "http://some/url"
#
# See the irb-example.rb below
#
# Note: you don't *have* to set a constant with this method but
# if you just use a regular variable, the class won't know
# it's name. Ruby classes get their name from their constant's name.
#
def make_me_a_class url_with_form
# go get the URL
doc = Nokogiri::HTML open(url_with_form).read
# grab the first <form> if it exists
if first_form = doc.css('form').first
# grab the <input>, <select>, <textarea> fields for this form, if any
fields = first_form.css('input, select, textarea')
unless fields.empty?
# make a new Class
klass = Class.new
# for each field, add an attr_accessor to the class using the field's name attribute
fields.each do |field|
begin
klass.send :attr_accessor, field[:name]
rescue Exception => ex
# if a field's name has brackets in it or is nil or anything like that, attr_accessor will fail
puts "Couldn't create valid accessor for #{field[:name].inspect}"
end
end
# return the new class!
return klass
end
end
end
>> GoogleForm = make_me_a_class 'http://www.google.com'
=> GoogleForm
>> GoogleForm.instance_methods - Object.instance_methods
=> ["hl=", "btnG", "btnG=", "q", "q=", "ie", "ie=", "btnI", "btnI=", "source", "source=", "hl"]
>> GistForm = make_me_a_class 'https://gist.github.com'
Couldn't create valid accessor for nil
>> GistForm.instance_methods - Object.instance_methods
=> ["page=", "q", "q=", "page"]
>> TwitterForm = make_me_a_class 'http://twitter.com'
=> TwitterForm
>> TwitterForm.instance_methods - Object.instance_methods
=> ["commit", "commit=", "q", "q=", "authenticity_token", "authenticity_token="]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment