code
stringlengths
1
1.73M
language
stringclasses
1 value
require 'mission_based' require 'xml' class Response < ActiveRecord::Base include MissionBased belongs_to(:form, :inverse_of => :responses, :counter_cache => true) has_many(:answers, :include => :questioning, :order => "questionings.rank", :autosave => true, :validate => false, :dependent => :destroy, :inve...
Ruby
class BroadcastAddressing < ActiveRecord::Base belongs_to(:broadcast, :inverse_of => :broadcast_addressings) belongs_to(:user, :inverse_of => :broadcast_addressings) end
Ruby
require 'mission_based' require 'translatable' class Question < ActiveRecord::Base include MissionBased include Translatable belongs_to(:type, :class_name => "QuestionType", :foreign_key => :question_type_id, :inverse_of => :questions) belongs_to(:option_set, :include => :options, :inverse_of => :questions) ...
Ruby
# A calculation that just returns the referenced argument with no modification class Report::IdentityCalculation < Report::Calculation def name_expr arg1.name_expr(:tbl_pfx => table_prefix) end def value_expr arg1.value_expr(:tbl_pfx => table_prefix) end def sort_expr arg1.sort_expr(:tbl_pfx =...
Ruby
class Report::Formatter extend ActionView::Helpers::TextHelper def self.format(value, type, context) case type when "date" # cast mysql date to nice string value.to_s.gsub(" 00:00:00", "") when "decimal" "%.2f" % value when "long_text" context == :header ? truncate(value, :le...
Ruby
# models response attributes that are not answers to questions (user, date, etc.) class Report::AttribField < Report::Field attr_accessor :name, :name_expr_params, :value_expr_params, :data_type, :groupable # builds one of each type of AttribField def self.all @@ATTRIBS.values.collect{|a| new(a[:name])}...
Ruby
# models a row/column of headers class Report::Header attr_accessor :cells, :title def initialize(params) @cells = params[:cells].collect{|c| Report::HeaderCell.new(c)} @title = params[:title] end # looks for a header cell with a matching key and returns its index; returns nil if not found def f...
Ruby
require 'mission_based' class Report::Report < ActiveRecord::Base include MissionBased attr_accessible :type, :name, :option_set_id, :display_type, :bar_style, :unreviewed, :question_labels, :show_question_labels, :percent_type, :unique_rows, :calculations_attributes, :calculations, :option_set, :filte...
Ruby
# models the result rows returned by the db from the query class Report::DbResult attr_reader :rows def initialize(rows) @rows = rows # debug print rows #rows.each{|row| pp row.attributes} end def has_col?(col) return !@rows.empty? && @rows.first.attributes.keys.include?(col) end #...
Ruby
class Report::ListReport < Report::Report has_many(:calculations, :class_name => "Report::Calculation", :foreign_key => "report_report_id", :order => "rank", :dependent => :destroy, :autosave => true) accepts_nested_attributes_for(:calculations, :allow_destroy => true) def as_json(options = {}) h = supe...
Ruby
# models a single cell in a header class Report::HeaderCell attr_accessor :name, :sort_value, :key def initialize(params) @name = params[:name] @sort_value = params[:sort_value] || @name @key = params[:key] || @name end def as_json(options = {}) {:name => name, :sort_value => sort_value, :ke...
Ruby
module Report::Groupable module ClassMethods end def self.included(base) # ruby idiom to activate class methods base.extend(ClassMethods) # add scope base.class_eval do attr_accessible :calculations_attributes has_many(:calculations, :class_name => "Report::Calculation", :foreign...
Ruby
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
class Questioning < ActiveRecord::Base 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_one(:condition, :autosave => true, :dependent => :dest...
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 SmsResponsesController < ApplicationController def incoming # TOM space after #. please fix all of these, there are a lot of them. #set adapter according to provider param. @adapter = Sms::Adapters::Factory.new.create(params[:provider]) # return hash with phone number and message # may includ...
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 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
# 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 SmsCodesController < ApplicationController # TOM what is this? please don't leave commented code lying around like this # render :text => n, :status => 200 def show # this may be different that the language setting for the website I18n.locale = configatron.outgoing_sms_language # TOM be car...
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' # TOM pretty sure this is built into rails, no? gem 'i18n'
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 AddSmsQuestionNoColumnToQuestions < ActiveRecord::Migration def change # TOM shouldn't this be in questionings? doesn't it depend on the order of the question on the form? Questions are form independent. add_column :questions, :sms_question_no, :integer 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 CreateSmsCodes < ActiveRecord::Migration def change create_table :sms_codes do |t| t.string :code # TOM should have indices on these foreign keys. please read up on how to create indices in rails migrations. # ditto for your other migrations. t.integer :questioning_id t.intege...
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