code
stringlengths
1
1.73M
language
stringclasses
1 value
class UpdateAccountRoles < ActiveRecord::Migration def up Account.where(:role => 'superuser').each do |account| account.role = 'admin' account.save end end def down end end
Ruby
class MoveProgramHelps < ActiveRecord::Migration HELP_SLUG_CHANGES = { :program_cycles => :directive_cycles, :program_info => :directive_info, :programs_list => :directives_list, :program_controls => :directive_controls, :program_more_info => :directive_more_info, :program => :directive } ...
Ruby
class RegulationToProgram < ActiveRecord::Migration def up rename_table :regulations, :programs rename_table :control_objectives, :sections change_table :sections do |t| t.integer :parent_id t.index :parent_id end end end
Ruby
class ChangePolymorphicTypesFromLocationToFacility < ActiveRecord::Migration def up ObjectPerson.where(:personable_type => 'Location').all.each do |o| o.update_attribute(:personable_type, 'Facility') end ObjectDocument.where(:documentable_type => 'Location').all.each do |o| o.update_attribute(...
Ruby
class CreateSystemSystems < ActiveRecord::Migration def change create_table :system_systems do |t| t.references :parent, :null => false t.references :child, :null => false t.string :type t.integer :order t.references :modified_by t.timestamps end end end
Ruby
class CreatePrograms < ActiveRecord::Migration def change create_table :programs do |t| t.string :slug t.string :title t.text :description t.string :url t.references :modified_by t.datetime :start_date t.datetime :stop_date t.timestamps end end end
Ruby
class RemoveRiskFields < ActiveRecord::Migration def up remove_column :risks, :financial_impact remove_column :risks, :reputational_impact remove_column :risks, :operational_impact end def down end end
Ruby
class AddDocumentOptionColumns < ActiveRecord::Migration def up change_table :documents do |t| t.text :description t.references :type t.references :kind t.references :year t.references :language end end def down change_table :documents do |t| t.remove :description ...
Ruby
class AddRelationshipTypeSymmetric < ActiveRecord::Migration def change add_column :relationship_types, :symmetric, :boolean, :default => false end end
Ruby
class EnsureRequestTypeIdIsNotNil < ActiveRecord::Migration def up Request.all.reject(&:type_name).each{ |r| r.update_attribute(:type_id, 1) } end def down end end
Ruby
class CreateControlRisks < ActiveRecord::Migration def change create_table :control_risks do |t| t.references :control, :null => false t.references :risk, :null => false t.references :modified_by t.timestamps end end end
Ruby
class CreateRelationshipTypes < ActiveRecord::Migration def change create_table :relationship_types, :id => false do |t| t.string :relationship_type t.string :description t.string :forward_short_description t.string :backward_short_description t.timestamps end add_index...
Ruby
class CreateRiskRiskyAttributes < ActiveRecord::Migration def change create_table :risk_risky_attributes do |t| t.references :risk, :null => false t.references :risky_attribute, :null => false t.references :modified_by t.timestamps end end end
Ruby
class CreateRiskyAttributes < ActiveRecord::Migration def change create_table :risky_attributes do |t| t.string :slug t.string :title t.text :description t.string :url t.references :modified_by t.datetime :start_date t.datetime :stop_date t.timestamps end ...
Ruby
class DeleteReferencesWithoutUrLs < ActiveRecord::Migration def up Document.where(:link => nil).concat(Document.where(:link => "")).each {|x| x.destroy} end def down end end
Ruby
class ChangePolymorphicTypesFromProgramToDirective < ActiveRecord::Migration RELATIONSHIP_TYPE_NAME_CHANGES = [ [:program_applies_to_data_asset, :directive_applies_to_data_asset], [:program_applies_to_facility, :directive_applies_to_facility], [:program_applies_to_market, :directive_applies_to_marke...
Ruby
class CreateProducts < ActiveRecord::Migration def up create_table :products do |t| t.string :slug t.string :title t.text :description t.string :url t.string :version t.references :type t.references :modified_by t.timestamps end end def down end end
Ruby
class CreatePopulationSamples < ActiveRecord::Migration def change create_table :population_samples do |t| t.references :response t.references :population_document t.integer :population t.references :sample_worksheet_document t.integer :samples t.references :sample_evidence_doc...
Ruby
class AddNetworkZoneIdToSystems < ActiveRecord::Migration def change add_column :systems, :network_zone_id, :integer end end
Ruby
class CreateRelationships < ActiveRecord::Migration def change create_table :relationships do |t| t.references :source, :polymorphic => true, :null => false t.references :destination, :polymorphic => true, :null => false t.references :modified_by t.string :relationship_type_id t.time...
Ruby
class FixRiskyAttributeSlugs < ActiveRecord::Migration def up RiskyAttribute.all.each do |ra| if ra.slug.match(/^RISKYATTRIBUTE/) ra.slug = ra.slug.sub(/^RISKYATTRIBUTE/, 'RA') ra.save! end end end def down end end
Ruby
class AddResponseDueAtToRequest < ActiveRecord::Migration def change add_column :requests, :response_due_at, :date end end
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 StateModel def state index = read_attribute(:state) || self.class.columns_hash['state'].default ControlState::VALUES[index] end def state=(value) write_attribute(:state, ControlState::VALUES.index(value)) end def good_state? ControlState::STATE_IS_GOOD[state] end def self.include...
Ruby
# Provides utility functions for doing authorization on CRUD and other operations # to the model, given a standard way of getting the current user and # a list of users and roles for an object. # Note: requires the model to implement the authorizing_objects method # FIXME: Properly deal with anonymous users - or are w...
Ruby
module BusinessObjectModel @business_object_models = nil def self.included(model) model.class_eval do end model.extend(ClassMethods) if model.ancestors.include?(ActiveRecord::Base) @business_object_models = [] if @business_object_models.nil? @business_object_models.push(model) end ...
Ruby
module CommonModel def self.included(model) model.send(:include, AuthoredModel) model.has_many :object_people, :as => :personable, :dependent => :destroy model.has_many :people, :through => :object_people model.has_many :object_documents, :as => :documentable, :dependent => :destroy model.has_many...
Ruby
module AuthoredModel # Typecast form parameters into the right primitive to work around a DataMapper dirty-detection bug. # # If we don't do this, the persistence layer thinks all non-strings params are modifications # where in fact we might just have changed false => 0, which is a no-op. This is important #...
Ruby
# A lot of this is cribbed from how declarative_authorization handles # model-based authorization. module Authorization # Controller-independent method for retrieving the current user. # Needed for model security where the current controller is not available. # Primarily for use by the console and tests, where w...
Ruby
module RoleModel ROLES = [:tech, :business] def role index = read_attribute(:role) || self.class.columns_hash['role'].default ROLES[index] end def role=(value) write_attribute(:role, ROLES.index(value)) end def self.included(model) model.validates :role, :presence => true end end
Ruby
module SearchableModel def self.included(model) model.extend(ClassMethods) end def self.sphinx_servers @@sphinx_servers ||= begin servers = CMS_CONFIG['FULLTEXT'] (servers or '').split(',').map do |host_port| { :host => host_port.split(':')[0], :port => host_port.split(':')[...
Ruby
module DefaultRelationshipTypes RELATIONSHIP_TYPES = { :data_asset_has_process => { :source_type => "DataAsset", :target_type => "Process", :forward_phrase => "has", :reverse_phrase => "is a process for", :forward_description => "This data asset relies upon the following processes."...
Ruby
module ControlState VALUES = [ :green, :yellow, :red, :unknown ] STATE_WEIGHT = { :green => 10, :unknown => 15, :yellow => 20, :red => 30 } STATE_IS_GOOD = { :green => true, :unknown => true } end
Ruby
module SluggedModel def compact_slug return slug unless parent cslug = slug cslug[parent.slug] = '' if cslug[parent.slug] # Substring replacement of parent.slug with '' return cslug end def self.included(model) model.extend(ClassMethods) model.class_eval do validates :slug, :presen...
Ruby
# RelatedModel mixin # # Many mixins that exist for managing relationships, and especially the relationship # traversal functions that are used in the context of authorization. # # Also creates some useful scoping functions that allow you to # create scopes for relationships with very little code. Example usage: # # In...
Ruby
module DatedModel include ActiveSupport::Concern def self.included(model) model.validate :stop_date_later_than_start_date end def stop_date_later_than_start_date if self.has_attribute? :stop_date if self.start_date.present? && self.stop_date.present? errors.add(:stop_date, 'Must be l...
Ruby
# Sanitize attributes before validation. # # Usage in model: # # sanitize_attributes :description, :documentation_description # module SanitizableAttributes # based on defaults from ActionView::Base.sanitized_allowed_tags with table tags added SANITIZED_ALLOWED_TAGS = %w(strong em b i p code pre tt samp kbd var s...
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' CmsRails::Application.load_tasks if Rails.env.development? || Rails.env.test? requ...
Ruby
# This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) run CmsRails::Application
Ruby
CmsRails::Application.routes.draw do resources :programs, :as => 'flow_programs', :only => [:index, :show, :new, :edit, :create, :update, :destroy] do member do get 'tooltip' get 'delete' get 'sections' get 'controls' end end resources :directives, :as => 'flow_directives', :only...
Ruby
require File.expand_path('../boot', __FILE__) require 'yaml' CMS_CONFIG = { "SECRET_TOKEN" => "0123456789abcdefChangethistosomethingsecret", "COMPANY" => "Company, Inc.", "COMPANY_LOGO" => nil, "COMPANY_LOGO_TEXT" => nil, "ABOUT_LINK" => "https://code.google.com/p/compliance-management/", "SECTION_IMPORT_...
Ruby
CmsRails::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 web ...
Ruby
CmsRails::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...
Ruby
CmsRails::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 o...
Ruby
CmsRails::Application.configure do # Settings specified here will take precedence over those in config/application.rb config.cache_classes = true config.action_controller.perform_caching = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error rep...
Ruby
# Disable Rake-environment-task framework detection by uncommenting/setting to false # Warbler.framework_detection = false # Warbler web application assembly configuration file Warbler::Config.new do |config| # Features: additional options controlling how the jar is built. # Currently the following features are su...
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
Rails.backtrace_cleaner.remove_silencers!
Ruby
# Be sure to restart your server when you modify this file. CmsRails::Application.config.session_store :encrypted_cookie_store, :key => '_cms_session_id' # 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 ...
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
require 'gdoc' require 'gdoc/document'
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
module CmsRails class Application < Rails::Application def self.sso_callback_url @@sso_callback rescue nil end def self.sso_callback_url=(url) @@sso_callback = url end end end
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
# Monkey patch to avoid riddle trying to exec stuff ENV['SPHINX_VERSION'] = '2.0.4' require 'riddle' module Riddle class Controller def sphinx_version ENV['SPHINX_VERSION'] end end end # Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails applicatio...
Ruby
# Monkey patch Prawn to fix 'incompatible character encodings' error in JRuby: # https://github.com/prawnpdf/prawn/issues/283 require 'prawn' module Prawn module Core def self.utf8_to_utf16(str) str end end end
Ruby
namespace :import do desc "Import various documents into CMS" task :consolidated, [:filename] => [:environment] do |t, args| puts "Import consolidated format from #{args[:filename]}" require 'importer/consolidated' ActiveRecord::Base.transaction do importer = Importer::Consolidated.new imp...
Ruby
namespace :demo do desc "Load demo seed data" task :seed => :environment do |t, args| demo_seed_file = File.join(Rails.root, 'db', 'demo_seeds', 'demo_seeds.rb') load(demo_seed_file) end task :setup => [:environment, :"db:seed", :"demo:seed"] task :reset, [ :subdir ] => [:environment, :"db:reset", :s...
Ruby
namespace :export do desc "Export help data to YAML file" task :help, [:filename] => [:environment] do |t, args| puts "Exporting help data to #{args[:filename]}" File.open(args[:filename], 'w') do |file| YAML::dump(Help.all, file) end end end
Ruby
require 'open-uri' require 'csv' module Importer # Importer for specialized CSV document format # # Expected columns are: # 0-4: Company control index, unused, title, description-part-1, description-part-2 # 5-6: Directive 1: description, slug(s) # 7-8: Directive 2: description, slug(s) # 9-10...
Ruby
require 'open-uri' require 'csv' module Importer class Regulation def initialize end def run_file(filename) open(filename, 'r:utf-8') do |file| run_csv(file.read) end end def run_csv(csv_string) directive = nil headers_seen = false CSV.parse(csv_string) ...
Ruby
require 'gdata' module Gdoc DOCLIST_SCOPE = 'https://docs.google.com/feeds/' DOCLIST_DOWNLOD_SCOPE = 'https://docs.googleusercontent.com/' CONTACTS_SCOPE = 'https://www.google.com/m8/feeds/' SPREADSHEETS_SCOPE = 'https://spreadsheets.google.com/feeds/' DEFAULT_FEED = DOCLIST_SCOPE + 'default/private/full' ...
Ruby
# Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
Ruby
# Importer contains classes and methods to import data from various formats # into the system. module Importer class ImportError < StandardError end end
Ruby
# encoding: utf-8 # 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.irregul...
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
# 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. # # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters ...
Ruby
# Be sure to restart your server when you modify this file. Comptec::Application.config.session_store :cookie_store, key: '_comptec_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 g...
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
Comptec::Application.configure do # Settings specified here will take precedence over those in config/application.rb # 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...
Ruby
Comptec::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 web se...
Ruby
Comptec::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
# Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application Comptec::Application.initialize!
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 defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*Rails.groups(:assets => %w(development test))) # If you want your assets lazily compiled in production, use this line # Bundler.requi...
Ruby
Comptec::Application.routes.draw do resources :imagens resources :usuarios resources :clientes resources :paginas resources :item_menus resources :menus resources :produtos resources :categorias resources :homes resources :categories # The priority is based upon order of creat...
Ruby
module ApplicationHelper def nova_imagem(owner) render partial: "imagens/nova_imagem", locals: { owner: owner } end def imagens(owner) render partial: "imagens/imagens", locals: {imagens: owner.imagens} end def get_menu_topo m = Menu.find_by_nome :Superior itens = m.itemMenus me...
Ruby
module UsuariosHelper end
Ruby
module ImagensHelper end
Ruby
module ProdutosHelper end
Ruby
#encoding: utf-8 module ItemMenusHelper end
Ruby
module CategoriesHelper end
Ruby
module HomesHelper end
Ruby
module PaginasHelper end
Ruby
module MenusHelper end
Ruby
module ClientesHelper end
Ruby
module CategoriasHelper end
Ruby
class Home < ActiveRecord::Base end
Ruby
class Produto < ActiveRecord::Base attr_accessible :ativo, :banner, :categoria_id, :destaque, :detalhe, :nome, :sugestao belongs_to :categoria has_many :imagens, as: :owner, :dependent => :destroy accepts_nested_attributes_for :imagens, :allow_destroy => true end #TODO Obrigado a preencher categoria. #TO...
Ruby
class Menu < ActiveRecord::Base has_many :children, class_name: "Menu", foreign_key: "father_id" belongs_to :father, class_name: "Menu" attr_accessible :action_id, :action_type, :father_id, :name end
Ruby
class Usuario < ActiveRecord::Base attr_accessible :ativo, :email, :login, :senha end
Ruby
class Pagina < ActiveRecord::Base attr_accessible :detalhes, :titulo end #TODO Adicionar ativo em pagina... #TODO Detalhes em rich text / textarea
Ruby
class ItemMenu < ActiveRecord::Base attr_accessible :ativo, :acao_id, :acao_item_id, :menu_id, :nome, :pai has_many :children, class_name: "ItemMenu", foreign_key: "pai" belongs_to :father, class_name: "ItemMenu", foreign_key: "pai" belongs_to :menu belongs_to :acao, class_name: "AcaoItemMenu", foreign_key...
Ruby
class Imagem < ActiveRecord::Base attr_accessible :owner_id, :owner_type, :titulo, :foto belongs_to :owner, polymorphic: true has_attached_file :foto, styles: { mini: "200x200", medium: "300x300>", thumb: "100x100>", original: "600x600>" } end
Ruby
class Categoria < ActiveRecord::Base attr_accessible :ativo, :nome, :father_id, :permitirProdutos has_many :children, :class_name => "Categoria", :foreign_key => "father_id" belongs_to :father, :class_name => "Categoria" has_many :produtos end
Ruby
class Cliente < ActiveRecord::Base attr_accessible :cidade, :contato, :email, :empresa, :endereco, :estado, :telefone end #TODO Criar tabela de cidade e estado (ibge)
Ruby
class Menu < ActiveRecord::Base attr_accessible :ativo, :nome has_many :itemMenus end
Ruby
class AcaoItemMenu < ActiveRecord::Base attr_accessible :nome end
Ruby
class ProdutosController < ApplicationController # GET /produtos # GET /produtos.json def index @produtos = Produto.all :include => :categoria respond_to do |format| format.html # index.html.erb format.json { render json: @produtos } end end # GET /produtos/1 # GET /produtos/1.json...
Ruby