code
stringlengths
1
1.73M
language
stringclasses
1 value
class CreateSources < ActiveRecord::Migration def self.up create_table :sources do |t| t.string :name t.string :type t.string :url t.timestamps end end def self.down drop_table :sources end end
Ruby
class DropFilters < ActiveRecord::Migration def self.up drop_table :filters end def self.down end end
Ruby
class RemoveUrlsAndTaggings < ActiveRecord::Migration def self.up drop_table :urls drop_table :url_refs drop_table :taggings drop_table :tags end def self.down end end
Ruby
class AddAuthoredAtIndexToReports < ActiveRecord::Migration def self.up add_index(:reports, [:authored_at]) end def self.down remove_index(:reports, [:authored_at]) end end
Ruby
class AddOffsetToSources < ActiveRecord::Migration def self.up add_column :sources, :offset, :integer end def self.down remove_column :sources, :offset end end
Ruby
class AddNewIndices < ActiveRecord::Migration def self.up add_index(:authors, [:name]) add_index(:reports, [:source_id]) add_index(:reports, [:author_id]) add_index(:reports, [:created_at]) execute("create unique index index_reports_on_author_id_and_title_and_content on reports (author_id, title, ...
Ruby
class CreateFilters < ActiveRecord::Migration def self.up create_table :filters do |t| t.integer :timespan_id t.string :ref t.timestamps end end def self.down drop_table :filters end end
Ruby
class CreateTags < ActiveRecord::Migration def self.up create_table :tags do |t| t.string :name t.boolean :is_hash t.timestamps end end def self.down drop_table :tags end end
Ruby
class CreateEntityAssocs < ActiveRecord::Migration def self.up create_table :entity_assocs do |t| t.integer :report_id t.integer :entity_id t.timestamps end add_index(:entity_assocs, [:report_id, :entity_id], :unique => true) end def self.down drop_table :entity_assocs e...
Ruby
class AddImportantIndexToReports < ActiveRecord::Migration def self.up add_index(:reports, [:important]) end def self.down end end
Ruby
class AddIsSearchChunkToTimespans < ActiveRecord::Migration def self.up add_column :timespans, :is_search_chunk, :boolean # Add some initial search chunk timespans d = CONF.chunk_start_time while d < Time.now do Timespan.create(:after_date => d, :before_date => d + CONF.chunk_size, :is_sear...
Ruby
class AddMarkReasonToReports < ActiveRecord::Migration def self.up add_column :reports, :mark_reason, :string end def self.down remove_column :reports, :mark_reason end end
Ruby
class CreateBatches < ActiveRecord::Migration def self.up create_table :batches do |t| t.timestamps end end def self.down drop_table :batches end end
Ruby
class CreateIncidentStatusChanges < ActiveRecord::Migration def self.up create_table :incident_status_changes do |t| t.integer :incident_id t.string :old_status t.string :new_status t.timestamps end add_index(:incident_status_changes, [:incident_id]) end def self.down rem...
Ruby
class CreateCategories < ActiveRecord::Migration def self.up create_table :categories do |t| t.string :name t.integer :parent_id t.timestamps end end def self.down drop_table :categories end end
Ruby
class AddIsPuToPlace < ActiveRecord::Migration def self.up add_column :places, :is_pu, :boolean execute("update places set is_pu = 1"); end def self.down remove_column :places, :is_pu end end
Ruby
class CreateJobRuns < ActiveRecord::Migration def self.up create_table :job_runs do |t| t.integer :job_id t.integer :crawl_id t.datetime :finished_at t.string :error t.timestamps end end def self.down drop_table :job_runs end end
Ruby
class CreateTaggings < ActiveRecord::Migration def self.up create_table :taggings do |t| t.integer :report_id t.integer :tag_id t.timestamps end end def self.down drop_table :taggings end end
Ruby
class RemoveOldCrawlerClasses < ActiveRecord::Migration def self.up drop_table :crawls drop_table :jobs drop_table :job_runs drop_table :job_run_pieces drop_table :source_events end def self.down end end
Ruby
class AddDuplicatesToScrape < ActiveRecord::Migration def self.up add_column :scrapes, :duplicates, :integer end def self.down remove_column :scrapes, :duplicates end end
Ruby
class CreateAuthors < ActiveRecord::Migration def self.up create_table :authors do |t| t.string :name t.timestamps end end def self.down drop_table :authors end end
Ruby
class RemoveAuthorFromReport < ActiveRecord::Migration def self.up remove_column :reports, :author end def self.down add_column :reports, :author, :string end end
Ruby
class CreateSettings < ActiveRecord::Migration def self.up create_table :settings do |t| t.string :timezone t.string :webmaster_email t.timestamps end end def self.down drop_table :settings end end
Ruby
class AddLatestAuthoredAtToSources < ActiveRecord::Migration def self.up add_column :sources, :latest_authored_at, :datetime end def self.down remove_column :sources, :latest_authored_at end end
Ruby
class CreateSearches < ActiveRecord::Migration def self.up create_table :searches do |t| t.string :query t.datetime :last_run_at t.timestamps end end def self.down drop_table :searches end end
Ruby
class AddDigestToReports < ActiveRecord::Migration def self.up add_column :reports, :digest, :string add_index :reports, [:digest] end def self.down #remove_column :reports, :hash end end
Ruby
class CreateIncidents < ActiveRecord::Migration def self.up create_table :incidents do |t| t.string :title t.integer :category_id t.integer :place_id t.text :notes t.string :status t.decimal :lat, :precision => 20, :scale => 15 t.decimal :lng, :precision => 20, :scale => ...
Ruby
class AddAuthorToReports < ActiveRecord::Migration def self.up add_column :reports, :author, :string execute("update reports r, authors a set r.author=a.name where r.author_id=a.id") add_index(:reports, [:author]) drop_table(:authors) end def self.down end end
Ruby
class CreateCrawls < ActiveRecord::Migration def self.up create_table :crawls do |t| t.integer :crawler_id t.datetime :finished_at t.timestamps end end def self.down drop_table :crawls end end
Ruby
class CreateSearchRuns < ActiveRecord::Migration def self.up create_table :search_runs do |t| t.integer :search_id t.integer :timespan_id t.integer :num t.timestamps end end def self.down drop_table :search_runs end end
Ruby
class DropSourceType < ActiveRecord::Migration def self.up drop_table :source_types end def self.down end end
Ruby
class AddOrigIdToReports < ActiveRecord::Migration def self.up add_column :reports, :orig_id, :string end def self.down remove_column :reports, :orig_id end end
Ruby
class CreateGroupingAnalytics < ActiveRecord::Migration def self.up create_table :grouping_analytics do |t| t.string :name t.string :search_term t.text :sql t.timestamps end # add a few (put limit 1, which will be replaced) GroupingAnalytic.create(:name => "Top Tags", :se...
Ruby
ENV["RAILS_ENV"] = "test" require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' class ActiveSupport::TestCase # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order. # # Note: You'll currently still have to declare fixtures explicitly in integrati...
Ruby
source 'http://rubygems.org' gem 'rails', '3.0.19' gem 'json' gem 'mysql' gem 'libxml-ruby' gem 'will_paginate', '3.0.pre2' gem 'configatron' gem 'tweetstream' gem 'feedzirra' gem 'rake', "0.8.7" gem 'fgraph'
Ruby
#!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. APP_PATH = File.expand_path('../../config/application', __FILE__) require File.expand_path('../../config/boot', __FILE__) require 'rails/commands'
Ruby
module ApplicationHelper def flash_and_form_errors(object = nil) render("layouts/flash", :flash => flash, :object => object) end # draws a basic form for the given object def basic_form(obj, &block) form_for(obj) do |f| f.mode = controller.action_name.to_sym # get the fields spec spec ...
Ruby
module BatchesHelper def batches_index_fields(options) %w[authored sourcename author content] end def batches_format_field(obj, field, options) reports_format_field(obj, field, options) end def batches_index_links(objs, options) [ batch_op_link(:name => "Finish", :action => "batches#fi...
Ruby
module SourcesHelper def sources_index_fields(options) %w[name kind url enabled? keywords languages actions] end def sources_format_field(obj, field, options) case field when "type" then obj.type.gsub(/Source$/, "") when "actions" link_to("Edit", edit_source_path(obj)) + " | " + link_t...
Ruby
module CategoriesHelper def categories_index_fields(options) %w[name parent actions] end def categories_format_field(obj, field, options) case field when "name" obj.full_name when "parent" obj.parent.name rescue "[none]" when "actions" action_links(obj, :exclude => :show) ...
Ruby
module ReportsHelper def reports_index_fields(options) %w[authored sourcename author content pertinent incidents] end def reports_format_field(obj, field, options) case field when "sourcename" link_to(obj.send(field), edit_source_path(obj.source_id)) when "incidents" (obj.incidents....
Ruby
module RulesHelper def rules_index_fields(options) %w[id search_query actions] end def rules_format_field(obj, field, options) case field when "id" "#" + obj.id.to_s.rjust(3, "0") when "actions" link_to("Delete", rule_path(obj), :method => :delete, :confirm => "Are you sure you want to...
Ruby
module IncidentsHelper def incidents_index_fields(options) %w[id category_name title num_rpts status place_name last_updated actions] end def incidents_format_field(obj, field, options) case field when "id" "#" + obj.id.to_s.rjust(3, "0") when "last_updated" distance_of_time_in_word...
Ruby
class AdminMailer < ActionMailer::Base default :from => CONF.site_email def error(exception, session = nil, params = nil, env = nil) @exception = exception @session = session @params = params @env = env path = env && (": " + env['REQUEST_URI']) || "" mail(:to => CONF.webmaster_emails, :su...
Ruby
# a post or update from one of the sources. this is the central object in the system. class Report < ActiveRecord::Base belongs_to(:source) has_many(:incident_reports) has_many(:incidents, :through => :incident_reports) before_create(:strip_html) #before_save(:check_for_duplicates) scope(:unmarked, wh...
Ruby
class Crawler::TrendJob < Crawler::Job def run log_info("Running searches") start_time = Time.now Search.run_saved finish_time = Time.now elapsed = (finish_time - start_time).to_f.round(1) log_info("Searches complete (#{elapsed} s).") @deadline = Time.now + 5.minutes end end
Ruby
class Crawler::SourceMonitorJob < Crawler::Job def initialize(crawler) super(crawler) # at first, set deadline to immediate b/c sources are needed @deadline = Time.now end def run # updates sources from database, detecting any changes made by other processes. if @crawler.sources.nil...
Ruby
class Crawler::RuleJob < Crawler::Job def run log_info("Applying rules") start_time = Time.now Rule.apply_all finish_time = Time.now elapsed = (finish_time - start_time).to_f.round(1) log_info("Rule application complete (#{elapsed} s).") @deadline = Time.now + 30.seconds end e...
Ruby
class Crawler::Job attr_accessor :deadline def self.create_all(crawler) [ Crawler::SourceMonitorJob.new(crawler), Crawler::FetchJob.new(crawler), Crawler::TrendJob.new(crawler), Crawler::RuleJob.new(crawler) ] end def initialize(crawler) @crawler = crawler update_de...
Ruby
class Crawler::BatchJob < Crawler::Job end
Ruby
class Crawler::FetchJob < Crawler::Job def run # sort jobs by deadline and get first next_src = @crawler.sources.reject{|s| !s.enabled}.sort_by{|s| s.deadline}.first # if no sources, do nothing if next_src.nil? log_info("No enabled sources to fetch.") # if deadline is in past, run...
Ruby
# a background processor that retrieves reports, runs searches, and does other housekeeping. class Crawler::Crawler < ActiveRecord::Base before_create(:remove_others) after_create(:write_pid) attr_accessor(:sources) VERBOSITY = 1 # can be 1 (low), 2, 3 (high) # returns the current crawler if it is runni...
Ruby
require 'open-uri' require 'fileutils' # one source of reports (e.g. Joe's blog, Fatima's Facebook group) class Source < ActiveRecord::Base has_many(:reports) validates(:name, :presence => true, :uniqueness => true, :format => {:with => /^[a-z0-9 ]+$/i}) validates(:kind, :presence => true) validate(:only_on...
Ruby
# a facebook group source # TODO: prevent duplicates when new comments are added # TODO: fix auth class FacebookGroupSource < Source MAX_PER_FETCH = 25 def fetch super fetched = 0 done = false # this is the proper way, but not working #token = FGraph.oauth_access_token('283815398303966',...
Ruby
class Timespan < ActiveRecord::Base has_many(:search_runs) has_many(:searches, :through => :search_runs) def self.common find(:all, :conditions => "is_common=1", :order => "before_offset desc, before_date desc") end def self.find_chunks_between(start, stop) find(:all, :conditions => ["is_search_...
Ruby
# one token or term in a search class SearchToken FIELDS = %w(sourcename sourcetype title content author before after pertinent report-id duplicate-of) REGEXP_FIELDS = %w(sourcename sourcetype title content author) DEFAULT_FIELDS = %w(title content author) def initialize(str) @str = str end # returns...
Ruby
# one run of a search, including most importantly the result class SearchRun < ActiveRecord::Base belongs_to(:search) belongs_to(:timespan) def self.last_run find(:first, :order => "created_at desc").updated_at rescue nil end # updates or creates the search run with the given search id and timespan ...
Ruby
# association between an incident and a report class IncidentReport < ActiveRecord::Base belongs_to(:incident) belongs_to(:report) end
Ruby
# a batch of records to be scanned. currently nothing needed in model. class Batch < ActiveRecord::Base end
Ruby
require 'feedzirra' class RssSource < Source def fetch super # load the items feed = Feedzirra::Feed.fetch_and_parse(url) # save the max latest_time (this is in case the feed entries are not sorted by date) old_latest = latest_authored_at.dup rescue nil fetched = 0 # for e...
Ruby
class User < ActiveRecord::Base end
Ruby
class TwitterSource < Source def fetch super # if we have a thread obj already, make sure it's alive. otherwise create a thread reason = nil if !@thread reason = "Stream thread doesn't exist. Restarting stream." elsif !@thread.alive? puts @thread.inspect reason = "Stream thr...
Ruby
# a category for incidents. supports hierarchies. should probably change this to a tagging setup. class Category < ActiveRecord::Base belongs_to(:parent, :class_name => "Category") has_many(:children, :foreign_key => "parent_id", :class_name => "Category") # before destroy check for stuff before_destroy(:che...
Ruby
# a particular search of the reports # searches can be saved and run on a regular basis class Search < ActiveRecord::Base has_many(:search_runs, :include => :timespan, :order => "timespans.after_date") has_many(:rules) # converts the given query to canonical format such that any two queries with the same # s...
Ruby
# a grouping of reports into a single event or occurrence, allowing tracking and annotation class Incident < ActiveRecord::Base has_many(:incident_reports, :dependent => :destroy) has_many(:reports, :through => :incident_reports) belongs_to(:category) before_save(:ensure_status) scope(:for_index, inclu...
Ruby
# models all the user-configurable settings in the app # there should only therefore need to be one row in this table class Setting < ActiveRecord::Base validates(:webmaster_email, :presence => true) validates(:timezone, :presence => true) after_save(:copy_to_config) # loads the one and only row def self.g...
Ruby
# an automatically applied search. reports matching this search are automatically marked important. class Rule < ActiveRecord::Base belongs_to(:search) # applies all rules in a transaction def self.apply_all transaction do cutoff = (Time.now.utc - 1.hour).basic_format # apply all.each{|a...
Ruby
module Crawler def self.table_name_prefix '' end end
Ruby
class RulesController < ApplicationController def index @new_rule = Rule.new @search = Search.new @rules = Rule.all end def create # create the search search = Search.find_or_create_by_query(params[:search][:query]) # create the rule Rule.find_or_create_by_search_id(search.id) ...
Ruby
class ReportsController < ApplicationController def index @search = session[:search] || Search.new @impt_search = Search.find_or_create_by_query("pertinent:yes") begin @reports = Report.all_by_page(params[:page], @search.conditions) render(:partial => "table_only", :locals => {:reports => @rep...
Ruby
class ApplicationController < ActionController::Base protect_from_forgery rescue_from(Exception, :with => :notify_error) before_filter(:set_default_title) before_filter(:get_crawler) before_filter(:login_required) before_filter(:set_timezone) protected def login_required redirect_to(welcome_u...
Ruby
class CategoriesController < ApplicationController def index @categories = Category.all end def new @category = Category.new end def edit @category = Category.find(params[:id]) end def create @category = Category.new(params[:category]) if @category.save redirect_to(categories_...
Ruby
class BatchesController < ApplicationController def new @title = "Batch Scan" # mark a batch with the session id and then load them sid = session[:session_id] Report.checkout_batch(sid) @reports = Report.batch(sid) end def finish finish_batch redirect_to(reports_path) end def...
Ruby
class CrawlersController < ApplicationController def log @log = Crawler::Crawler.log(50) @title = "Crawler Log" render(:partial => "log") if ajax_request? end end
Ruby
class UsersController < ApplicationController def welcome @title = "Login" end def create # if this is really a login, redirect login if params[:login] end def login pass = params[:user][:password] the_user = User.find(:first) if pass == the_user.password session[:user] = t...
Ruby
class SourcesController < ApplicationController def index @sources = Source.sorted(:paginate => true, :page => params[:page]) end def new @source = Source.new end def create @source = Source.new(params[:source]) if @source.save flash[:success] = "Source created successfully." ...
Ruby
class SearchesController < ApplicationController def index @title = "Trends" @searches = Search.find_all_by_is_saved(true) @timespans = Timespan.paginate_default_to_last(params[:page]) @new_search = Search.new(:is_saved => true) end def create update end def update ref = params[:ref] ...
Ruby
class SettingsController < ApplicationController def index @setting = Setting.get render(:action => :edit) end def update @setting = Setting.find(params[:id]) if @setting.update_attributes(params[:setting]) flash[:success] = "Settings updated successfully." redirect_to(:action => :i...
Ruby
class IncidentsController < ApplicationController def index @lookup = session[:incident_lookup] || "" @incidents = Incident.for_index.by_id @incidents = @incidents.where(Incident.search_condition(@lookup)) unless @lookup.blank? @incidents = @incidents.paginate(:page => params[:page]) end d...
Ruby
# 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', ...
Ruby
# 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 probl...
Ruby
# 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 attac...
Ruby
# 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
Ruby
class Array # Matches elements of a to elements of b and passes each pair to a block. # If an element of a has no match in b or vice versa, nil is passed. # Assumes no duplicates in either array. def match(arr, &block) # create hashes from a and b ah = Hash[*self.collect{|x| [x,x]}.flatten] bh = Has...
Ruby
# Be sure to restart your server when you modify this file. Aggie::Application.config.session_store :cookie_store, :key => '_aggie_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 "rails ge...
Ruby
# uncomment these lines and set appropriately # path to rake #configatron.rake_path = "/usr/local/bin/rake" # # twitter oauth credentials (only necessary if you're using twitter) #configatron.twitter_consumer_key = 'xxx' #configatron.twitter_consumer_secret = 'xxx' #configatron.twitter_oauth_token = 'xxx' #configatron....
Ruby
class Time def basic_format self.strftime("%Y-%m-%d %T") end end
Ruby
CONF = configatron Setting.copy_to_config CONF.site_email = "Aggie <tomsmyth@gmail.com>" CONF.chunk_start_time = Time.zone.parse("2011-04-02 00:00:00") CONF.chunk_size = 5.minutes CONF.saved_search_chunks_per_page = 72 CONF.saved_search_htick_interval = 12 # unit is chunks; should divide per_page value evenly CONF.sav...
Ruby
Aggie::Application.routes.draw do resources(:settings) resources(:categories) resources(:users){collection {get 'welcome'; get 'logout'}} resources(:incidents){collection {get 'picker'; get 'lookup'}; member {get 'choose'; get 'delete'}} resource(:crawler){member {get 'log'}} resources(:rules){member {ge...
Ruby
require 'rubygems' # Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
Ruby
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 Aggie class Application < Rails::Application # S...
Ruby
# Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application Aggie::Application.initialize!
Ruby
Aggie::Application.configure do # Settings specified here will take precedence over those in config/application.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 ...
Ruby
Aggie::Application.configure do # Settings specified here will take precedence over those in config/application.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 webserv...
Ruby
Aggie::Application.configure do # Settings specified here will take precedence over those in config/application.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 su...
Ruby
# This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) run Aggie::Application
Ruby
# 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' Aggie::Application.load_tasks
Ruby
#!/usr/local/bin/ruby RAILS_ROOT = File.expand_path(File.dirname(__FILE__) + "/../..") # hack to get local config server_url = "" File.open("#{RAILS_ROOT}/config/initializers/conf-local.rb") do |f| f.read.match(/server_root_path = "(.+)"/) server_url = $1 end tempfile = "#{RAILS_ROOT}/tmp/emailtemp" # redirect s...
Ruby
STDOUT.sync = true # get rails root RAILS_ROOT = File.expand_path(File.dirname(__FILE__) + "/../..") LOCAL_CONF = File.read(File.join(RAILS_ROOT, "config/initializers/conf-local.rb")) # get rake path from local-config RAKE_PATH = LOCAL_CONF.match(/rake_path\s*=\s*"(.+)"/)[1] # get crawler PID file pid_file = File.j...
Ruby
namespace :db do desc "Seed the current environment's database." task :seed_it => :environment do ActiveRecord::Base.transaction do find_or_create(User, :username, :username => "root", :password => "freeNfair") end end end def find_or_create(klass, key_field, attribs) key_val = attribs[key_field...
Ruby