code
stringlengths
1
1.73M
language
stringclasses
1 value
class Report::ReportError < StandardError end
Ruby
class Report::Calculation < ActiveRecord::Base attr_accessible :type, :report_report_id, :attrib1_name, :question1_id, :arg1, :attrib1, :question1, :rank attr_writer :table_prefix belongs_to :report, :class_name => "Report::Report", :foreign_key => "report_report_id" belongs_to :question1, :class_name => "Qu...
Ruby
# models the various joins in the Response/Answer db structure class Report::Join attr_reader :name, :sql, :dependencies def self.list_to_sql(list, prefix = "") expand(list).collect{|join| join.to_sql(prefix)} end def self.expand(list) expanded = [] list.each{|j| expanded += @@joins[j.to_sym]...
Ruby
class Report::Field end
Ruby
# contains methods common to all tally reports class Report::TallyReport < Report::Report protected # extracts the row header values from the db_result object def get_row_header get_header(:row) end # extracts the col header values from the db_result object def get_col_header get_he...
Ruby
class Report::GroupedTallyReport < Report::TallyReport include Report::Groupable protected def prep_relation(rel) joins = [] # add tally to select rel = rel.select("COUNT(responses.id) AS tally") # add filter rel = filter.apply(rel) unless filter.nil? ...
Ruby
# models the data table that results from the report class Report::Data attr_accessor :rows attr_reader :totals def initialize(rows) @rows = rows end def set_cell(row, col, value) @rows[row][col] = value unless row.nil? || col.nil? end def empty? @rows.empty? end def empty_r...
Ruby
# A calculation that returns 0 if the answer value is 0 and 1 otherwise class Report::ZeroNonzeroCalculation < Report::Calculation def name_expr @name_expr ||= Report::Expression.new(:sql_tplt => "IF(__TBL_PFX__answers.value > 0, 'One or More', 'Zero')", :name => "name", :clause => :select, :chunks => {:tb...
Ruby
class Report::OptionSetChoice < ActiveRecord::Base belongs_to(:option_set) belongs_to(:report_report) end
Ruby
class Report::QuestionAnswerTallyReport < Report::TallyReport has_many(:option_set_choices, :class_name => "Report::OptionSetChoice", :foreign_key => "report_report_id", :dependent => :destroy, :autosave => true) has_many(:option_sets, :through => :option_set_choices) has_many(:calculations, :class_name => "Repor...
Ruby
# models the two headers (row, col) for a given report class Report::HeaderSet attr_reader :headers # constructs a header_set object with the given row and col sources def initialize(headers) @headers = headers end # pass the [] operator on to the @headers array def [](which) @headers[which] ...
Ruby
class Report::Grouping def initialize(calculation, rank) @calculation = calculation @rank = rank end def apply(rel) prefix = @rank.to_s[0,3] # get fragments @calculation.table_prefix = prefix name_expr = @calculation.name_expr value_expr = @calculation.value_expr where_expr ...
Ruby
class Report::AnswerField < Report::Field attr_reader :question @@expression_params = [ {:sql_tplt => "__TBL_PFX__aotr.str", :name => "select_one_name", :clause => :select, :join => :options}, {:sql_tplt => "__TBL_PFX__cotr.str", :name => "select_multiple_name", :clause => :select, :join => :choices}, ...
Ruby
# models an sql expression to be used in an SQL clause # clause - the kind of clause that this expression is useful for # sql_tplt - template for the sql fragment # name - a name that can be used in an AS clause. should be unique per field type. # chunks - parameters to be subbed into the sql template class Report::Exp...
Ruby
require 'form_versionable' class Questioning < ActiveRecord::Base include FormVersionable belongs_to(:form, :inverse_of => :questionings, :counter_cache => true) belongs_to(:question, :autosave => true, :inverse_of => :questionings) has_many(:answers, :dependent => :destroy, :inverse_of => :questioning) has_...
Ruby
class UserBatch < ActiveRecord::Base attr_reader :created_users def create_users(mission) @created_users = [] transaction do users.each do |u| name, email, phone = u.split(/,|\t/).collect{|x| x.strip} user = User.new_with_login_and_password(:name => name, :email => email, :phone => ...
Ruby
class Condition < ActiveRecord::Base belongs_to(:questioning, :inverse_of => :condition) belongs_to(:ref_qing, :class_name => "Questioning", :foreign_key => "ref_qing_id", :inverse_of => :referring_conditions) belongs_to(:option) before_validation(:clear_blanks) before_validation(:clean_times) validate(:...
Ruby
class OptionSetsController < ApplicationController def index @sets = apply_filters(OptionSet).for_index end def new @set = OptionSet.for_mission(current_mission).new render_form end def edit @set = OptionSet.find(params[:id]) render_form end def show @set = OptionSet.find(pa...
Ruby
class SettingsController < ApplicationController def index # load setting for current mission (create with defaults if doesn't exist) @setting = Setting.find_or_create(current_mission) end def update begin (@setting = Setting.find(params[:id])).update_attributes!(params[:setting]) ...
Ruby
class MissionsController < ApplicationController def index @missions = Mission.all end def new @mission = Mission.new render(:form) end def edit @mission = Mission.find(params[:id]) render(:form) end def destroy begin (@mission = Mission.find(params[:id])).destroy ...
Ruby
class PasswordResetsController < ApplicationController before_filter(:load_user_using_perishable_token, :only => [:edit, :update]) def new @title = "Reset Password" end # when the user returns and enters their new password def edit @title = "Reset Password" end def create @user = Use...
Ruby
class UserSessionsController < ApplicationController def new @title = "Login" @user_session = UserSession.new end def create # reset the session for security purposes reset_session_preserving_return_to @user_session = UserSession.new(params[:user_session]) # if the save is ...
Ruby
class WelcomeController < ApplicationController def index # this page is not permission controlled since we don't want the "must login" error message to show up return redirect_to_login unless current_user @reports = Report::Report.for_mission(current_mission).by_popularity @pubd_forms = restrict(For...
Ruby
class UserBatchesController < ApplicationController def new @batch = UserBatch.new end def create @batch = UserBatch.new begin @batch.attributes = params[:user_batch] @batch.create_users(current_mission) flash[:success] = "Users created successfully." session[:new_user_batch...
Ruby
class ResponsesController < ApplicationController def create # if this is a submission from ODK collect if request.format == Mime::XML if %w(HEAD GET).include?(request.method) # just render the 'no content' status since that's what odk wants! render(:nothing => true, :status => 204) ...
Ruby
class SmsTestsController < ApplicationController def new @sms_test = Sms::Test.new end # handles a request for a test. this will be an AJAX call so we only return the message body def create # create an sms object sms = Sms::Message.new(:direction => :incoming, :from => params[:sms_test][:from], ...
Ruby
class ProxiesController < ApplicationController require 'open-uri' GEOCODER_URL = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false" def geocoder begin render(:json => open("#{GEOCODER_URL}&#{request.query_string}"){|f| f.read}) rescue SocketError render(:text => $!.to_s, :status ...
Ruby
class PermissionsController < ApplicationController def no end end
Ruby
class FormsController < ApplicationController # in the choose_questions action we have a question form so we need this include QuestionFormable def index respond_to do |format| # render normally if html format.html do @forms = apply_filters(Form).with_form_type.all render(:ind...
Ruby
# handles incoming sms messages from various providers class SmsController < ApplicationController # disable csrf protection for this stuff protect_from_forgery :except => :create # takes an incoming sms and returns an outgoing one # may return nil if no response is appropriate def self.handle_sms(sms)...
Ruby
# methods required to setup a question for use in the new question form module QuestionFormable extend ActiveSupport::Concern def init_qing(params) Questioning.new_with_question(current_mission, :form_id => params[:form_id]) end def setup_qing_form_support_objs @option_sets = restrict(OptionSet) ...
Ruby
class QuestioningsController < ApplicationController include QuestionFormable def new @qing = init_qing(:form_id => params[:form_id]) render_and_setup end def edit @qing = Questioning.find(params[:id]) render_and_setup end def show @qing = Questioning.find(params[:id]) rende...
Ruby
class BroadcastsController < ApplicationController def index @broadcasts = apply_filters(Broadcast) end def new flash[:success] = "To send a broadcast, first select the recipients below, and then click 'Send Broadcast'." redirect_to(users_path) end # Displays a new broadcast form with the...
Ruby
class ApplicationController < ActionController::Base require 'authlogic' include ActionView::Helpers::AssetTagHelper protect_from_forgery rescue_from(Exception, :with => :notify_error) before_filter(:set_default_title) before_filter(:mailer_set_url_options) # user/user_session stuff before_filter(:b...
Ruby
class FormTypesController < ApplicationController def index @form_types = apply_filters(FormType) end def new @form_type = FormType.new render(:form) end def edit @form_type = FormType.find(params[:id]) render(:form) end def show @form_type = FormType.find(params[:id]) r...
Ruby
class Report::ReportsController < ApplicationController def index @reports = apply_filters(Report::Report.by_popularity).all.collect{|r| r.becomes(Report::Report)} end def new @report = Report::Report.new_with_default_name(current_mission) render_show end def show @report = Report::Repor...
Ruby
class MarkersController < ApplicationController def show # generate (or locate in the cache) the image and get its path image_url = Marker.generate(params[:color]) # set content types for direct image download response.headers['Content-Type'] = 'image/png' response.headers['Content-Dispositi...
Ruby
class UsersController < ApplicationController def index @users = apply_filters(User.includes(:missions)) end def new @user = User.new render_form end def edit @user = User.find(params[:id]) @title = "Edit Profile" if @user == current_user render_form end def update @user = User...
Ruby
class OptionsController < ApplicationController def index @options = apply_filters(Option) end def new @option = Option.for_mission(current_mission).new render_form end def edit @option = Option.find(params[:id]) render_form end def show @option = Option.find(params[:id]) ...
Ruby
class AdminMailer < ActionMailer::Base default :from => configatron.site_email # mails an error report to the webmaster def error(exception, session = nil, params = nil, env = nil, user = nil) @exception = exception @session = session @params = params @env = env @user = user path = (env...
Ruby
class Notifier < ActionMailer::Base default(:from => configatron.site_email) def password_reset_instructions(user) @reset_url = edit_password_reset_url(user.perishable_token, :protocol => configatron.mailer_url_protocol) mail(:to => user.email, :subject => "Password Reset Instructions") end d...
Ruby
class BroadcastMailer < ActionMailer::Base default :from => configatron.site_email def broadcast(recips, subj, msg) s = configatron.broadcast_tag + " " + (subj || "") @msg = msg mail(:to => recips.collect{|r| r.email}.compact, :subject => s) end end
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' ELMO::Application.load_tasks
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
source 'http://rubygems.org' gem 'rails', '3.2.11' gem 'authlogic' gem 'rake' gem 'mysql2' gem 'will_paginate' gem 'configatron' gem 'libxml-ruby' gem 'rdiscount' gem 'jquery-rails' gem 'random_data' # building factories for testing -- stupid and offensive name but it's a good gem :( gem "factory_girl_rails", "~> 4.0...
Ruby
class DumpOldReports < ActiveRecord::Migration def up # ensure tmp directory dir = File.join(Rails.root, "tmp") Dir.mkdir(dir) unless File.exists?(dir) # output data File.open(File.join(dir, "old_reports.yml"), "w") do |f| %w(reports groupings aggregations fields response_attributes).ea...
Ruby
class AddLongNameToQuestionTypes < ActiveRecord::Migration def self.up add_column :question_types, :long_name, :string end def self.down remove_column :question_types, :long_name end end
Ruby
class CreateReportCalculations < ActiveRecord::Migration def self.up create_table :report_calculations do |t| t.string :name t.string :code t.string :constraints t.timestamps end end def self.down drop_table :report_calculations end end
Ruby
class AddDateTimeValuesToAnswers < ActiveRecord::Migration def change add_column :answers, :time_value, :time add_column :answers, :date_value, :date add_column :answers, :datetime_value, :datetime end end
Ruby
class RenameIsActiveToActiveForUser < ActiveRecord::Migration def self.up rename_column :users, :is_active, :active end def self.down end end
Ruby
class AddAlternatePhoneNumbers < ActiveRecord::Migration def up add_column :users, :phone2, :string end def down remove_column :users, :phone2 end end
Ruby
class CreatePlaceSuggs < ActiveRecord::Migration def self.up create_table :place_suggs do |t| t.integer :place_lookup_id t.integer :place_id t.integer :google_geolocation_id t.timestamps end end def self.down drop_table :place_suggs end end
Ruby
class CreateQuestions < ActiveRecord::Migration def self.up create_table :questions do |t| t.string :code t.string :name t.integer :question_type_id t.integer :option_set_id t.timestamps end end def self.down drop_table :questions end end
Ruby
class RenameReportGroupingAttributesToReportResponseAttributes < ActiveRecord::Migration def up rename_table :report_grouping_attributes, :report_response_attributes end def down rename_table :report_response_attributes, :report_grouping_attributes end end
Ruby
class RemoveTeamNumberFromUsers < ActiveRecord::Migration def self.up remove_column :users, :team_number end def self.down add_column :users, :team_number, :string end end
Ruby
class CreatePlaceCreators < ActiveRecord::Migration def self.up create_table :place_creators do |t| t.integer :place_id t.timestamps end end def self.down drop_table :place_creators end end
Ruby
class AddOutgoingSmsAdapterToSettings < ActiveRecord::Migration def up add_column :settings, :outgoing_sms_adapter, :string # default to intellisms Setting.update_all("outgoing_sms_adapter = 'IntelliSms'") end end
Ruby
class RenameNumericToInteger < ActiveRecord::Migration def self.up execute("update question_types set name = 'integer', long_name = 'Integer' where name = 'numeric'") QuestionType.create(:name => "decimal", :long_name => "Decimal", :odk_name => "decimal", :odk_tag => "input") end def self.down end end
Ruby
class AddForeignKeyIndicesToAssignments < ActiveRecord::Migration def change add_index :assignments, :mission_id add_index :assignments, :user_id end end
Ruby
class RemoveQuestionCodeSpaces < ActiveRecord::Migration def up Question.all.each{|q| q.code = q.code.gsub(" ", ""); q.save(:validate => false)} end def down end end
Ruby
class AddSourceToResponse < ActiveRecord::Migration def self.up add_column :responses, :source, :string execute("update responses set source='odk'") end def self.down remove_column :responses, :source end end
Ruby
class AddOdkNameToQuestionTypes < ActiveRecord::Migration def self.up add_column :question_types, :odk_name, :string end def self.down remove_column :question_types, :odk_name end end
Ruby
class AddLanguagesToSettings < ActiveRecord::Migration def up add_column :settings, :languages, :string # setup defaults execute("UPDATE settings s SET s.languages = (SELECT GROUP_CONCAT(l.code) FROM languages l WHERE s.mission_id = l.mission_id GROUP BY l.mission_id)") end def down remove...
Ruby
class ClearSessions < ActiveRecord::Migration def self.up execute("DELETE FROM sessions") end def self.down end end
Ruby
class AddOrderingToOptionSets < ActiveRecord::Migration def self.up add_column :option_sets, :ordering, :string end def self.down remove_column :option_sets, :ordering end end
Ruby
class CreatePlaceTypes < ActiveRecord::Migration def self.up create_table :place_types do |t| t.string :name t.integer :level t.timestamps end end def self.down drop_table :place_types end end
Ruby
class AddTeamNumberToUsers < ActiveRecord::Migration def self.up add_column :users, :team_number, :string end def self.down remove_column :users, :team_number end end
Ruby
class AddDisplayTypeToReportReport < ActiveRecord::Migration def change add_column :report_reports, :display_type, :string, :default => "Table" end end
Ruby
class CreateMainView < ActiveRecord::Migration def self.up execute("DROP VIEW IF EXISTS _answers") execute(" CREATE VIEW _answers AS select r.id AS response_id, r.observed_at AS observation_time, r.reviewed AS is_reviewed, f.name AS form_name, ft.name AS for...
Ruby
class AddForeignKeyIndices < ActiveRecord::Migration def change # if the indices already exist, that's ok add_index(:responses, :form_id) rescue nil add_index(:questionings, :form_id) rescue nil add_index(:questionings, :question_id) rescue nil end end
Ruby
class DropViews < ActiveRecord::Migration def up execute("DROP VIEW _answers") rescue nil end def down end end
Ruby
class AddCompactNameIndexToMissions < ActiveRecord::Migration def change add_index(:missions, [:compact_name]) end end
Ruby
class RemoveDeviceFromUsers < ActiveRecord::Migration def up remove_column :users, :device end def down add_column :users, :device, :string end end
Ruby
class CreateGoogleGeolocations < ActiveRecord::Migration def self.up create_table :google_geolocations do |t| t.string :full_name t.text :json t.integer :place_type_id t.decimal :latitude, :precision => 20, :scale => 15 t.decimal :longitude, :precision => 20, :scale => 15 t.str...
Ruby
class AddUnreviewedToReportReports < ActiveRecord::Migration def change add_column :report_reports, :unreviewed, :boolean, :default => false end end
Ruby
class UpdateGroupingToUseNewGroupingAttributeClass < ActiveRecord::Migration def up remove_column :report_groupings, :name remove_column :report_groupings, :code remove_column :report_groupings, :join_tables add_column :report_groupings, :attrib_id, :integer end def down end end
Ruby
class DropOldReportTables < ActiveRecord::Migration def up drop_table :report_aggregations drop_table :report_calculations drop_table :report_fields drop_table :report_groupings drop_table :report_reports drop_table :report_response_attributes end def down end end
Ruby
class AddUniqueRowsToReportReports < ActiveRecord::Migration def change add_column :report_reports, :unique_rows, :boolean end end
Ruby
class CreateLanguages < ActiveRecord::Migration def self.up create_table :languages do |t| t.string :name t.boolean :is_active t.timestamps end end def self.down drop_table :languages end end
Ruby
class QuestionShouldBeQuestioningForAnswer < ActiveRecord::Migration def self.up add_column(:answers, :questioning_id, :integer) connection.execute("update answers a, responses r, questionings qing set a.questioning_id=qing.id where a.response_id=r.id and qing.form_id=r.form_id and qing.question_id=a.questio...
Ruby
class RemoveOmnibusCalculationFromReportReports < ActiveRecord::Migration def change remove_column :report_reports, :omnibus_calculation end end
Ruby
class CreateBroadcasts < ActiveRecord::Migration def self.up create_table :broadcasts do |t| t.string :subject t.text :body t.string :medium t.text :send_errors t.timestamps end end def self.down drop_table :broadcasts end end
Ruby
class RemoveOldUserFields < ActiveRecord::Migration def up remove_column(:users, :role_id) remove_column(:users, :active) remove_column(:users, :location_id) end def down end end
Ruby
class RemoveSecondCalculationFields < ActiveRecord::Migration def change remove_column :report_calculations, :attrib2_name remove_column :report_calculations, :question2_id end end
Ruby
class CreateBroadcastAddressings < ActiveRecord::Migration def self.up create_table :broadcast_addressings do |t| t.integer :broadcast_id t.integer :user_id t.timestamps end end def self.down drop_table :broadcast_addressings end end
Ruby
class ChangeReportTypeToKind < ActiveRecord::Migration def up rename_column(:report_reports, :type, :kind) end def down end end
Ruby
class AddLoginCountToUsers < ActiveRecord::Migration def self.up add_column :users, :login_count, :integer, :default => 0 end def self.down remove_column :users, :login_count end end
Ruby
require 'digest/sha2' class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :login t.string :first_name t.string :last_name t.string :email t.integer :language_id t.integer :role_id t.integer :location_id t.string :phone ...
Ruby
class RemoveObservedAtFromResponses < ActiveRecord::Migration def up # wrap this part in a transaction in case it fails for some reason transaction do # if there are any existing forms if Form.count > 0 # add a new question called Form Start Time puts "Creating new FormStartTime q...
Ruby
class ChangeTranslationsToPolymorphic < ActiveRecord::Migration def self.up add_column(:translations, :class_name, :string) add_column(:translations, :object_id, :integer) add_column(:translations, :fld, :string) remove_column(:translations, :question_id) remove_column(:translations, :option_id) ...
Ruby
class CreateResponses < ActiveRecord::Migration def self.up create_table :responses do |t| t.integer :form_id t.integer :user_id t.integer :location_id t.datetime :observed_at t.timestamps end end def self.down drop_table :responses end end
Ruby
class RemoveKindFromReportReports < ActiveRecord::Migration def up remove_column :report_reports, :kind Report::Report.all.each{|r| r.aggregation = Report::Aggregation.find_by_name("Tally"); r.save(:validate => false)} end def down add_column :report_reports, :kind, :string end end
Ruby
class AddGroupableToReportResponseAttributes < ActiveRecord::Migration def change add_column :report_response_attributes, :groupable, :boolean, :default => false end end
Ruby
class CreateOptionSets < ActiveRecord::Migration def self.up create_table :option_sets do |t| t.string :name t.timestamps end end def self.down drop_table :option_sets end end
Ruby
class DropUnneededPlaceTables < ActiveRecord::Migration def self.up drop_table :place_lookups drop_table :place_suggs drop_table :place_sugg_sets end def self.down end end
Ruby
class AddStackedBarsToReportReport < ActiveRecord::Migration def change add_column :report_reports, :bar_style, :string, :default => "Side By Side" end end
Ruby
class CreatePlaces < ActiveRecord::Migration def self.up create_table :places do |t| t.string :long_name t.string :short_name t.string :full_name t.integer :place_type_id t.integer :container_id t.decimal :latitude, :precision => 20, :scale => 15 t.decimal :longitude, :pr...
Ruby
class RemoveSettables < ActiveRecord::Migration def up # add 'key' column to settings add_column(:settings, :key, :string) # copy settable keys to settings execute("UPDATE settings s, settables sb SET s.key = sb.key WHERE s.settable_id = sb.id") # remove settables table and settable_id c...
Ruby
class AddDataTypeToReportResponseAttribute < ActiveRecord::Migration def change add_column :report_response_attributes, :data_type, :string end end
Ruby
class CreateQuestionTypes < ActiveRecord::Migration def self.up create_table :question_types do |t| t.string :name t.timestamps end end def self.down drop_table :question_types end end
Ruby