Permalink
Browse files

First version. Search by room count, room price, and geocode.

  • Loading branch information...
0 parents commit e6c6e41cdf993d47d520783510df1f0a2d253852 @pwnall committed Jul 17, 2010
Showing with 13,411 additions and 0 deletions.
  1. +4 −0 .gitignore
  2. +12 −0 .project
  3. +29 −0 Gemfile
  4. +80 −0 Gemfile.lock
  5. +256 −0 README
  6. +7 −0 Rakefile
  7. +3 −0 app/controllers/application_controller.rb
  8. +23 −0 app/controllers/geocode_fetches_controller.rb
  9. +120 −0 app/controllers/listings_controller.rb
  10. +35 −0 app/controllers/page_fetches_controller.rb
  11. +2 −0 app/helpers/application_helper.rb
  12. +2 −0 app/helpers/geocode_fetches_helper.rb
  13. +2 −0 app/helpers/listings_helper.rb
  14. +2 −0 app/helpers/page_fetches_helper.rb
  15. +28 −0 app/models/geocode_fetch.rb
  16. +21 −0 app/models/listing.rb
  17. +17 −0 app/models/page_fetch.rb
  18. +22 −0 app/views/geocode_fetches/index.html.erb
  19. +18 −0 app/views/geocode_fetches/show.html.erb
  20. +14 −0 app/views/layouts/application.html.erb
  21. BIN app/views/listings/index.html.erb
  22. +28 −0 app/views/listings/search.html.erb
  23. +33 −0 app/views/listings/show.html.erb
  24. +22 −0 app/views/page_fetches/index.html.erb
  25. +18 −0 app/views/page_fetches/show.html.erb
  26. +4 −0 config.ru
  27. +50 −0 config/application.rb
  28. +13 −0 config/boot.rb
  29. +38 −0 config/database.yml
  30. +5 −0 config/environment.rb
  31. +22 −0 config/environments/development.rb
  32. +49 −0 config/environments/production.rb
  33. +35 −0 config/environments/test.rb
  34. +7 −0 config/initializers/backtrace_silencers.rb
  35. +62 −0 config/initializers/geokit_config.rb
  36. +10 −0 config/initializers/inflections.rb
  37. +5 −0 config/initializers/mime_types.rb
  38. +7 −0 config/initializers/secret_token.rb
  39. +8 −0 config/initializers/session_store.rb
  40. +5 −0 config/locales/en.yml
  41. +66 −0 config/routes.rb
  42. +20 −0 db/migrate/20100717031511_create_listings.rb
  43. +14 −0 db/migrate/20100717031855_create_page_fetches.rb
  44. +17 −0 db/migrate/20100717075712_create_geocode_fetches.rb
  45. +47 −0 db/schema.rb
  46. +7 −0 db/seeds.rb
  47. +2 −0 doc/README_FOR_APP
  48. +170 −0 lib/listing_populator.rb
  49. 0 lib/tasks/.gitkeep
  50. +26 −0 public/404.html
  51. +26 −0 public/422.html
  52. +26 −0 public/500.html
  53. 0 public/favicon.ico
  54. BIN public/images/rails.png
  55. +2 −0 public/javascripts/application.js
  56. +965 −0 public/javascripts/controls.js
  57. +974 −0 public/javascripts/dragdrop.js
  58. +1,123 −0 public/javascripts/effects.js
  59. +6,001 −0 public/javascripts/prototype.js
  60. +175 −0 public/javascripts/rails.js
  61. +5 −0 public/robots.txt
  62. 0 public/stylesheets/.gitkeep
  63. +56 −0 public/stylesheets/scaffold.css
  64. +6 −0 script/populator.rb
  65. +6 −0 script/rails
  66. +11 −0 test/fixtures/geocode_fetches.yml
  67. +15 −0 test/fixtures/listings.yml
  68. +11 −0 test/fixtures/page_fetches.yml
  69. +49 −0 test/functional/geocode_fetches_controller_test.rb
  70. +49 −0 test/functional/listings_controller_test.rb
  71. +49 −0 test/functional/page_fetches_controller_test.rb
  72. +9 −0 test/performance/browsing_test.rb
  73. +13 −0 test/test_helper.rb
  74. +8 −0 test/unit/geocode_fetch_test.rb
  75. +4 −0 test/unit/helpers/geocode_fetches_helper_test.rb
  76. +4 −0 test/unit/helpers/listings_helper_test.rb
  77. +4 −0 test/unit/helpers/page_fetches_helper_test.rb
  78. +8 −0 test/unit/listing_test.rb
  79. +8 −0 test/unit/page_fetch_test.rb
  80. 0 vendor/plugins/.gitkeep
  81. +46 −0 vendor/plugins/geokit-rails/CHANGELOG.rdoc
  82. +20 −0 vendor/plugins/geokit-rails/MIT-LICENSE
  83. +561 −0 vendor/plugins/geokit-rails/README.markdown
  84. +18 −0 vendor/plugins/geokit-rails/Rakefile
  85. +9 −0 vendor/plugins/geokit-rails/about.yml
  86. +61 −0 vendor/plugins/geokit-rails/assets/api_keys_template
  87. +1 −0 vendor/plugins/geokit-rails/init.rb
  88. +14 −0 vendor/plugins/geokit-rails/install.rb
  89. +26 −0 vendor/plugins/geokit-rails/lib/geokit-rails.rb
  90. +456 −0 vendor/plugins/geokit-rails/lib/geokit-rails/acts_as_mappable.rb
  91. +31 −0 vendor/plugins/geokit-rails/lib/geokit-rails/adapters/abstract.rb
  92. +22 −0 vendor/plugins/geokit-rails/lib/geokit-rails/adapters/mysql.rb
  93. +22 −0 vendor/plugins/geokit-rails/lib/geokit-rails/adapters/postgresql.rb
  94. +43 −0 vendor/plugins/geokit-rails/lib/geokit-rails/adapters/sqlserver.rb
  95. +22 −0 vendor/plugins/geokit-rails/lib/geokit-rails/defaults.rb
  96. +16 −0 vendor/plugins/geokit-rails/lib/geokit-rails/geocoder_control.rb
  97. +46 −0 vendor/plugins/geokit-rails/lib/geokit-rails/ip_geocode_lookup.rb
  98. +474 −0 vendor/plugins/geokit-rails/test/acts_as_mappable_test.rb
  99. +25 −0 vendor/plugins/geokit-rails/test/boot.rb
  100. +20 −0 vendor/plugins/geokit-rails/test/database.yml
  101. +7 −0 vendor/plugins/geokit-rails/test/fixtures/companies.yml
  102. +54 −0 vendor/plugins/geokit-rails/test/fixtures/custom_locations.yml
  103. +54 −0 vendor/plugins/geokit-rails/test/fixtures/locations.yml
  104. +17 −0 vendor/plugins/geokit-rails/test/fixtures/mock_addresses.yml
  105. +2 −0 vendor/plugins/geokit-rails/test/fixtures/mock_families.yml
  106. +9 −0 vendor/plugins/geokit-rails/test/fixtures/mock_houses.yml
  107. +5 −0 vendor/plugins/geokit-rails/test/fixtures/mock_organizations.yml
  108. +5 −0 vendor/plugins/geokit-rails/test/fixtures/mock_people.yml
  109. 0 vendor/plugins/geokit-rails/test/fixtures/stores.yml
  110. +77 −0 vendor/plugins/geokit-rails/test/ip_geocode_lookup_test.rb
  111. +3 −0 vendor/plugins/geokit-rails/test/models/company.rb
  112. +12 −0 vendor/plugins/geokit-rails/test/models/custom_location.rb
  113. +4 −0 vendor/plugins/geokit-rails/test/models/location.rb
  114. +4 −0 vendor/plugins/geokit-rails/test/models/mock_address.rb
  115. +3 −0 vendor/plugins/geokit-rails/test/models/mock_family.rb
  116. +3 −0 vendor/plugins/geokit-rails/test/models/mock_house.rb
  117. +4 −0 vendor/plugins/geokit-rails/test/models/mock_organization.rb
  118. +4 −0 vendor/plugins/geokit-rails/test/models/mock_person.rb
  119. +3 −0 vendor/plugins/geokit-rails/test/models/store.rb
  120. +60 −0 vendor/plugins/geokit-rails/test/schema.rb
  121. +31 −0 vendor/plugins/geokit-rails/test/tasks.rake
  122. +23 −0 vendor/plugins/geokit-rails/test/test_helper.rb
4 .gitignore
@@ -0,0 +1,4 @@
+.bundle
+db/*.sqlite3
+log/*.log
+tmp/**/*
12 .project
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>clh</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ </buildSpec>
+ <natures>
+ <nature>org.radrails.rails.core.railsnature</nature>
+ </natures>
+</projectDescription>
29 Gemfile
@@ -0,0 +1,29 @@
+source 'http://rubygems.org'
+
+gem 'rails', '3.0.0.beta4'
+
+# Bundle edge Rails instead:
+# gem 'rails', :git => 'git://github.com/rails/rails.git'
+
+gem 'mysql'
+
+# Use unicorn as the web server
+# gem 'unicorn'
+
+# Deploy with Capistrano
+# gem 'capistrano'
+
+# To use debugger
+# gem 'ruby-debug'
+
+# Bundle the extra gems:
+gem 'geokit'
+gem 'mechanize'
+gem 'nokogiri'
+
+# Bundle gems for the local environment. Make sure to
+# put test-only gems in this group so their generators
+# and rake tasks are available in development mode:
+# group :development, :test do
+# gem 'webrat'
+# end
80 Gemfile.lock
@@ -0,0 +1,80 @@
+GEM
+ remote: http://rubygems.org/
+ specs:
+ abstract (1.0.0)
+ actionmailer (3.0.0.beta4)
+ actionpack (= 3.0.0.beta4)
+ mail (~> 2.2.5)
+ actionpack (3.0.0.beta4)
+ activemodel (= 3.0.0.beta4)
+ activesupport (= 3.0.0.beta4)
+ builder (~> 2.1.2)
+ erubis (~> 2.6.6)
+ i18n (~> 0.4.1)
+ rack (~> 1.2.1)
+ rack-mount (~> 0.6.9)
+ rack-test (~> 0.5.4)
+ tzinfo (~> 0.3.22)
+ activemodel (3.0.0.beta4)
+ activesupport (= 3.0.0.beta4)
+ builder (~> 2.1.2)
+ i18n (~> 0.4.1)
+ activerecord (3.0.0.beta4)
+ activemodel (= 3.0.0.beta4)
+ activesupport (= 3.0.0.beta4)
+ arel (~> 0.4.0)
+ tzinfo (~> 0.3.22)
+ activeresource (3.0.0.beta4)
+ activemodel (= 3.0.0.beta4)
+ activesupport (= 3.0.0.beta4)
+ activesupport (3.0.0.beta4)
+ arel (0.4.0)
+ activesupport (>= 3.0.0.beta)
+ builder (2.1.2)
+ erubis (2.6.6)
+ abstract (>= 1.0.0)
+ geokit (1.5.0)
+ i18n (0.4.1)
+ mail (2.2.5)
+ activesupport (>= 2.3.6)
+ mime-types
+ treetop (>= 1.4.5)
+ mechanize (1.0.0)
+ nokogiri (>= 1.2.1)
+ mime-types (1.16)
+ mysql (2.8.1)
+ nokogiri (1.4.2)
+ polyglot (0.3.1)
+ rack (1.2.1)
+ rack-mount (0.6.9)
+ rack (>= 1.0.0)
+ rack-test (0.5.4)
+ rack (>= 1.0)
+ rails (3.0.0.beta4)
+ actionmailer (= 3.0.0.beta4)
+ actionpack (= 3.0.0.beta4)
+ activerecord (= 3.0.0.beta4)
+ activeresource (= 3.0.0.beta4)
+ activesupport (= 3.0.0.beta4)
+ bundler (>= 1.0.0.beta.2)
+ railties (= 3.0.0.beta4)
+ railties (3.0.0.beta4)
+ actionpack (= 3.0.0.beta4)
+ activesupport (= 3.0.0.beta4)
+ rake (>= 0.8.3)
+ thor (~> 0.13.7)
+ rake (0.8.7)
+ thor (0.13.8)
+ treetop (1.4.8)
+ polyglot (>= 0.3.1)
+ tzinfo (0.3.22)
+
+PLATFORMS
+ ruby
+
+DEPENDENCIES
+ geokit
+ mechanize
+ mysql
+ nokogiri
+ rails (= 3.0.0.beta4)
256 README
@@ -0,0 +1,256 @@
+== Welcome to Rails
+
+Rails is a web-application framework that includes everything needed to create
+database-backed web applications according to the Model-View-Control pattern.
+
+This pattern splits the view (also called the presentation) into "dumb"
+templates that are primarily responsible for inserting pre-built data in between
+HTML tags. The model contains the "smart" domain objects (such as Account,
+Product, Person, Post) that holds all the business logic and knows how to
+persist themselves to a database. The controller handles the incoming requests
+(such as Save New Account, Update Product, Show Post) by manipulating the model
+and directing data to the view.
+
+In Rails, the model is handled by what's called an object-relational mapping
+layer entitled Active Record. This layer allows you to present the data from
+database rows as objects and embellish these data objects with business logic
+methods. You can read more about Active Record in
+link:files/vendor/rails/activerecord/README.html.
+
+The controller and view are handled by the Action Pack, which handles both
+layers by its two parts: Action View and Action Controller. These two layers
+are bundled in a single package due to their heavy interdependence. This is
+unlike the relationship between the Active Record and Action Pack that is much
+more separate. Each of these packages can be used independently outside of
+Rails. You can read more about Action Pack in
+link:files/vendor/rails/actionpack/README.html.
+
+
+== Getting Started
+
+1. At the command prompt, create a new Rails application:
+ <tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name)
+
+2. Change directory to <tt>myapp</tt> and start the web server:
+ <tt>cd myapp; rails server</tt> (run with --help for options)
+
+3. Go to http://localhost:3000/ and you'll see:
+ "Welcome aboard: You're riding Ruby on Rails!"
+
+4. Follow the guidelines to start developing your application. You can find
+the following resources handy:
+
+* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html
+* Ruby on Rails Tutorial Book: http://www.railstutorial.org/
+
+
+== Debugging Rails
+
+Sometimes your application goes wrong. Fortunately there are a lot of tools that
+will help you debug it and get it back on the rails.
+
+First area to check is the application log files. Have "tail -f" commands
+running on the server.log and development.log. Rails will automatically display
+debugging and runtime information to these files. Debugging info will also be
+shown in the browser on requests from 127.0.0.1.
+
+You can also log your own messages directly into the log file from your code
+using the Ruby logger class from inside your controllers. Example:
+
+ class WeblogController < ActionController::Base
+ def destroy
+ @weblog = Weblog.find(params[:id])
+ @weblog.destroy
+ logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
+ end
+ end
+
+The result will be a message in your log file along the lines of:
+
+ Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1!
+
+More information on how to use the logger is at http://www.ruby-doc.org/core/
+
+Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are
+several books available online as well:
+
+* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe)
+* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
+
+These two books will bring you up to speed on the Ruby language and also on
+programming in general.
+
+
+== Debugger
+
+Debugger support is available through the debugger command when you start your
+Mongrel or WEBrick server with --debugger. This means that you can break out of
+execution at any point in the code, investigate and change the model, and then,
+resume execution! You need to install ruby-debug to run the server in debugging
+mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
+
+ class WeblogController < ActionController::Base
+ def index
+ @posts = Post.find(:all)
+ debugger
+ end
+ end
+
+So the controller will accept the action, run the first line, then present you
+with a IRB prompt in the server window. Here you can do things like:
+
+ >> @posts.inspect
+ => "[#<Post:0x14a6be8
+ @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>,
+ #<Post:0x14a6620
+ @attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]"
+ >> @posts.first.title = "hello from a debugger"
+ => "hello from a debugger"
+
+...and even better, you can examine how your runtime objects actually work:
+
+ >> f = @posts.first
+ => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
+ >> f.
+ Display all 152 possibilities? (y or n)
+
+Finally, when you're ready to resume execution, you can enter "cont".
+
+
+== Console
+
+The console is a Ruby shell, which allows you to interact with your
+application's domain model. Here you'll have all parts of the application
+configured, just like it is when the application is running. You can inspect
+domain models, change values, and save to the database. Starting the script
+without arguments will launch it in the development environment.
+
+To start the console, run <tt>rails console</tt> from the application
+directory.
+
+Options:
+
+* Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications
+ made to the database.
+* Passing an environment name as an argument will load the corresponding
+ environment. Example: <tt>rails console production</tt>.
+
+To reload your controllers and models after launching the console run
+<tt>reload!</tt>
+
+More information about irb can be found at:
+link:http://www.rubycentral.com/pickaxe/irb.html
+
+
+== dbconsole
+
+You can go to the command line of your database directly through <tt>rails
+dbconsole</tt>. You would be connected to the database with the credentials
+defined in database.yml. Starting the script without arguments will connect you
+to the development database. Passing an argument will connect you to a different
+database, like <tt>rails dbconsole production</tt>. Currently works for MySQL,
+PostgreSQL and SQLite 3.
+
+== Description of Contents
+
+The default directory structure of a generated Ruby on Rails application:
+
+ |-- app
+ | |-- controllers
+ | |-- helpers
+ | |-- models
+ | `-- views
+ | `-- layouts
+ |-- config
+ | |-- environments
+ | |-- initializers
+ | `-- locales
+ |-- db
+ |-- doc
+ |-- lib
+ | `-- tasks
+ |-- log
+ |-- public
+ | |-- images
+ | |-- javascripts
+ | `-- stylesheets
+ |-- script
+ | `-- performance
+ |-- test
+ | |-- fixtures
+ | |-- functional
+ | |-- integration
+ | |-- performance
+ | `-- unit
+ |-- tmp
+ | |-- cache
+ | |-- pids
+ | |-- sessions
+ | `-- sockets
+ `-- vendor
+ `-- plugins
+
+app
+ Holds all the code that's specific to this particular application.
+
+app/controllers
+ Holds controllers that should be named like weblogs_controller.rb for
+ automated URL mapping. All controllers should descend from
+ ApplicationController which itself descends from ActionController::Base.
+
+app/models
+ Holds models that should be named like post.rb. Models descend from
+ ActiveRecord::Base by default.
+
+app/views
+ Holds the template files for the view that should be named like
+ weblogs/index.html.erb for the WeblogsController#index action. All views use
+ eRuby syntax by default.
+
+app/views/layouts
+ Holds the template files for layouts to be used with views. This models the
+ common header/footer method of wrapping views. In your views, define a layout
+ using the <tt>layout :default</tt> and create a file named default.html.erb.
+ Inside default.html.erb, call <% yield %> to render the view using this
+ layout.
+
+app/helpers
+ Holds view helpers that should be named like weblogs_helper.rb. These are
+ generated for you automatically when using generators for controllers.
+ Helpers can be used to wrap functionality for your views into methods.
+
+config
+ Configuration files for the Rails environment, the routing map, the database,
+ and other dependencies.
+
+db
+ Contains the database schema in schema.rb. db/migrate contains all the
+ sequence of Migrations for your schema.
+
+doc
+ This directory is where your application documentation will be stored when
+ generated using <tt>rake doc:app</tt>
+
+lib
+ Application specific libraries. Basically, any kind of custom code that
+ doesn't belong under controllers, models, or helpers. This directory is in
+ the load path.
+
+public
+ The directory available for the web server. Contains subdirectories for
+ images, stylesheets, and javascripts. Also contains the dispatchers and the
+ default HTML files. This should be set as the DOCUMENT_ROOT of your web
+ server.
+
+script
+ Helper scripts for automation and generation.
+
+test
+ Unit and functional tests along with fixtures. When using the rails generate
+ command, template test files will be generated for you and placed in this
+ directory.
+
+vendor
+ External libraries that the application depends on. Also includes the plugins
+ subdirectory. If the app has frozen rails, those gems also go here, under
+ vendor/rails/. This directory is in the load path.
7 Rakefile
@@ -0,0 +1,7 @@
+# Add your own tasks in files placed in lib/tasks ending in .rake,
+# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
+
+require File.expand_path('../config/application', __FILE__)
+require 'rake'
+
+Clh::Application.load_tasks
3 app/controllers/application_controller.rb
@@ -0,0 +1,3 @@
+class ApplicationController < ActionController::Base
+ protect_from_forgery
+end
23 app/controllers/geocode_fetches_controller.rb
@@ -0,0 +1,23 @@
+class GeocodeFetchesController < ApplicationController
+ # GET /geocode_fetches
+ # GET /geocode_fetches.xml
+ def index
+ @geocode_fetches = GeocodeFetch.all
+
+ respond_to do |format|
+ format.html # index.html.erb
+ format.xml { render :xml => @geocode_fetches }
+ end
+ end
+
+ # GET /geocode_fetches/1
+ # GET /geocode_fetches/1.xml
+ def show
+ @geocode_fetch = GeocodeFetch.find(params[:id])
+
+ respond_to do |format|
+ format.html # show.html.erb
+ format.xml { render :xml => @geocode_fetch }
+ end
+ end
+end
120 app/controllers/listings_controller.rb
@@ -0,0 +1,120 @@
+class ListingsController < ApplicationController
+ # GET /listings
+ # GET /listings.xml
+ def index
+ @listings = Listing.all
+
+ respond_to do |format|
+ format.html # index.html.erb
+ format.xml { render :xml => @listings }
+ end
+ end
+
+ # GET /search
+ # GET /search.xml
+ def search
+ location = nil
+ if params[:location] && params[:radius]
+ geocode = GeocodeFetch.get params[:location]
+ location = Geokit::LatLng.new geocode[:lat], geocode[:lng]
+ radius = params[:radius].to_f
+ end
+
+ rel = Listing
+ if params[:rooms_min]
+ rel = rel.where('rooms >= ?', params[:rooms_min].to_i)
+ end
+ if params[:rooms_max]
+ rel = rel.where('rooms <= ?', params[:rooms_max].to_i)
+ end
+ @listings = rel.all.select do |listing|
+ if params[:room_price_max]
+ if (listing.price / listing.rooms.to_f) > params[:room_price_max].to_f
+ next false
+ end
+ end
+ if location
+ if radius < listing.distance_to(location, :units => :miles)
+ next false
+ end
+ end
+ true
+ end
+
+ respond_to do |format|
+ format.html # search.html.erb
+ format.xml { render :xml => @listings }
+ end
+ end
+
+ # GET /listings/1
+ # GET /listings/1.xml
+ def show
+ @listing = Listing.find(params[:id])
+
+ respond_to do |format|
+ format.html # show.html.erb
+ format.xml { render :xml => @listing }
+ end
+ end
+
+ # GET /listings/new
+ # GET /listings/new.xml
+ def new
+ @listing = Listing.new
+
+ respond_to do |format|
+ format.html # new.html.erb
+ format.xml { render :xml => @listing }
+ end
+ end
+
+ # GET /listings/1/edit
+ def edit
+ @listing = Listing.find(params[:id])
+ end
+
+ # POST /listings
+ # POST /listings.xml
+ def create
+ @listing = Listing.new(params[:listing])
+
+ respond_to do |format|
+ if @listing.save
+ format.html { redirect_to(@listing, :notice => 'Listing was successfully created.') }
+ format.xml { render :xml => @listing, :status => :created, :location => @listing }
+ else
+ format.html { render :action => "new" }
+ format.xml { render :xml => @listing.errors, :status => :unprocessable_entity }
+ end
+ end
+ end
+
+ # PUT /listings/1
+ # PUT /listings/1.xml
+ def update
+ @listing = Listing.find(params[:id])
+
+ respond_to do |format|
+ if @listing.update_attributes(params[:listing])
+ format.html { redirect_to(@listing, :notice => 'Listing was successfully updated.') }
+ format.xml { head :ok }
+ else
+ format.html { render :action => "edit" }
+ format.xml { render :xml => @listing.errors, :status => :unprocessable_entity }
+ end
+ end
+ end
+
+ # DELETE /listings/1
+ # DELETE /listings/1.xml
+ def destroy
+ @listing = Listing.find(params[:id])
+ @listing.destroy
+
+ respond_to do |format|
+ format.html { redirect_to(listings_url) }
+ format.xml { head :ok }
+ end
+ end
+end
35 app/controllers/page_fetches_controller.rb
@@ -0,0 +1,35 @@
+class PageFetchesController < ApplicationController
+ # GET /page_fetches
+ # GET /page_fetches.xml
+ def index
+ @page_fetches = PageFetch.all
+
+ respond_to do |format|
+ format.html # index.html.erb
+ format.xml { render :xml => @page_fetches }
+ end
+ end
+
+ # GET /page_fetches/1
+ # GET /page_fetches/1.xml
+ def show
+ @page_fetch = PageFetch.find(params[:id])
+
+ respond_to do |format|
+ format.html # show.html.erb
+ format.xml { render :xml => @page_fetch }
+ end
+ end
+
+ # DELETE /page_fetches/1
+ # DELETE /page_fetches/1.xml
+ def destroy
+ @page_fetch = PageFetch.find(params[:id])
+ @page_fetch.destroy
+
+ respond_to do |format|
+ format.html { redirect_to(page_fetches_url) }
+ format.xml { head :ok }
+ end
+ end
+end
2 app/helpers/application_helper.rb
@@ -0,0 +1,2 @@
+module ApplicationHelper
+end
2 app/helpers/geocode_fetches_helper.rb
@@ -0,0 +1,2 @@
+module GeocodeFetchesHelper
+end
2 app/helpers/listings_helper.rb
@@ -0,0 +1,2 @@
+module ListingsHelper
+end
2 app/helpers/page_fetches_helper.rb
@@ -0,0 +1,2 @@
+module PageFetchesHelper
+end
28 app/models/geocode_fetch.rb
@@ -0,0 +1,28 @@
+class GeocodeFetch < ActiveRecord::Base
+ serialize :response
+
+ def self.get(fine_location, coarse_location = '')
+ entry = where(:location => fine_location, :city => coarse_location).first
+ unless entry
+ entry = new :location => fine_location, :city => coarse_location,
+ :response => geocode(fine_location, coarse_location)
+ entry.save!
+ end
+ entry.response
+ end
+
+ def self.geocode(fine_location, coarse_location)
+ if coarse_location && coarse_location != ''
+ # TODO: cache these guys as well
+ coarse_result =
+ Geokit::Geocoders::GoogleGeocoder.geocode(coarse_location)
+ bounds = coarse_result && coarse_result.suggested_bounds
+ else
+ bounds = nil
+ end
+
+ result = Geokit::Geocoders::MultiGeocoder.geocode fine_location,
+ :bias => bounds
+ result.hash
+ end
+end
21 app/models/listing.rb
@@ -0,0 +1,21 @@
+class Listing < ActiveRecord::Base
+ acts_as_mappable
+
+ def location=(new_location)
+ super
+ geocode = GeocodeFetch.get location, city
+ self.lat, self.lng = geocode[:lat], geocode[:lng]
+ end
+
+ def geocode_location
+ if location[-2, 2] == 'us'
+ location
+ else
+ [location, city].join ' near '
+ end
+ end
+
+ def self.for_url(url)
+ where(:cl_url => url).first || new(:cl_url => url)
+ end
+end
17 app/models/page_fetch.rb
@@ -0,0 +1,17 @@
+class PageFetch < ActiveRecord::Base
+ def self.get(url)
+ return nil unless page = self.where(:url => url).first
+ return page.contents if page.expires_at > Time.now
+ page.destroy
+ nil
+ end
+
+ def self.put(url, contents, expires_at)
+ page = self.where(:url => url).first
+ page ||= self.new :url => url
+ page.contents = contents
+ page.expires_at = expires_at
+ page.save!
+ page
+ end
+end
22 app/views/geocode_fetches/index.html.erb
@@ -0,0 +1,22 @@
+<h1>Listing geocode_fetches</h1>
+
+<table>
+ <tr>
+ <th>Location</th>
+ <th>City</th>
+ <th>Response</th>
+ <th></th>
+ <th></th>
+ <th></th>
+ </tr>
+
+<% @geocode_fetches.each do |geocode_fetch| %>
+ <tr>
+ <td><%= geocode_fetch.location %></td>
+ <td><%= geocode_fetch.city %></td>
+ <td><%= geocode_fetch.response.to_json %></td>
+ <td><%= link_to 'Show', geocode_fetch %></td>
+ <td><%= link_to 'Destroy', geocode_fetch, :confirm => 'Are you sure?', :method => :delete %></td>
+ </tr>
+<% end %>
+</table>
18 app/views/geocode_fetches/show.html.erb
@@ -0,0 +1,18 @@
+<p id="notice"><%= notice %></p>
+
+<p>
+ <b>Location:</b>
+ <%= @geocode_fetch.location %>
+</p>
+
+<p>
+ <b>City:</b>
+ <%= @geocode_fetch.city %>
+</p>
+
+<p>
+ <b>Response:</b>
+ <%= @geocode_fetch.response.to_json %>
+</p>
+
+<%= link_to 'Back', geocode_fetches_path %>
14 app/views/layouts/application.html.erb
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Craigslist Housing Helper</title>
+ <%= stylesheet_link_tag :all %>
+ <%= javascript_include_tag :defaults %>
+ <%= csrf_meta_tag %>
+</head>
+<body>
+
+<%= yield %>
+
+</body>
+</html>
BIN app/views/listings/index.html.erb
Binary file not shown.
28 app/views/listings/search.html.erb
@@ -0,0 +1,28 @@
+<h1>Listings</h1>
+
+<table>
+ <tr>
+ <th>Price</th>
+ <th>Rooms</th>
+ <th>Location</th>
+ <th>Title</th>
+ <th>Posted at</th>
+ <th>Url</th>
+ <th></th>
+ <th></th>
+ <th></th>
+ </tr>
+
+<% @listings.each do |listing| %>
+ <tr>
+ <td><%= listing.price %></td>
+ <td><%= listing.rooms %></td>
+ <td><%= listing.location %></td>
+ <td><%= listing.title %></td>
+ <td><%= listing.posted_at.strftime('%m/%d %H:%M') %></td>
+ <td><%= link_to listing.cl_url, listing.cl_url %></td>
+ <td><%= link_to 'Show', listing %></td>
+ <td><%= link_to 'Destroy', listing, :confirm => 'Are you sure?', :method => :delete %></td>
+ </tr>
+<% end %>
+</table>
33 app/views/listings/show.html.erb
@@ -0,0 +1,33 @@
+<p id="notice"><%= notice %></p>
+
+<p>
+ <b>Price:</b>
+ <%= @listing.price %>
+</p>
+
+<p>
+ <b>Rooms:</b>
+ <%= @listing.rooms %>
+</p>
+
+<p>
+ <b>Location:</b>
+ <%= @listing.location %>
+</p>
+
+<p>
+ <b>Title:</b>
+ <%= @listing.title %>
+</p>
+
+<p>
+ <b>Posted at:</b>
+ <%= @listing.posted_at %>
+</p>
+
+<p>
+ <b>Url:</b>
+ <%= @listing.cl_url %>
+</p>
+
+<%= link_to 'Back', listings_path %>
22 app/views/page_fetches/index.html.erb
@@ -0,0 +1,22 @@
+<h1>Page Fetches</h1>
+
+<table>
+ <tr>
+ <th>Url</th>
+ <th>Expires at</th>
+ <th>Size</th>
+ <th></th>
+ <th></th>
+ <th></th>
+ </tr>
+
+<% @page_fetches.each do |page_fetch| %>
+ <tr>
+ <td><%= page_fetch.url %></td>
+ <td><%= page_fetch.expires_at %></td>
+ <td><%= page_fetch.contents.length %></td>
+ <td><%= link_to 'Show', page_fetch %></td>
+ <td><%= link_to 'Destroy', page_fetch, :confirm => 'Are you sure?', :method => :delete %></td>
+ </tr>
+<% end %>
+</table>
18 app/views/page_fetches/show.html.erb
@@ -0,0 +1,18 @@
+<p id="notice"><%= notice %></p>
+
+<p>
+ <b>Url:</b>
+ <%= @page_fetch.url %>
+</p>
+
+<p>
+ <b>Expires at:</b>
+ <%= @page_fetch.expires_at %>
+</p>
+
+<p>
+ <b>Contents:</b>
+ <%= @page_fetch.contents %>
+</p>
+
+<%= link_to 'Back', page_fetches_path %>
4 config.ru
@@ -0,0 +1,4 @@
+# This file is used by Rack-based servers to start the application.
+
+require ::File.expand_path('../config/environment', __FILE__)
+run Clh::Application
50 config/application.rb
@@ -0,0 +1,50 @@
+require File.expand_path('../boot', __FILE__)
+
+require 'rails/all'
+
+# If you have a Gemfile, require the gems listed there, including any gems
+# you've limited to :test, :development, or :production.
+Bundler.require(:default, Rails.env) if defined?(Bundler)
+
+module Clh
+ class Application < Rails::Application
+ # Settings in config/environments/* take precedence over those specified here.
+ # Application configuration should go into files in config/initializers
+ # -- all .rb files in that directory are automatically loaded.
+
+ # Custom directories with classes and modules you want to be autoloadable.
+ # config.autoload_paths += %W(#{config.root}/extras)
+ config.autoload_paths += %W(#{config.root}/lib)
+
+ # Only load the plugins named here, in the order given (default is alphabetical).
+ # :all can be used as a placeholder for all plugins not explicitly named.
+ # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
+
+ # Activate observers that should always be running.
+ # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
+
+ # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
+ # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
+ config.time_zone = 'Eastern Time (US & Canada)'
+
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
+ # config.i18n.default_locale = :de
+
+ # JavaScript files you want as :defaults (application.js is always included).
+ # config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
+
+ # Configure generators values. Many other options are available, be sure to check the documentation.
+ # config.generators do |g|
+ # g.orm :active_record
+ # g.template_engine :erb
+ # g.test_framework :test_unit, :fixture => true
+ # end
+
+ # Configure the default encoding used in templates for Ruby 1.9.
+ config.encoding = "utf-8"
+
+ # Configure sensitive parameters which will be filtered from the log file.
+ config.filter_parameters += [:password]
+ end
+end
13 config/boot.rb
@@ -0,0 +1,13 @@
+require 'rubygems'
+
+# Set up gems listed in the Gemfile.
+gemfile = File.expand_path('../../Gemfile', __FILE__)
+begin
+ ENV['BUNDLE_GEMFILE'] = gemfile
+ require 'bundler'
+ Bundler.setup
+rescue Bundler::GemNotFound => e
+ STDERR.puts e.message
+ STDERR.puts "Try running `bundle install`."
+ exit!
+end if File.exist?(gemfile)
38 config/database.yml
@@ -0,0 +1,38 @@
+dev_pgsql: &dev_pgsql
+ adapter: postgresql
+ database: clh_dev
+ username: root
+ password: ""
+
+dev_mysql: &dev_mysql
+ adapter: mysql
+ database: clh_dev
+ username: root
+ password:
+
+test_pgsql: &test_pgsql
+ adapter: postgresql
+ database: clh_test
+ username: root
+ password: ""
+
+test_mysql: &test_mysql
+ adapter: mysql
+ database: clh_test
+ username: root
+ password:
+
+# use *dev_pgsql or *dev_mysql, depending on which db engine you want
+development:
+ <<: *dev_mysql
+
+# Warning: The database defined as 'test' will be erased and
+# re-generated from your development database when you run 'rake'.
+# Do not set this db to the same as development or production.
+test:
+ <<: *test_mysql
+
+# This section is rewritten by rpwn. For development, it's pointing to the
+# -dev database, so we can run the loader scripts in production mode.
+production:
+ <<: *dev_mysql
5 config/environment.rb
@@ -0,0 +1,5 @@
+# Load the rails application
+require File.expand_path('../application', __FILE__)
+
+# Initialize the rails application
+Clh::Application.initialize!
22 config/environments/development.rb
@@ -0,0 +1,22 @@
+Clh::Application.configure do
+ # Settings specified here will take precedence over those in config/environment.rb
+
+ # In the development environment your application's code is reloaded on
+ # every request. This slows down response time but is perfect for development
+ # since you don't have to restart the webserver when you make code changes.
+ config.cache_classes = false
+
+ # Log error messages when you accidentally call methods on nil.
+ config.whiny_nils = true
+
+ # Show full error reports and disable caching
+ config.consider_all_requests_local = true
+ config.action_view.debug_rjs = true
+ config.action_controller.perform_caching = false
+
+ # Don't care if the mailer can't send
+ config.action_mailer.raise_delivery_errors = false
+
+ # Print deprecation notices to the Rails logger
+ config.active_support.deprecation = :log
+end
49 config/environments/production.rb
@@ -0,0 +1,49 @@
+Clh::Application.configure do
+ # Settings specified here will take precedence over those in config/environment.rb
+
+ # The production environment is meant for finished, "live" apps.
+ # Code is not reloaded between requests
+ config.cache_classes = true
+
+ # Full error reports are disabled and caching is turned on
+ config.consider_all_requests_local = false
+ config.action_controller.perform_caching = true
+
+ # Specifies the header that your server uses for sending files
+ config.action_dispatch.x_sendfile_header = "X-Sendfile"
+
+ # For nginx:
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
+
+ # If you have no front-end server that supports something like X-Sendfile,
+ # just comment this out and Rails will serve the files
+
+ # See everything in the log (default is :info)
+ # config.log_level = :debug
+
+ # Use a different logger for distributed setups
+ # config.logger = SyslogLogger.new
+
+ # Use a different cache store in production
+ # config.cache_store = :mem_cache_store
+
+ # Disable Rails's static asset server
+ # In production, Apache or nginx will already do this
+ config.serve_static_assets = false
+
+ # Enable serving of images, stylesheets, and javascripts from an asset server
+ # config.action_controller.asset_host = "http://assets.example.com"
+
+ # Disable delivery errors, bad email addresses will be ignored
+ # config.action_mailer.raise_delivery_errors = false
+
+ # Enable threaded mode
+ # config.threadsafe!
+
+ # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
+ # the I18n.default_locale when a translation can not be found)
+ config.i18n.fallbacks = true
+
+ # Send deprecation notices to registered listeners
+ config.active_support.deprecation = :notify
+end
35 config/environments/test.rb
@@ -0,0 +1,35 @@
+Clh::Application.configure do
+ # Settings specified here will take precedence over those in config/environment.rb
+
+ # The test environment is used exclusively to run your application's
+ # test suite. You never need to work with it otherwise. Remember that
+ # your test database is "scratch space" for the test suite and is wiped
+ # and recreated between test runs. Don't rely on the data there!
+ config.cache_classes = true
+
+ # Log error messages when you accidentally call methods on nil.
+ config.whiny_nils = true
+
+ # Show full error reports and disable caching
+ config.consider_all_requests_local = true
+ config.action_controller.perform_caching = false
+
+ # Raise exceptions instead of rendering exception templates
+ config.action_dispatch.show_exceptions = false
+
+ # Disable request forgery protection in test environment
+ config.action_controller.allow_forgery_protection = false
+
+ # Tell Action Mailer not to deliver emails to the real world.
+ # The :test delivery method accumulates sent emails in the
+ # ActionMailer::Base.deliveries array.
+ config.action_mailer.delivery_method = :test
+
+ # Use SQL instead of Active Record's schema dumper when creating the test database.
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
+ # like if you have constraints or database-specific column types
+ # config.active_record.schema_format = :sql
+
+ # Print deprecation notices to the stderr
+ config.active_support.deprecation = :stderr
+end
7 config/initializers/backtrace_silencers.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
+# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
+
+# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
+# Rails.backtrace_cleaner.remove_silencers!
62 config/initializers/geokit_config.rb
@@ -0,0 +1,62 @@
+if defined? Geokit
+
+ # These defaults are used in Geokit::Mappable.distance_to and in acts_as_mappable
+ Geokit::default_units = :miles
+ Geokit::default_formula = :sphere
+
+ # This is the timeout value in seconds to be used for calls to the geocoder web
+ # services. For no timeout at all, comment out the setting. The timeout unit
+ # is in seconds.
+ Geokit::Geocoders::request_timeout = 3
+
+ # These settings are used if web service calls must be routed through a proxy.
+ # These setting can be nil if not needed, otherwise, addr and port must be
+ # filled in at a minimum. If the proxy requires authentication, the username
+ # and password can be provided as well.
+ Geokit::Geocoders::proxy_addr = nil
+ Geokit::Geocoders::proxy_port = nil
+ Geokit::Geocoders::proxy_user = nil
+ Geokit::Geocoders::proxy_pass = nil
+
+ # This is your yahoo application key for the Yahoo Geocoder.
+ # See http://developer.yahoo.com/faq/index.html#appid
+ # and http://developer.yahoo.com/maps/rest/V1/geocode.html
+ Geokit::Geocoders::yahoo = 'ytbhFBXV34Gs3jG9bnvkwlAkJu_NAcbNRigeEksUkuM3Y7qg7XY_BuV_xEFitak8cMf7'
+
+ # This is your Google Maps geocoder key.
+ # See http://www.google.com/apis/maps/signup.html
+ # and http://www.google.com/apis/maps/documentation/#Geocoding_Examples
+ # Geokit::Geocoders::google = 'ABQIAAAAS7NujCHaPcIJMvXorn0kvhTGVevBfNEiu9r_jEl8GNWZzE8IkxSSKD6lmYdXPixm3Ln51UQdLwtV1w'
+ Geokit::Geocoders::google = 'ABQIAAAAS7NujCHaPcIJMvXorn0kvhT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSq7pq6mbE-jnULTb0S_-AXH9DPSw'
+
+ # This is your username and password for geocoder.us.
+ # To use the free service, the value can be set to nil or false. For
+ # usage tied to an account, the value should be set to username:password.
+ # See http://geocoder.us
+ # and http://geocoder.us/user/signup
+ Geokit::Geocoders::geocoder_us = false
+
+ # This is your authorization key for geocoder.ca.
+ # To use the free service, the value can be set to nil or false. For
+ # usage tied to an account, set the value to the key obtained from
+ # Geocoder.ca.
+ # See http://geocoder.ca
+ # and http://geocoder.ca/?register=1
+ Geokit::Geocoders::geocoder_ca = false
+
+ # Uncomment to use a username with the Geonames geocoder
+ #Geokit::Geocoders::geonames="REPLACE_WITH_YOUR_GEONAMES_USERNAME"
+
+ # This is the order in which the geocoders are called in a failover scenario
+ # If you only want to use a single geocoder, put a single symbol in the array.
+ # Valid symbols are :google, :yahoo, :us, and :ca.
+ # Be aware that there are Terms of Use restrictions on how you can use the
+ # various geocoders. Make sure you read up on relevant Terms of Use for each
+ # geocoder you are going to use.
+ Geokit::Geocoders::provider_order = [:google, :yahoo, :us]
+
+ # The IP provider order. Valid symbols are :ip,:geo_plugin.
+ # As before, make sure you read up on relevant Terms of Use for each
+ # Geokit::Geocoders::ip_provider_order = [:geo_plugin,:ip]
+
+end
10 config/initializers/inflections.rb
@@ -0,0 +1,10 @@
+# Be sure to restart your server when you modify this file.
+
+# Add new inflection rules using the following format
+# (all these examples are active by default):
+# ActiveSupport::Inflector.inflections do |inflect|
+# inflect.plural /^(ox)$/i, '\1en'
+# inflect.singular /^(ox)en/i, '\1'
+# inflect.irregular 'person', 'people'
+# inflect.uncountable %w( fish sheep )
+# end
5 config/initializers/mime_types.rb
@@ -0,0 +1,5 @@
+# Be sure to restart your server when you modify this file.
+
+# Add new mime types for use in respond_to blocks:
+# Mime::Type.register "text/richtext", :rtf
+# Mime::Type.register_alias "text/html", :iphone
7 config/initializers/secret_token.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# Your secret key for verifying the integrity of signed cookies.
+# If you change this key, all old signed cookies will become invalid!
+# Make sure the secret is at least 30 characters and all random,
+# no regular words or you'll be exposed to dictionary attacks.
+Clh::Application.config.secret_token = '090b09e0ad82dadeb3598498f9166e7114d92ea3c5fee599b38714822b4fa05b7d178109d29fd86b77f61e7b58ee3972e9937aec3cf40ae6d1906031c2f67e9b'
8 config/initializers/session_store.rb
@@ -0,0 +1,8 @@
+# Be sure to restart your server when you modify this file.
+
+Clh::Application.config.session_store :cookie_store, :key => '_clh_session'
+
+# Use the database for sessions instead of the cookie-based default,
+# which shouldn't be used to store highly confidential information
+# (create the session table with "rake db:sessions:create")
+# Clh::Application.config.session_store :active_record_store
5 config/locales/en.yml
@@ -0,0 +1,5 @@
+# Sample localization file for English. Add more files in this directory for other locales.
+# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
+
+en:
+ hello: "Hello world"
66 config/routes.rb
@@ -0,0 +1,66 @@
+Clh::Application.routes.draw do
+ resources :geocode_fetches
+
+ resources :page_fetches
+
+ resources :listings do
+ collection { get :search }
+ end
+
+ # The priority is based upon order of creation:
+ # first created -> highest priority.
+
+ # Sample of regular route:
+ # match 'products/:id' => 'catalog#view'
+ # Keep in mind you can assign values other than :controller and :action
+
+ # Sample of named route:
+ # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
+ # This route can be invoked with purchase_url(:id => product.id)
+
+ # Sample resource route (maps HTTP verbs to controller actions automatically):
+ # resources :products
+
+ # Sample resource route with options:
+ # resources :products do
+ # member do
+ # get :short
+ # post :toggle
+ # end
+ #
+ # collection do
+ # get :sold
+ # end
+ # end
+
+ # Sample resource route with sub-resources:
+ # resources :products do
+ # resources :comments, :sales
+ # resource :seller
+ # end
+
+ # Sample resource route with more complex sub-resources
+ # resources :products do
+ # resources :comments
+ # resources :sales do
+ # get :recent, :on => :collection
+ # end
+ # end
+
+ # Sample resource route within a namespace:
+ # namespace :admin do
+ # # Directs /admin/products/* to Admin::ProductsController
+ # # (app/controllers/admin/products_controller.rb)
+ # resources :products
+ # end
+
+ # You can have the root of your site routed with "root"
+ # just remember to delete public/index.html.
+ root :to => "listings#index"
+
+ # See how all your routes lay out with "rake routes"
+
+ # This is a legacy wild controller route that's not recommended for RESTful applications.
+ # Note: This route will make all actions in every controller accessible via GET requests.
+ # match ':controller(/:action(/:id(.:format)))'
+end
20 db/migrate/20100717031511_create_listings.rb
@@ -0,0 +1,20 @@
+class CreateListings < ActiveRecord::Migration
+ def self.up
+ create_table :listings do |t|
+ t.integer :price, :null => false
+ t.integer :rooms, :null => false
+ t.datetime :posted_at, :null => false
+ t.string :cl_url, :limit => 128, :null => false
+ t.string :title, :limit => 128, :null => false
+ t.string :location, :limit => 128, :null => false
+ t.string :city, :limit => 32, :null => false
+ t.decimal :lat, :precision => 14, :scale => 10, :null => false
+ t.decimal :lng, :precision => 14, :scale => 10, :null => false
+ end
+ add_index :listings, :cl_url, :unique => true, :null => false
+ end
+
+ def self.down
+ drop_table :listings
+ end
+end
14 db/migrate/20100717031855_create_page_fetches.rb
@@ -0,0 +1,14 @@
+class CreatePageFetches < ActiveRecord::Migration
+ def self.up
+ create_table :page_fetches do |t|
+ t.string :url, :limit => 128, :null => false
+ t.datetime :expires_at, :null => false
+ t.binary :contents, :limit => 1.megabyte, :null => false
+ end
+ add_index :page_fetches, :url, :unique => true, :null => false
+ end
+
+ def self.down
+ drop_table :page_fetches
+ end
+end
17 db/migrate/20100717075712_create_geocode_fetches.rb
@@ -0,0 +1,17 @@
+class CreateGeocodeFetches < ActiveRecord::Migration
+ def self.up
+ create_table :geocode_fetches do |t|
+ t.string :location, :limit => 128, :null => false
+ t.string :city, :limit => 32, :null => false
+ t.binary :response, :limit => 32.kilobytes, :null => false
+
+ t.timestamps
+ end
+ add_index :geocode_fetches, [:location, :city], :unique => true,
+ :null => false
+ end
+
+ def self.down
+ drop_table :geocode_fetches
+ end
+end
47 db/schema.rb
@@ -0,0 +1,47 @@
+# This file is auto-generated from the current state of the database. Instead
+# of editing this file, please use the migrations feature of Active Record to
+# incrementally modify your database, and then regenerate this schema definition.
+#
+# Note that this schema.rb definition is the authoritative source for your
+# database schema. If you need to create the application database on another
+# system, you should be using db:schema:load, not running all the migrations
+# from scratch. The latter is a flawed and unsustainable approach (the more migrations
+# you'll amass, the slower it'll run and the greater likelihood for issues).
+#
+# It's strongly recommended to check this file into your version control system.
+
+ActiveRecord::Schema.define(:version => 20100717075712) do
+
+ create_table "geocode_fetches", :force => true do |t|
+ t.string "location", :limit => 128, :null => false
+ t.string "city", :limit => 32, :null => false
+ t.binary "response", :null => false
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ add_index "geocode_fetches", ["location", "city"], :name => "index_geocode_fetches_on_location_and_city", :unique => true
+
+ create_table "listings", :force => true do |t|
+ t.integer "price", :null => false
+ t.integer "rooms", :null => false
+ t.datetime "posted_at", :null => false
+ t.string "cl_url", :limit => 128, :null => false
+ t.string "title", :limit => 128, :null => false
+ t.string "location", :limit => 128, :null => false
+ t.string "city", :limit => 32, :null => false
+ t.decimal "lat", :precision => 14, :scale => 10, :null => false
+ t.decimal "lng", :precision => 14, :scale => 10, :null => false
+ end
+
+ add_index "listings", ["cl_url"], :name => "index_listings_on_cl_url", :unique => true
+
+ create_table "page_fetches", :force => true do |t|
+ t.string "url", :limit => 128, :null => false
+ t.datetime "expires_at", :null => false
+ t.binary "contents", :limit => 16777215, :null => false
+ end
+
+ add_index "page_fetches", ["url"], :name => "index_page_fetches_on_url", :unique => true
+
+end
7 db/seeds.rb
@@ -0,0 +1,7 @@
+# This file should contain all the record creation needed to seed the database with its default values.
+# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
+#
+# Examples:
+#
+# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
+# Mayor.create(:name => 'Daley', :city => cities.first)
2 doc/README_FOR_APP
@@ -0,0 +1,2 @@
+Use this README file to introduce your application and point to useful places in the API for learning more.
+Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries.
170 lib/listing_populator.rb
@@ -0,0 +1,170 @@
+class ListingPopulator
+ def run(url, list_limit = 20)
+ list_urls = [url]
+ visited = Set.new([url])
+ i = 0
+ while i < list_limit && i < list_urls.length
+ url = list_urls[i]
+ list = process_list_page url
+ list[:nav].each do |nav_url, nav_anchor|
+ next if visited.include? nav_url
+ list_urls << nav_url
+ visited << nav_url
+ end
+ list[:posts].each do |post_url, post_anchor|
+ process_post_page post_url, post_anchor
+ end
+ i += 1
+ end
+ end
+
+ def process_post_page(url, anchor_text)
+ page = Nokogiri::HTML fetch(url, 14.days)
+ page_text = page.root.inner_text
+
+ page_title = nil
+ page.root.css('h2').each do |heading|
+ text = heading.inner_text
+ if text[0, anchor_text.length] == anchor_text
+ page_title = text
+ break
+ end
+ end
+ return unless page_title
+
+ title_suffix = page_title[(anchor_text.length)..-1]
+
+ # Price
+ return unless match = /^\$(\d+)\s*/.match(page_title)
+ price = match[1].to_i
+ page_title = page_title[(match[0].length)..-1]
+
+
+ # Rooms
+ rooms = nil
+ if /studio/i =~ page_title
+ rooms = 1
+ elsif match = /^\/\s*(\d)\s*br/i.match(page_title)
+ rooms = match[1].to_i
+ page_title = page_title[(match[0].length)..-1]
+ elsif match = /(\d)\s+(br)|(bd)/i.match(page_title)
+ rooms = match[1].to_i
+ else
+ [/(\d)\s*bed/i, /bed\w*\W*(\d)/i].each do |pattern|
+ if match = pattern.match(page_text)
+ rooms = match[1].to_i
+ end
+ end
+ end
+ rooms ||= 10 # Unknown number of rooms -- should be easy to spot.
+
+ # City.
+ city = nil
+ page.root.css('div.bchead').css('a').each do |link|
+ link_text = link.inner_text.downcase
+ if match = /^(.*)\s+craigslist\s*$/.match(link_text)
+ city = match[1]
+ break
+ end
+ end
+ return unless city
+
+ # Location by mapping.
+ location = nil
+ page.root.css('a').each do |link|
+ next unless href = link['href']
+ if match = /maps\.google\.com\/.*q\=([^&]+)/.match(href)
+ location = URI.decode match[1]
+ location = location[4..-1] if location[0, 3] == 'loc'
+ break
+ end
+ end
+ # Location by text link.
+ unless location
+ if match = /\s*\(([^()]+)\)\s*$/.match(title_suffix)
+ location = match[1]
+ page_title = page_title[0...(-match[0].length)]
+ elsif match = /\s*\(([^()]+)\)\s*$/.match(page_title)
+ location = match[1].gsub(',', '')
+ page_title = page_title[0...(-match[0].length)]
+ else
+ location = 'Unknown'
+ end
+ end
+
+ # Posting date
+ date_regexp = /date:\s*(\d{2,4}\-\d{1,2}\-\d{1,2}.{0,5}\d{1,2}\:\d\d\s*\w{0,2}\s*\w{0,5})/i
+ if match = date_regexp.match(page_text)
+ posted_at = Time.parse match[1]
+ else
+ return
+ end
+
+ listing = Listing.for_url url
+ listing.price = price
+ listing.rooms = rooms
+ listing.city = clean_location city
+ listing.location = clean_location location
+ listing.posted_at = posted_at
+ listing.title = clean_title page_title
+ listing.save!
+ end
+
+ def clean_location(raw_location)
+ location = raw_location.downcase
+ location.gsub! /[^a-z0-9.,&]/, ' '
+ location.gsub! /\s+/, ' '
+ location.strip!
+ location
+ end
+
+ def clean_title(raw_title)
+ title = raw_title.downcase
+ title.gsub! /[^a-z0-9.,?\/:&]/, ' '
+ title.gsub! '\s+', ' '
+ title.gsub! /([^a-z0-9 ])[^a-z0-9 ]+/, '\1'
+ title.strip!
+ title
+ end
+
+ def clean_link(rel_url, page_url)
+ URI.parse(page_url).merge(rel_url).to_s
+ end
+
+ def process_list_page(url)
+ page = Nokogiri::HTML fetch(url)
+ post_links = []
+ nav_links = []
+ page.root.css('a').each do |link|
+ next unless link_target = link['href']
+ link_text = link.inner_text
+ case link_target
+ when /index\d+.html?$/
+ link_target = clean_link link_target, url
+ nav_links << [link_target, link_text]
+ when /\.craigslist.org\/.*\/\d+\.html?$/
+ post_links << [link_target, link_text]
+ end
+ end
+ { :posts => post_links, :nav => nav_links }
+ end
+
+ def fetch(url, cache_time = 1.minute)
+ unless body = PageFetch.get(url)
+ body = agent.get_file url
+ expires_at = Time.now + cache_time
+ PageFetch.put url, body, expires_at
+ end
+ body
+ end
+
+ def agent
+ @agent ||= Mechanize.new do |a|
+ a.user_agent_alias = 'Mac Safari'
+ end
+ end
+
+ def initialize
+ @agent = nil
+ end
+end
0 lib/tasks/.gitkeep
No changes.
26 public/404.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The page you were looking for doesn't exist (404)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/404.html -->
+ <div class="dialog">
+ <h1>The page you were looking for doesn't exist.</h1>
+ <p>You may have mistyped the address or the page may have moved.</p>
+ </div>
+</body>
+</html>
26 public/422.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The change you wanted was rejected (422)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/422.html -->
+ <div class="dialog">
+ <h1>The change you wanted was rejected.</h1>
+ <p>Maybe you tried to change something you didn't have access to.</p>
+ </div>
+</body>
+</html>
26 public/500.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>We're sorry, but something went wrong (500)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/500.html -->
+ <div class="dialog">
+ <h1>We're sorry, but something went wrong.</h1>
+ <p>We've been notified about this issue and we'll take a look at it shortly.</p>
+ </div>
+</body>
+</html>
0 public/favicon.ico
No changes.
BIN public/images/rails.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 public/javascripts/application.js
@@ -0,0 +1,2 @@
+// Place your application-specific JavaScript functions and classes here
+// This file is automatically included by javascript_include_tag :defaults
965 public/javascripts/controls.js
@@ -0,0 +1,965 @@
+// script.aculo.us controls.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// (c) 2005-2009 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
+// (c) 2005-2009 Jon Tirsen (http://www.tirsen.com)
+// Contributors:
+// Richard Livsey
+// Rahul Bhargava
+// Rob Wills
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+// Autocompleter.Base handles all the autocompletion functionality
+// that's independent of the data source for autocompletion. This
+// includes drawing the autocompletion menu, observing keyboard
+// and mouse events, and similar.
+//
+// Specific autocompleters need to provide, at the very least,
+// a getUpdatedChoices function that will be invoked every time
+// the text inside the monitored textbox changes. This method
+// should get the text for which to provide autocompletion by
+// invoking this.getToken(), NOT by directly accessing
+// this.element.value. This is to allow incremental tokenized
+// autocompletion. Specific auto-completion logic (AJAX, etc)
+// belongs in getUpdatedChoices.
+//
+// Tokenized incremental autocompletion is enabled automatically
+// when an autocompleter is instantiated with the 'tokens' option
+// in the options parameter, e.g.:
+// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
+// will incrementally autocomplete with a comma as the token.
+// Additionally, ',' in the above example can be replaced with
+// a token array, e.g. { tokens: [',', '\n'] } which
+// enables autocompletion on multiple tokens. This is most
+// useful when one of the tokens is \n (a newline), as it
+// allows smart autocompletion after linebreaks.
+
+if(typeof Effect == 'undefined')
+ throw("controls.js requires including script.aculo.us' effects.js library");
+
+var Autocompleter = { };
+Autocompleter.Base = Class.create({
+ baseInitialize: function(element, update, options) {
+ element = $(element);
+ this.element = element;
+ this.update = $(update);
+ this.hasFocus = false;
+ this.changed = false;
+ this.active = false;
+ this.index = 0;
+ this.entryCount = 0;
+ this.oldElementValue = this.element.value;
+
+ if(this.setOptions)
+ this.setOptions(options);
+ else
+ this.options = options || { };
+
+ this.options.paramName = this.options.paramName || this.element.name;
+ this.options.tokens = this.options.tokens || [];
+ this.options.frequency = this.options.frequency || 0.4;
+ this.options.minChars = this.options.minChars || 1;
+ this.options.onShow = this.options.onShow ||
+ function(element, update){
+ if(!update.style.position || update.style.position=='absolute') {
+ update.style.position = 'absolute';
+ Position.clone(element, update, {
+ setHeight: false,
+ offsetTop: element.offsetHeight
+ });
+ }
+ Effect.Appear(update,{duration:0.15});
+ };
+ this.options.onHide = this.options.onHide ||
+ function(element, update){ new Effect.Fade(update,{duration:0.15}) };
+
+ if(typeof(this.options.tokens) == 'string')
+ this.options.tokens = new Array(this.options.tokens);
+ // Force carriage returns as token delimiters anyway
+ if (!this.options.tokens.include('\n'))
+ this.options.tokens.push('\n');
+
+ this.observer = null;
+
+ this.element.setAttribute('autocomplete','off');
+
+ Element.hide(this.update);
+
+ Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
+ Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
+ },
+
+ show: function() {
+ if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
+ if(!this.iefix &&
+ (Prototype.Browser.IE) &&
+ (Element.getStyle(this.update, 'position')=='absolute')) {
+ new Insertion.After(this.update,
+ '<iframe id="' + this.update.id + '_iefix" '+
+ 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
+ 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
+ this.iefix = $(this.update.id+'_iefix');
+ }
+ if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
+ },
+
+ fixIEOverlapping: function() {
+ Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
+ this.iefix.style.zIndex = 1;
+ this.update.style.zIndex = 2;
+ Element.show(this.iefix);
+ },
+
+ hide: function() {
+ this.stopIndicator();
+ if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
+ if(this.iefix) Element.hide(this.iefix);
+ },
+
+ startIndicator: function() {
+ if(this.options.indicator) Element.show(this.options.indicator);
+ },
+
+ stopIndicator: function() {
+ if(this.options.indicator) Element.hide(this.options.indicator);
+ },
+
+ onKeyPress: function(event) {
+ if(this.active)
+ switch(event.keyCode) {
+ case Event.KEY_TAB:
+ case Event.KEY_RETURN:
+ this.selectEntry();
+ Event.stop(event);
+ case Event.KEY_ESC:
+ this.hide();
+ this.active = false;
+ Event.stop(event);
+ return;
+ case Event.KEY_LEFT:
+ case Event.KEY_RIGHT:
+ return;
+ case Event.KEY_UP:
+ this.markPrevious();
+ this.render();
+ Event.stop(event);
+ return;
+ case Event.KEY_DOWN:
+ this.markNext();
+ this.render();
+ Event.stop(event);
+ return;
+ }
+ else
+ if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
+ (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
+
+ this.changed = true;
+ this.hasFocus = true;
+
+ if(this.observer) clearTimeout(this.observer);
+ this.observer =
+ setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
+ },
+
+ activate: function() {
+ this.changed = false;
+ this.hasFocus = true;
+ this.getUpdatedChoices();
+ },
+
+ onHover: function(event) {
+ var element = Event.findElement(event, 'LI');
+ if(this.index != element.autocompleteIndex)
+ {
+ this.index = element.autocompleteIndex;
+ this.render();
+ }
+ Event.stop(event);
+ },
+
+ onClick: function(event) {
+ var element = Event.findElement(event, 'LI');
+ this.index = element.autocompleteIndex;
+ this.selectEntry();
+ this.hide();
+ },
+
+ onBlur: function(event) {
+ // needed to make click events working
+ setTimeout(this.hide.bind(this), 250);
+ this.hasFocus = false;
+ this.active = false;
+ },
+
+ render: function() {
+ if(this.entryCount > 0) {
+ for (var i = 0; i < this.entryCount; i++)
+ this.index==i ?
+ Element.addClassName(this.getEntry(i),"selected") :
+ Element.removeClassName(this.getEntry(i),"selected");
+ if(this.hasFocus) {
+ this.show();
+ this.active = true;
+ }
+ } else {
+ this.active = false;
+ this.hide();
+ }
+ },
+
+ markPrevious: function() {
+ if(this.index > 0) this.index--;
+ else this.index = this.entryCount-1;
+ this.getEntry(this.index).scrollIntoView(true);
+ },
+
+ markNext: function() {
+ if(this.index < this.entryCount-1) this.index++;
+ else this.index = 0;
+ this.getEntry(this.index).scrollIntoView(false);
+ },
+
+ getEntry: function(index) {
+ return this.update.firstChild.childNodes[index];
+ },
+
+ getCurrentEntry: function() {
+ return this.getEntry(this.index);
+ },
+
+ selectEntry: function() {
+ this.active = false;
+ this.updateElement(this.getCurrentEntry());
+ },
+
+ updateElement: function(selectedElement) {
+ if (this.options.updateElement) {
+ this.options.updateElement(selectedElement);
+ return;
+ }
+ var value = '';
+ if (this.options.select) {
+ var nodes = $(selectedElement).select('.' + this.options.select) || [];
+ if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
+ } else
+ value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
+
+ var bounds = this.getTokenBounds();
+ if (bounds[0] != -1) {
+ var newValue = this.element.value.substr(0, bounds[0]);
+ var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
+ if (whitespace)
+ newValue += whitespace[0];
+ this.element.value = newValue + value + this.element.value.substr(bounds[1]);
+ } else {
+ this.element.value = value;
+ }
+ this.oldElementValue = this.element.value;
+ this.element.focus();
+
+ if (this.options.afterUpdateElement)
+ this.options.afterUpdateElement(this.element, selectedElement);
+ },
+
+ updateChoices: function(choices) {
+ if(!this.changed && this.hasFocus) {
+ this.update.innerHTML = choices;
+ Element.cleanWhitespace(this.update);
+ Element.cleanWhitespace(this.update.down());
+
+ if(this.update.firstChild && this.update.down().childNodes) {
+ this.entryCount =
+ this.update.down().childNodes.length;
+ for (var i = 0; i < this.entryCount; i++) {
+ var entry = this.getEntry(i);
+ entry.autocompleteIndex = i;
+ this.addObservers(entry);
+ }
+ } else {
+ this.entryCount = 0;
+ }
+
+ this.stopIndicator();
+ this.index = 0;
+
+ if(this.entryCount==1 && this.options.autoSelect) {
+ this.selectEntry();
+ this.hide();
+ } else {
+ this.render();
+ }
+ }
+ },
+
+ addObservers: function(element) {
+ Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
+ Event.observe(element, "click", this.onClick.bindAsEventListener(this));
+ },
+
+ onObserverEvent: function() {
+ this.changed = false;
+ this.tokenBounds = null;
+ if(this.getToken().length>=this.options.minChars) {
+ this.getUpdatedChoices();
+ } else {
+ this.active = false;
+ this.hide();
+ }
+ this.oldElementValue = this.element.value;
+ },
+
+ getToken: function() {
+ var bounds = this.getTokenBounds();
+ return this.element.value.substring(bounds[0], bounds[1]).strip();
+ },
+
+ getTokenBounds: function() {
+ if (null != this.tokenBounds) return this.tokenBounds;
+ var value = this.element.value;
+ if (value.strip().empty()) return [-1, 0];
+ var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
+ var offset = (diff == this.oldElementValue.length ? 1 : 0);
+ var prevTokenPos = -1, nextTokenPos = value.length;
+ var tp;
+ for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
+ tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
+ if (tp > prevTokenPos) prevTokenPos = tp;
+ tp = value.indexOf(this.options.tokens[index], diff + offset);
+ if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
+ }
+ return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
+ }
+});
+
+Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
+ var boundary = Math.min(newS.length, oldS.length);
+ for (var index = 0; index < boundary; ++index)
+ if (newS[index] != oldS[index])
+ return index;
+ return boundary;
+};
+
+Ajax.Autocompleter = Class.create(Autocompleter.Base, {
+ initialize: function(element, update, url, options) {
+ this.baseInitialize(element, update, options);
+ this.options.asynchronous = true;
+ this.options.onComplete = this.onComplete.bind(this);
+ this.options.defaultParams = this.options.parameters || null;
+ this.url = url;
+ },
+
+ getUpdatedChoices: function() {
+ this.startIndicator();
+
+ var entry = encodeURIComponent(this.options.paramName) + '=' +
+ encodeURIComponent(this.getToken());
+
+ this.options.parameters = this.options.callback ?
+ this.options.callback(this.element, entry) : entry;
+
+ if(this.options.defaultParams)
+ this.options.parameters += '&' + this.options.defaultParams;
+
+ new Ajax.Request(this.url, this.options);
+ },
+
+ onComplete: function(request) {
+ this.updateChoices(request.responseText);
+ }
+});
+
+// The local array autocompleter. Used when you'd prefer to
+// inject an array of autocompletion options into the page, rather
+// than sending out Ajax queries, which can be quite slow sometimes.
+//
+// The constructor takes four parameters. The first two are, as usual,
+// the id of the monitored textbox, and id of the autocompletion menu.
+// The third is the array you want to autocomplete from, and the fourth
+// is the options block.
+//
+// Extra local autocompletion options:
+// - choices - How many autocompletion choices to offer
+//
+// - partialSearch - If false, the autocompleter will match entered
+// text only at the beginning of strings in the
+// autocomplete array. Defaults to true, which will
+// match text at the beginning of any *word* in the
+// strings in the autocomplete array. If you want to
+// search anywhere in the string, additionally set
+// the option fullSearch to true (default: off).
+//
+// - fullSsearch - Search anywhere in autocomplete array strings.
+//
+// - partialChars - How many characters to enter before triggering
+// a partial match (unlike minChars, which defines
+// how many characters are required to do any match
+// at all). Defaults to 2.
+//
+// - ignoreCase - Whether to ignore case when autocompleting.
+// Defaults to true.
+//
+// It's possible to pass in a custom function as the 'selector'
+// option, if you prefer to write your own autocompletion logic.
+// In that case, the other options above will not apply unless
+// you support them.
+
+Autocompleter.Local = Class.create(Autocompleter.Base, {
+ initialize: function(element, update, array, options) {
+ this.baseInitialize(element, update, options);
+ this.options.array = array;
+ },
+
+ getUpdatedChoices: function() {
+ this.updateChoices(this.options.selector(this));
+ },
+
+ setOptions: function(options) {
+ this.options = Object.extend({
+ choices: 10,
+ partialSearch: true,
+ partialChars: 2,
+ ignoreCase: true,
+ fullSearch: false,
+ selector: function(instance) {
+ var ret = []; // Beginning matches
+ var partial = []; // Inside matches
+ var entry = instance.getToken();
+ var count = 0;
+
+ for (var i = 0; i < instance.options.array.length &&
+ ret.length < instance.options.choices ; i++) {