repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
tmyracle/mandrill-stats
mandrill_stats.rb
require 'mandrill' API_KEY = 'ADD API KEY HERE' mandrill = Mandrill::API.new API_KEY # Add the template names you want stats on to this array templates_to_query = [ 'template-name', ] templates_to_query.each do |template| begin total_sent = 0 total_unique_open = 0 total_unique_clicks = 0 results = mandrill.templates.time_series template results.each do |data| total_sent += data["sent"] total_unique_open += data["unique_opens"] total_unique_clicks += data["unique_clicks"] end open_rate = (total_unique_open.to_f / total_sent * 100).round(2) click_rate = (total_unique_clicks.to_f / total_sent * 100).round(2) puts "For the template #{template}: The total sent is #{total_sent}, the open rate is #{open_rate}%, and click through rate is #{click_rate}%." rescue Mandrill::Error => e puts "A mandrill error occured: #{e.class} - #{e.message}" raise end end
ecbypi/capistrano-env
lib/capistrano/env.rb
require 'capistrano' require "capistrano/env/version" if Capistrano::Configuration.instance Capistrano::Configuration.instance.load do require 'aws' _cset :aws_credentials, {} _cset(:s3) { AWS::S3.new(aws_credentials) } _cset :env_bucket_name do name = ENV['AWS_BUCKET_NAME'] || ENV['BUCKET_NAME'] || ENV['FOG_DIRECTORY'] if name.nil? $stdout.puts <<-MESSAGE :env_bucket_name must be specified explicitly if not in any of the ENV variables: * AWS_BUCKET_NAME * BUCKET_NAME * FOG_DIRECTORY MESSAGE exit 1 end name end _cset :env_bucket do bucket_name = fetch(:env_bucket_name) bucket = s3.buckets[bucket_name] bucket = s3.buckets.create(bucket_name) unless bucket.exists? bucket end _cset :env_object_key do stage_name = fetch(:stage, nil) app_name = fetch(:application) stage_name ? "#{app_name}-#{stage_name}" : app_name end _cset :env_object do fetch(:env_bucket).objects[fetch(:env_object_key)] end _cset :env_hash do content = fetch(:env_object).read rescue "" Hash[content.split(/\n/).map { |line| line.split('=', 2) }] end namespace :env do def env_variables index = 1 stage_name = fetch(:stage, nil) default_stage_name = fetch(:default_stage, nil) if stage_name && default_stage_name && stage_name.to_s != default_stage_name.to_s index = 2 end ARGV[index..-1] end desc <<-DOC Reads the .env file from S3. DOC task :read do begin $stdout.puts fetch(:env_object).read rescue $stdout.puts "the object #{fetch(:env_object_key)} in bucket #{fetch(:env_bucket_name)} does not exist, set some values first" end end desc "Set a value" task :set do pairs = fetch(:env_hash) env_variables.map do |pair| key, value = pair.split('=', 2) pairs[key] = value end end desc <<-DOC Persists any changes made to the .env file and uploads it to the instances via scp. DOC task :export do pairs = fetch(:env_hash).sort object = fetch(:env_object) content = pairs.map { |key, value| "#{key}=#{value}" }.join("\n") << "\n" object.write content put content, "#{latest_release}/.env", :via => :scp end desc <<-DOC Unset values from the .env file. Has the slight drawback that the recommended usage causes capistrano to print an error about being unable to find tasks with the name of the environment variable(s) being unset. DOC task :unset do pairs = fetch(:env_hash) env_variables.each { |key| pairs.delete(key) } end end after 'env:set', 'env:export' after 'env:unset', 'env:export' after 'deploy:finalize_update', 'env:export' end end
ecbypi/capistrano-env
capistrano-env.gemspec
<reponame>ecbypi/capistrano-env # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'capistrano/env/version' Gem::Specification.new do |spec| spec.name = "capistrano-env" spec.version = Capistrano::Env::VERSION spec.authors = ["<NAME>"] spec.email = ["<EMAIL>"] spec.description = %q{ Set and unset ENV variables in your .env file using S3 as a storage backend. } spec.summary = %q{ Capistrano tasks to manage and deploy .env files stored on S3. } spec.homepage = "https://github.com/ecbypi/capistrano-env" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency 'aws-sdk', '~> 1.15' spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" end
rewindio/dagwood
lib/dagwood/dependency_graph.rb
# frozen_string_literal: true require 'tsort' module Dagwood class DependencyGraph include TSort attr_reader :dependencies # @param dependencies [Hash] # A hash of the form { item1: ['item2', 'item3'], item2: ['item3'], item3: []} # would mean that "item1" depends on item2 and item3, item2 depends on item3 # and item3 has no dependencies. Nil and missing values will be converted to []. def initialize(dependencies) @dependencies = Hash.new([]).merge(dependencies.transform_values { |v| v.nil? ? [] : v.sort }) end def order @order ||= tsort end def reverse_order @reverse_order ||= order.reverse end # Similar to #order, except this will group items that # have the same "priority", thus indicating they can be done # in parallel. # # Same priority means: # 1) They have the same exact same sub-dependencies OR # 2) B comes after A and all of B's dependencies have been resolved before A def parallel_order groups = [] ungrouped_dependencies = order.dup until ungrouped_dependencies.empty? # Start this group with the first dependency we haven't grouped yet group_starter = ungrouped_dependencies.delete_at(0) group = [group_starter] ungrouped_dependencies.each do |ungrouped_dependency| same_priority = @dependencies[ungrouped_dependency].all? do |sub_dependency| groups.reduce(false) { |found, g| found || g.include?(sub_dependency) } end group << ungrouped_dependency if same_priority end # Remove depedencies we managed to group ungrouped_dependencies -= group groups << group.sort end groups end # Generate a subgraph starting at the given node def subgraph(node) return self.class.new({}) unless @dependencies.key? node # Add the given node and its dependencies to our hash hash = {} hash[node] = @dependencies[node] # For every dependency of the given node, recursively create a subgraph and merge it into our result @dependencies[node].each { |dep| hash.merge! subgraph(dep).dependencies } self.class.new hash end # Returns a new graph containing all dependencies from this graph and the given graph. # If both graphs depend on the same item, but that item's sub-dependencies differ, the # resulting graph will depend on the union of both. def merge(other) all_dependencies = {} (dependencies.keys | other.dependencies.keys).each do |key| all_dependencies[key] = dependencies[key] | other.dependencies[key] end self.class.new all_dependencies end private def tsort_each_child(node, &block) @dependencies.fetch(node, []).each(&block) end def tsort_each_node(&block) @dependencies.each_key(&block) end end end
rewindio/dagwood
spec/dagwood_spec.rb
<gh_stars>10-100 # frozen_string_literal: true describe Dagwood do it 'should have a version number' do expect(Dagwood::VERSION).not_to be_nil end end
rewindio/dagwood
dagwood.gemspec
<reponame>rewindio/dagwood<filename>dagwood.gemspec # frozen_string_literal: true lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'dagwood/version' Gem::Specification.new do |spec| spec.name = 'dagwood' spec.version = Dagwood::VERSION spec.authors = ['<EMAIL>'] spec.email = ['<EMAIL>'] spec.summary = 'For all your dependency graph needs' spec.description = 'Dagwood allows you to create dependency graphs for doing work in series or in parallel, always in the right order.' spec.homepage = 'https://github.com/rewindio/dagwood' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(spec|.github|examples)/}) } spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '2.0.1' spec.add_development_dependency 'rake', '~> 13.0' spec.add_development_dependency 'rewind-ruby-style' spec.add_development_dependency 'rspec', '~> 3.9.0' spec.add_development_dependency 'rubocop', '~> 0.87.0' spec.add_development_dependency 'simplecov', '~> 0.19' spec.add_development_dependency 'simplecov-console', '~> 0.4' end
rewindio/dagwood
lib/dagwood.rb
<filename>lib/dagwood.rb # frozen_string_literal: true require 'dagwood/version' require 'dagwood/dependency_graph' module Dagwood class Error < StandardError; end end
rewindio/dagwood
spec/dependency_graph_spec.rb
# frozen_string_literal: true require 'spec_helper' describe Dagwood::DependencyGraph do describe '#initialize' do it 'converts nil values to []' do graph = Dagwood::DependencyGraph.new(item1: nil, item2: [], item3: [:item1]) expect(graph.dependencies).to eql item1: [], item2: [], item3: [:item1] end it 'converts missing values to []' do graph = Dagwood::DependencyGraph.new(item1: nil) expect(graph.dependencies[:item4]).to eql [] end it 'sorts all sub-dependency lists' do graph = Dagwood::DependencyGraph.new(item1: %i[item2 item1], item2: %i[item3 item2 item4]) expect(graph.dependencies).to eql item1: %i[item1 item2], item2: %i[item2 item3 item4] end it 'works on frozen hashes' do graph = Dagwood::DependencyGraph.new({ item1: nil, item2: %i[item3 item2 item4] }.freeze) expect(graph.dependencies[:item4]).to eql [] end end describe '#order' do it 'returns the dependencies in order of least dependent to most dependent' do graph = Dagwood::DependencyGraph.new(item1: %i[item2 item3], item2: %i[item3], item3: []) expect(graph.order).to eql %i[item3 item2 item1] end it 'survives missing dependencies' do graph = Dagwood::DependencyGraph.new(item1: %i[item2 item3], item2: %i[item3]) expect(graph.order).to eql %i[item3 item2 item1] graph = Dagwood::DependencyGraph.new(item1: %i[item2 item3], item2: %i[item3], item3: nil) expect(graph.order).to eql %i[item3 item2 item1] end end describe '#reverse_order' do it 'returns the dependencies in order of most dependent to least dependent' do graph = Dagwood::DependencyGraph.new(item1: %i[item2 item3], item2: %i[item3], item3: []) expect(graph.reverse_order).to eql %i[item1 item2 item3] end end describe '#parallel_order' do it 'groups items with no dependencies' do graph = Dagwood::DependencyGraph.new(item1: %i[], item2: %i[], item3: %i[]) expect(graph.parallel_order).to eql [%i[item1 item2 item3]] end it 'groups items with the exact same dependencies' do # Relatively well ordered dependency graph graph = Dagwood::DependencyGraph.new(item1: %i[item3], item2: %i[item3], item3: %i[item4 item5], item4: %i[item5], item5: %i[]) expect(graph.parallel_order).to eql [%i[item5], %i[item4], %i[item3], %i[item1 item2]] # Disordered dependency graph graph = Dagwood::DependencyGraph.new(item1: %i[], item2: %i[item1], item3: %i[], item4: %i[item3 item5], item5: %i[item3 item6], item6: %i[item1]) expect(graph.parallel_order).to eql [%i[item1 item3], %i[item2 item6], %i[item5], %i[item4]] end it 'groups items with the exact same dependencies even if in a different order' do graph = Dagwood::DependencyGraph.new(item1: %i[item3 item4], item2: %i[item4 item3]) expect(graph.parallel_order).to eql [%i[item3 item4], %i[item1 item2]] end it 'groups items A and B if all of B\'s dependencies have been resolved already' do # We know that we can get away with grouping [item1, item2] # because item2's dependencies were resolved earlier in the order. graph = Dagwood::DependencyGraph.new(item1: %i[item3], item2: %i[item3 item4], item3: %i[item4], item4: %i[]) expect(graph.parallel_order).to eql [%i[item4], %i[item3], %i[item1 item2]] end end describe '#subgraph' do it 'includes only given node if it has no dependencies' do graph = Dagwood::DependencyGraph.new(item1: %i[]) expect(graph.subgraph(:item1).dependencies).to eql item1: %i[] end it 'returns an empty graph if given node does not exist' do graph = Dagwood::DependencyGraph.new(item1: %i[]) expect(graph.subgraph(:item2).dependencies).to be_empty end it 'includes all dependencies of the given node as well as their dependencies' do graph = Dagwood::DependencyGraph.new(item1: %i[item3], item2: %i[item3 item4], item3: %i[item4], item4: %i[]) expect(graph.subgraph(:item2).dependencies).to eql item2: %i[item3 item4], item3: %i[item4], item4: %i[] graph = Dagwood::DependencyGraph.new(item1: %i[item2 item3 item4], item2: %i[item5 item6 item7], item3: %i[item7 item8 item9]) expect(graph.subgraph(:item2).dependencies).to eql item2: %i[item5 item6 item7] graph = Dagwood::DependencyGraph.new(item1: %i[item2 item3 item4], item2: %i[item5 item6 item7], item3: %i[item7 item8 item9], item5: %i[item3]) expect(graph.subgraph(:item2).dependencies).to eql item2: %i[item5 item6 item7], item3: %i[item7 item8 item9], item5: %i[item3] end end describe '#merge' do it 'returns a new graph with all dependencies from both graphs' do graph = Dagwood::DependencyGraph.new(item1: %i[item2]) other = Dagwood::DependencyGraph.new(item3: %i[item4]) merged = graph.merge other expect(merged.dependencies).to contain_exactly([:item1, %i[item2]], [:item3, %i[item4]]) end it 'works with empty graphs' do graph = Dagwood::DependencyGraph.new(item1: %i[item2]) other = Dagwood::DependencyGraph.new({}) merged = graph.merge other expect(merged.dependencies).to contain_exactly([:item1, %i[item2]]) end it 'merges duplicate dependencies' do graph = Dagwood::DependencyGraph.new(item1: %i[item2 item3]) other = Dagwood::DependencyGraph.new(item1: %i[item2]) merged = graph.merge other expect(merged.dependencies).to contain_exactly([:item1, %i[item2 item3]]) graph = Dagwood::DependencyGraph.new(item1: %i[item2]) other = Dagwood::DependencyGraph.new(item1: %i[item2 item3]) merged = graph.merge other expect(merged.dependencies).to contain_exactly([:item1, %i[item2 item3]]) graph = Dagwood::DependencyGraph.new(item1: %i[item2]) other = Dagwood::DependencyGraph.new(item1: %i[item2]) merged = graph.merge other expect(merged.dependencies).to contain_exactly([:item1, %i[item2]]) end end end
davosky/OpisNext
config/routes.rb
<gh_stars>0 # frozen_string_literal: true Rails.application.routes.draw do root to: 'dashboard#index' resources :howtos get 'dashboard/index' get 'dashboard/credits' get 'dashboard/authorization' devise_for :users, skip: [:registrations] as :user do get 'users/edit' => 'devise/registrations#edit', :as => 'edit_user_registration' put 'users' => 'devise/registrations#update', :as => 'user_registration' end mount RailsAdmin::Engine => '/admin', as: 'rails_admin' resources :inca_receipts do collection do get :billdownload end end resources :inca_subscriptions do collection do get :billdownload get :billdownloadnidil end end resources :generic_subscriptions do collection do get :billdownload get :billdownloadnidil end end end
davosky/OpisNext
app/controllers/generic_subscriptions_controller.rb
<filename>app/controllers/generic_subscriptions_controller.rb class GenericSubscriptionsController < ApplicationController load_and_authorize_resource before_action :set_generic_subscription, only: %i[show edit update destroy] def index @user = current_user @q = GenericSubscription.ransack(params[:q]) @generic_subscriptions = @q.result(didtinct: true).order(name: 'DESC') .paginate(page: params[:page], per_page: 10) @tariffs = Tariff.all.order(position: 'ASC') end def show @tariffs = Tariff.all.order(position: 'ASC') respond_to do |format| format.html format.json format.pdf { render template: 'generic_subscriptions/pdfgenericsubscription', pdf: 'pdfgenericsubscription' } end end def billdownload @tariffs = Tariff.all.order(position: 'ASC') @q = GenericSubscription.ransack(params[:q]) @generic_subscriptions = @q.result(distinct: true) .order(name: 'ASC') .where(cancellation: [false, nil]) .where.not(category_id: 9) respond_to do |format| format.html format.json format.pdf { render template: 'generic_subscriptions/pdfbilldownload', pdf: 'pdfbilldownload' } format.xlsx end @totale @totalegenerale @ufficio @contanti @contantitotale @pos @postotale @bonifico @bonificototale @ccpostale @ccpostaletotale @altro @altrototale end def billdownloadnidil @tariffs = Tariff.all.order(position: 'ASC') @q = GenericSubscription.ransack(params[:q]) @generic_subscriptions = @q.result(distinct: true) .order(name: 'ASC') .where(cancellation: [false, nil]) .where(category_id: 9) respond_to do |format| format.html format.json format.pdf { render template: 'generic_subscriptions/pdfbilldownloadnidil', pdf: 'pdfbilldownload' } format.xlsx end @totale @totalegenerale @ufficio @contanti @contantitotale @pos @postotale @bonifico @bonificototale @ccpostale @ccpostaletotale @altro @altrototale end def new @generic_subscription = GenericSubscription.new @tariffs = Tariff.all.order(position: 'ASC') end def edit redirect_to generic_subscriptions_path if @generic_subscription.cancellation.present? @tariffs = Tariff.all.order(position: 'ASC') end def create @generic_subscription = current_user.generic_subscriptions.build(generic_subscription_params) @generic_subscription.date = Date.today @generic_subscription.institute = current_user.institute @tariffs = Tariff.all.order(position: 'ASC') respond_to do |format| if @generic_subscription.save format.html { redirect_to generic_subscriptions_path, notice: 'generic subscription was successfully created.' } format.json { render :show, status: :created, location: @generic_subscription } else format.html { render :new, status: :unprocessable_entity } format.json { render json: @generic_subscription.errors, status: :unprocessable_entity } end end end def update @tariffs = Tariff.all.order(position: 'ASC') respond_to do |format| if @generic_subscription.update(generic_subscription_params) format.html { redirect_to generic_subscriptions_path, notice: 'generic subscription was successfully updated.' } format.json { render :show, status: :ok, location: @generic_subscription } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @generic_subscription.errors, status: :unprocessable_entity } end end end def destroy @tariffs = Tariff.all.order(position: 'ASC') @generic_subscription.destroy respond_to do |format| format.html { redirect_to generic_subscriptions_url, notice: 'generic subscription was successfully destroyed.' } format.json { head :no_content } end end private def set_generic_subscription @generic_subscription = GenericSubscription.find(params[:id]) end def generic_subscription_params params.require(:generic_subscription).permit(:generic_office_id, :subscription_typology_id, :customer_name, :customer_forname, :sex_id, :customer_birth_place, :customer_birth_date, :customer_fiscal_code, :customer_nationality, :customer_address, :customer_zip, :customer_city, :customer_province, :customer_phone, :customer_mobile, :customer_email, :company_vat_number, :company_fiscal_code, :company_name, :company_address, :company_zip, :company_city, :company_province, :company_typology_id, :work_qualify_id, :work_level_id, :work_contract, :work_worker_id, :work_employee_date, :work_workplace, :payment, :payment_typology_id, :category_id, :subscription_year_id, :generic_practise_id, :privacy_one_id, :privacy_two_id, :privacy_three_id, :note, :cancellation, :cancellation_reason, :name, :date, :institute, :user_id, :pdf) end end
davosky/OpisNext
app/models/payment_typology.rb
<filename>app/models/payment_typology.rb # frozen_string_literal: true class PaymentTypology < ApplicationRecord has_many :inca_receipts has_many :inca_subscriptions has_many :generic_subscriptions validates :name, presence: true validates :position, presence: true end
davosky/OpisNext
app/models/work_worker.rb
class WorkWorker < ApplicationRecord has_many :inca_subscriptions has_many :generic_subscriptions validates :name, presence: true validates :position, presence: true end
davosky/OpisNext
app/views/inca_subscriptions/index.json.jbuilder
json.array! @inca_subscriptions, partial: "inca_subscriptions/inca_subscription", as: :inca_subscription
davosky/OpisNext
app/views/inca_receipts/index.json.jbuilder
<gh_stars>0 json.array! @inca_receipts, partial: "inca_receipts/inca_receipt", as: :inca_receipt
davosky/OpisNext
app/views/inca_subscriptions/show.json.jbuilder
<reponame>davosky/OpisNext<filename>app/views/inca_subscriptions/show.json.jbuilder json.partial! "inca_subscriptions/inca_subscription", inca_subscription: @inca_subscription
davosky/OpisNext
config/initializers/rails_admin.rb
# frozen_string_literal: true RailsAdmin.config do |config| config.authorize_with do redirect_to main_app.root_path unless current_user.admin == true end config.parent_controller = 'ApplicationController' config.main_app_name = ['Opis Next Generation'] config.model 'User' do visible true label 'Utente' label_plural 'Utenti' end config.model 'Howto' do visible true label 'Guida' label_plural 'Guide' end config.model 'Category' do visible true label 'Categoria' label_plural 'Categorie' end config.model 'IncaOffice' do visible true label 'Ufficio INCA' label_plural 'Uffici INCA' end config.model 'IncaPractise' do visible true label 'Pratica INCA' label_plural 'Pratiche INCA' end config.model 'PaymentTypology' do visible true label 'Tipo Pagamento' label_plural 'Tipi Pagamento' end config.model 'IncaReceipt' do visible true label 'Ricevuta INCA' label_plural 'Ricevute INCA' end config.model 'SubscriptionTypology' do visible true label 'Tipo Sottoscrizione' label_plural 'Tipi Sottoscrizione' end config.model 'SubscriptionYear' do visible true label 'Anno Sottoscrizione' label_plural 'Anni Sottoscrizione' end config.model 'CompanyTypology' do visible true label 'Tipo Azienda' label_plural 'Tipi Azienda' end config.model 'PrivacyOne' do visible true label 'Privacy Uno' label_plural 'Privacy Uno' end config.model 'PrivacyTwo' do visible true label 'Privacy Due' label_plural 'Privacy Due' end config.model 'PrivacyThree' do visible true label 'Privacy Tre' label_plural 'Privacy Tre' end config.model 'Sex' do visible true label 'Sesso' label_plural 'Sessi' end config.model 'WorkLevel' do visible true label 'Livello' label_plural 'Livelli' end config.model 'WorkQualify' do visible true label 'Qualifica' label_plural 'Qualifiche' end config.model 'WorkWorker' do visible true label 'Tipo Lavoratore' label_plural 'Tipi Lavoratore' end config.model 'IncaSubscription' do visible true label 'Sottoscrizione INCA' label_plural 'Sottoscrizioni INCA' end config.model 'Tariff' do visible true label 'Tariffa Categoria' label_plural 'Tariffe Categorie' end config.model 'GenericSubscription' do visible true label 'Sottoscrizione GENERICA' label_plural 'Sottoscrizioni GENERICHE' end config.model 'GenericOffice' do visible true label 'Ufficio GENERICO' label_plural 'Uffici GENERICI' end config.model 'GenericPractise' do visible true label 'Pratica GENERICA' label_plural 'Pratiche GENERICHE' end config.actions do dashboard index new export bulk_delete show edit delete show_in_app end end
davosky/OpisNext
app/views/howtos/index.json.jbuilder
<reponame>davosky/OpisNext json.array! @howtos, partial: "howtos/howto", as: :howto
davosky/OpisNext
app/models/inca_practise.rb
<reponame>davosky/OpisNext # frozen_string_literal: true class IncaPractise < ApplicationRecord has_many :inca_subscriptions validates :name, presence: true validates :position, presence: true end
davosky/OpisNext
db/migrate/20211210075551_create_tariffs.rb
class CreateTariffs < ActiveRecord::Migration[6.1] def change create_table :tariffs do |t| t.integer :name t.references :category, null: false, foreign_key: true t.integer :position t.string :typology t.decimal :amount, precision: 8, scale: 2, default: 0.0 t.timestamps end end end
davosky/OpisNext
db/migrate/202112166095981_create_generic_subscriptions.rb
class CreateGenericSubscriptions < ActiveRecord::Migration[6.1] def change create_table :generic_subscriptions do |t| t.references :generic_office, null: false, foreign_key: true t.references :subscription_typology, null: false, foreign_key: true t.string :customer_name t.string :customer_forname t.references :sex, null: false, foreign_key: true t.string :customer_birth_place t.date :customer_birth_date t.string :customer_fiscal_code t.string :customer_nationality t.string :customer_address t.string :customer_zip t.string :customer_city t.string :customer_province t.string :customer_phone t.string :customer_mobile t.string :customer_email t.string :company_vat_number t.string :company_fiscal_code t.string :company_name t.string :company_address t.string :company_zip t.string :company_city t.string :company_province t.references :company_typology, null: true, foreign_key: true t.references :work_qualify, null: true, foreign_key: true t.references :work_level, null: true, foreign_key: true t.string :work_contract t.references :work_worker, null: true, foreign_key: true t.date :work_employee_date t.string :work_workplace t.decimal :payment, precision: 8, scale: 2, default: 0.0 t.references :payment_typology, null: false, foreign_key: true t.references :category, null: false, foreign_key: true t.references :subscription_year, null: false, foreign_key: true t.references :generic_practise, null: false, foreign_key: true t.references :privacy_one, null: false, foreign_key: true t.references :privacy_two, null: false, foreign_key: true t.references :privacy_three, null: false, foreign_key: true t.text :note t.boolean :cancellation t.string :cancellation_reason t.integer :name t.date :date t.string :institute t.references :user, null: false, foreign_key: true t.timestamps end end end
davosky/OpisNext
db/schema.rb
<reponame>davosky/OpisNext # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # This file is the source Rails uses to define your schema when running `bin/rails # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to # be faster and is potentially less error prone than running all of your # migrations from scratch. Old migrations may fail to apply correctly if those # migrations use external dependencies or application code. # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 202112166095981) do create_table "active_storage_attachments", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false t.bigint "record_id", null: false t.bigint "blob_id", null: false t.datetime "created_at", null: false t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id" t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true end create_table "active_storage_blobs", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "key", null: false t.string "filename", null: false t.string "content_type" t.text "metadata" t.string "service_name", null: false t.bigint "byte_size", null: false t.string "checksum", null: false t.datetime "created_at", null: false t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true end create_table "active_storage_variant_records", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.bigint "blob_id", null: false t.string "variation_digest", null: false t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true end create_table "categories", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name" t.integer "position" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "company_typologies", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name" t.integer "position" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "generic_offices", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name" t.integer "position" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "generic_practises", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name" t.integer "position" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "generic_subscriptions", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.bigint "generic_office_id", null: false t.bigint "subscription_typology_id", null: false t.string "customer_name" t.string "customer_forname" t.bigint "sex_id", null: false t.string "customer_birth_place" t.date "customer_birth_date" t.string "customer_fiscal_code" t.string "customer_nationality" t.string "customer_address" t.string "customer_zip" t.string "customer_city" t.string "customer_province" t.string "customer_phone" t.string "customer_mobile" t.string "customer_email" t.string "company_vat_number" t.string "company_fiscal_code" t.string "company_name" t.string "company_address" t.string "company_zip" t.string "company_city" t.string "company_province" t.bigint "company_typology_id" t.bigint "work_qualify_id" t.bigint "work_level_id" t.string "work_contract" t.bigint "work_worker_id" t.date "work_employee_date" t.string "work_workplace" t.decimal "payment", precision: 8, scale: 2, default: "0.0" t.bigint "payment_typology_id", null: false t.bigint "category_id", null: false t.bigint "subscription_year_id", null: false t.bigint "generic_practise_id", null: false t.bigint "privacy_one_id", null: false t.bigint "privacy_two_id", null: false t.bigint "privacy_three_id", null: false t.text "note" t.boolean "cancellation" t.string "cancellation_reason" t.integer "name" t.date "date" t.string "institute" t.bigint "user_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["category_id"], name: "index_generic_subscriptions_on_category_id" t.index ["company_typology_id"], name: "index_generic_subscriptions_on_company_typology_id" t.index ["generic_office_id"], name: "index_generic_subscriptions_on_generic_office_id" t.index ["generic_practise_id"], name: "index_generic_subscriptions_on_generic_practise_id" t.index ["payment_typology_id"], name: "index_generic_subscriptions_on_payment_typology_id" t.index ["privacy_one_id"], name: "index_generic_subscriptions_on_privacy_one_id" t.index ["privacy_three_id"], name: "index_generic_subscriptions_on_privacy_three_id" t.index ["privacy_two_id"], name: "index_generic_subscriptions_on_privacy_two_id" t.index ["sex_id"], name: "index_generic_subscriptions_on_sex_id" t.index ["subscription_typology_id"], name: "index_generic_subscriptions_on_subscription_typology_id" t.index ["subscription_year_id"], name: "index_generic_subscriptions_on_subscription_year_id" t.index ["user_id"], name: "index_generic_subscriptions_on_user_id" t.index ["work_level_id"], name: "index_generic_subscriptions_on_work_level_id" t.index ["work_qualify_id"], name: "index_generic_subscriptions_on_work_qualify_id" t.index ["work_worker_id"], name: "index_generic_subscriptions_on_work_worker_id" end create_table "howtos", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "title" t.string "topic" t.text "description" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "inca_offices", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name" t.integer "position" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "inca_practises", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name" t.integer "position" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "inca_receipts", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.bigint "inca_office_id", null: false t.string "customer_name" t.string "customer_forname" t.string "customer_birth_place" t.date "customer_birth_date" t.string "customer_fiscal_code" t.string "customer_address" t.string "customer_zip" t.string "customer_city" t.string "customer_province" t.decimal "payment", precision: 8, scale: 2, default: "0.0" t.bigint "payment_typology_id", null: false t.text "note" t.integer "name" t.date "date" t.bigint "user_id", null: false t.string "institute" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.boolean "cancellation" t.string "cancellation_reason" t.index ["inca_office_id"], name: "index_inca_receipts_on_inca_office_id" t.index ["payment_typology_id"], name: "index_inca_receipts_on_payment_typology_id" t.index ["user_id"], name: "index_inca_receipts_on_user_id" end create_table "inca_subscriptions", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.bigint "inca_office_id", null: false t.bigint "subscription_typology_id", null: false t.string "customer_name" t.string "customer_forname" t.bigint "sex_id", null: false t.string "customer_birth_place" t.date "customer_birth_date" t.string "customer_fiscal_code" t.string "customer_nationality" t.string "customer_address" t.string "customer_zip" t.string "customer_city" t.string "customer_province" t.string "customer_phone" t.string "customer_mobile" t.string "customer_email" t.string "company_vat_number" t.string "company_name" t.string "company_address" t.string "company_zip" t.string "company_city" t.string "company_province" t.bigint "company_typology_id" t.bigint "work_qualify_id" t.bigint "work_level_id" t.string "work_contract" t.bigint "work_worker_id" t.date "work_employee_date" t.string "work_workplace" t.decimal "payment", precision: 8, scale: 2, default: "0.0" t.bigint "payment_typology_id", null: false t.bigint "category_id", null: false t.bigint "subscription_year_id", null: false t.bigint "inca_practise_id", null: false t.bigint "privacy_one_id", null: false t.bigint "privacy_two_id", null: false t.bigint "privacy_three_id", null: false t.text "note" t.boolean "cancellation" t.string "cancellation_reason" t.integer "name" t.date "date" t.string "institute" t.bigint "user_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.integer "cancellation_id" t.string "pdf_file_name" t.string "pdf_content_type" t.bigint "pdf_file_size" t.datetime "pdf_updated_at" t.string "company_vat_code" t.string "company_fiscal_code" t.index ["category_id"], name: "index_inca_subscriptions_on_category_id" t.index ["company_typology_id"], name: "index_inca_subscriptions_on_company_typology_id" t.index ["inca_office_id"], name: "index_inca_subscriptions_on_inca_office_id" t.index ["inca_practise_id"], name: "index_inca_subscriptions_on_inca_practise_id" t.index ["payment_typology_id"], name: "index_inca_subscriptions_on_payment_typology_id" t.index ["privacy_one_id"], name: "index_inca_subscriptions_on_privacy_one_id" t.index ["privacy_three_id"], name: "index_inca_subscriptions_on_privacy_three_id" t.index ["privacy_two_id"], name: "index_inca_subscriptions_on_privacy_two_id" t.index ["sex_id"], name: "index_inca_subscriptions_on_sex_id" t.index ["subscription_typology_id"], name: "index_inca_subscriptions_on_subscription_typology_id" t.index ["subscription_year_id"], name: "index_inca_subscriptions_on_subscription_year_id" t.index ["user_id"], name: "index_inca_subscriptions_on_user_id" t.index ["work_level_id"], name: "index_inca_subscriptions_on_work_level_id" t.index ["work_qualify_id"], name: "index_inca_subscriptions_on_work_qualify_id" t.index ["work_worker_id"], name: "index_inca_subscriptions_on_work_worker_id" end create_table "payment_typologies", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name" t.integer "position" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "privacy_ones", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name" t.integer "position" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "privacy_threes", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name" t.integer "position" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "privacy_twos", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name" t.integer "position" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "sexes", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name" t.integer "position" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "subscription_typologies", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name" t.integer "position" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "subscription_years", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name" t.integer "position" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "tariffs", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.integer "name" t.bigint "category_id", null: false t.integer "position" t.string "typology" t.decimal "amount", precision: 8, scale: 2, default: "0.0" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["category_id"], name: "index_tariffs_on_category_id" end create_table "users", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.boolean "admin", default: false t.boolean "manager", default: false t.boolean "regular", default: true t.string "name" t.string "address" t.string "mobile" t.string "pec" t.string "institute" t.string "office" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["email"], name: "index_users_on_email", unique: true t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true end create_table "work_levels", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name" t.integer "position" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "work_qualifies", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name" t.integer "position" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "work_workers", charset: "utf8mb4", collation: "utf8mb4_unicode_ci", force: :cascade do |t| t.string "name" t.integer "position" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id" add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id" add_foreign_key "generic_subscriptions", "categories" add_foreign_key "generic_subscriptions", "company_typologies" add_foreign_key "generic_subscriptions", "generic_offices" add_foreign_key "generic_subscriptions", "generic_practises" add_foreign_key "generic_subscriptions", "payment_typologies" add_foreign_key "generic_subscriptions", "privacy_ones" add_foreign_key "generic_subscriptions", "privacy_threes" add_foreign_key "generic_subscriptions", "privacy_twos" add_foreign_key "generic_subscriptions", "sexes" add_foreign_key "generic_subscriptions", "subscription_typologies" add_foreign_key "generic_subscriptions", "subscription_years" add_foreign_key "generic_subscriptions", "users" add_foreign_key "generic_subscriptions", "work_levels" add_foreign_key "generic_subscriptions", "work_qualifies" add_foreign_key "generic_subscriptions", "work_workers" add_foreign_key "inca_receipts", "inca_offices" add_foreign_key "inca_receipts", "payment_typologies" add_foreign_key "inca_receipts", "users" add_foreign_key "inca_subscriptions", "categories" add_foreign_key "inca_subscriptions", "company_typologies" add_foreign_key "inca_subscriptions", "inca_offices" add_foreign_key "inca_subscriptions", "inca_practises" add_foreign_key "inca_subscriptions", "payment_typologies" add_foreign_key "inca_subscriptions", "privacy_ones" add_foreign_key "inca_subscriptions", "privacy_threes" add_foreign_key "inca_subscriptions", "privacy_twos" add_foreign_key "inca_subscriptions", "sexes" add_foreign_key "inca_subscriptions", "subscription_typologies" add_foreign_key "inca_subscriptions", "subscription_years" add_foreign_key "inca_subscriptions", "users" add_foreign_key "inca_subscriptions", "work_levels" add_foreign_key "inca_subscriptions", "work_qualifies" add_foreign_key "inca_subscriptions", "work_workers" add_foreign_key "tariffs", "categories" end
davosky/OpisNext
app/models/inca_subscription.rb
class IncaSubscription < ApplicationRecord belongs_to :inca_office belongs_to :subscription_typology belongs_to :sex belongs_to :company_typology, optional: true belongs_to :work_qualify, optional: true belongs_to :work_level, optional: true belongs_to :work_worker, optional: true belongs_to :payment_typology belongs_to :category belongs_to :subscription_year belongs_to :inca_practise belongs_to :privacy_one belongs_to :privacy_two belongs_to :privacy_three belongs_to :user has_one_attached :pdf before_create :set_name def set_name last_name = IncaSubscription.maximum(:name) self.name = last_name.to_i + 1 end validates :customer_name, presence: true validates :customer_forname, presence: true validates :customer_birth_place, presence: true validates :customer_birth_date, presence: true validates :customer_fiscal_code, presence: true validates :sex_id, presence: true validates :customer_address, presence: true validates :customer_zip, presence: true validates :customer_city, presence: true validates :customer_province, presence: true validates :customer_nationality, presence: true validates :payment, presence: true validates :payment_typology_id, presence: true validates :inca_office_id, presence: true validates :inca_practise_id, presence: true validates :subscription_year, presence: true validates :category_id, presence: true validates :privacy_one, presence: true validates :privacy_two, presence: true validates :privacy_three, presence: true validates :cancellation_reason, if: -> { cancellation == true }, presence: true end
davosky/OpisNext
app/controllers/howtos_controller.rb
# frozen_string_literal: true class HowtosController < ApplicationController load_and_authorize_resource before_action :set_howto, only: %i[show edit update destroy] def index @howtos = Howto.all.paginate(page: params[:page], per_page: 5) end def show; end def new @howto = Howto.new # authorize! :create, @howto end def edit # authorize! :update, @howto end def create @howto = Howto.new(howto_params) respond_to do |format| if @howto.save format.html { redirect_to @howto, notice: 'Howto was successfully created.' } format.json { render :show, status: :created, location: @howto } else format.html { render :new, status: :unprocessable_entity } format.json { render json: @howto.errors, status: :unprocessable_entity } end end end def update respond_to do |format| if @howto.update(howto_params) format.html { redirect_to @howto, notice: 'Howto was successfully updated.' } format.json { render :show, status: :ok, location: @howto } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @howto.errors, status: :unprocessable_entity } end end end def destroy @howto.destroy respond_to do |format| format.html { redirect_to howtos_url, notice: 'Howto was successfully destroyed.' } format.json { head :no_content } end # authorize! :destroy, @howto end private def set_howto @howto = Howto.find(params[:id]) end def howto_params params.require(:howto).permit(:title, :topic, :description) end end
davosky/OpisNext
app/controllers/inca_subscriptions_controller.rb
class IncaSubscriptionsController < ApplicationController load_and_authorize_resource before_action :set_inca_subscription, only: %i[show edit update destroy] def index @user = current_user @q = IncaSubscription.ransack(params[:q]) @inca_subscriptions = @q.result(didtinct: true).order(name: 'DESC') .paginate(page: params[:page], per_page: 10) @tariffs = Tariff.all.order(position: 'ASC') end def show @tariffs = Tariff.all.order(position: 'ASC') respond_to do |format| format.html format.json format.pdf { render template: 'inca_subscriptions/pdfincasubscription', pdf: 'pdfincasubscription' } end end def billdownload @tariffs = Tariff.all.order(position: 'ASC') @q = IncaSubscription.ransack(params[:q]) @inca_subscriptions = @q.result(distinct: true) .order(name: 'ASC') .where(cancellation: [false, nil]) .where.not(category_id: 9) respond_to do |format| format.html format.json format.pdf { render template: 'inca_subscriptions/pdfbilldownload', pdf: 'pdfbilldownload' } format.xlsx end @totale @totalegenerale @ufficio @contanti @contantitotale @pos @postotale @bonifico @bonificototale @ccpostale @ccpostaletotale @altro @altrototale end def billdownloadnidil @tariffs = Tariff.all.order(position: 'ASC') @q = IncaSubscription.ransack(params[:q]) @inca_subscriptions = @q.result(distinct: true) .order(name: 'ASC') .where(cancellation: [false, nil]) .where(category_id: 9) respond_to do |format| format.html format.json format.pdf { render template: 'inca_subscriptions/pdfbilldownloadnidil', pdf: 'pdfbilldownload' } format.xlsx end @totale @totalegenerale @ufficio @contanti @contantitotale @pos @postotale @bonifico @bonificototale @ccpostale @ccpostaletotale @altro @altrototale end def new @inca_subscription = IncaSubscription.new @tariffs = Tariff.all.order(position: 'ASC') end def edit redirect_to inca_subscriptions_path if @inca_subscription.cancellation.present? @tariffs = Tariff.all.order(position: 'ASC') end def create @inca_subscription = current_user.inca_subscriptions.build(inca_subscription_params) @inca_subscription.date = Date.today @inca_subscription.institute = current_user.institute @tariffs = Tariff.all.order(position: 'ASC') respond_to do |format| if @inca_subscription.save format.html { redirect_to inca_subscriptions_path, notice: 'Inca subscription was successfully created.' } format.json { render :show, status: :created, location: @inca_subscription } else format.html { render :new, status: :unprocessable_entity } format.json { render json: @inca_subscription.errors, status: :unprocessable_entity } end end end def update @tariffs = Tariff.all.order(position: 'ASC') respond_to do |format| if @inca_subscription.update(inca_subscription_params) format.html { redirect_to inca_subscriptions_path, notice: 'Inca subscription was successfully updated.' } format.json { render :show, status: :ok, location: @inca_subscription } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @inca_subscription.errors, status: :unprocessable_entity } end end end def destroy @tariffs = Tariff.all.order(position: 'ASC') @inca_subscription.destroy respond_to do |format| format.html { redirect_to inca_subscriptions_url, notice: 'Inca subscription was successfully destroyed.' } format.json { head :no_content } end end private def set_inca_subscription @inca_subscription = IncaSubscription.find(params[:id]) end def inca_subscription_params params.require(:inca_subscription).permit(:inca_office_id, :subscription_typology_id, :customer_name, :customer_forname, :sex_id, :customer_birth_place, :customer_birth_date, :customer_fiscal_code, :customer_nationality, :customer_address, :customer_zip, :customer_city, :customer_province, :customer_phone, :customer_mobile, :customer_email, :company_vat_number, :company_fiscal_code, :company_name, :company_address, :company_zip, :company_city, :company_province, :company_typology_id, :work_qualify_id, :work_level_id, :work_contract, :work_worker_id, :work_employee_date, :work_workplace, :payment, :payment_typology_id, :category_id, :subscription_year_id, :inca_practise_id, :privacy_one_id, :privacy_two_id, :privacy_three_id, :note, :cancellation, :cancellation_reason, :name, :date, :institute, :user_id, :pdf) end end
davosky/OpisNext
app/helpers/application_helper.rb
# frozen_string_literal: true module ApplicationHelper def admin? current_user.admin == true end def full_user "#{current_user.name} - #{current_user.institute}" end def inca_receipt_customer_full_name(inca_receipt) "#{inca_receipt.customer_name} #{inca_receipt.customer_forname}" end def inca_subscription_customer_full_name(inca_subscription) "#{inca_subscription.customer_name} #{inca_subscription.customer_forname}" end def generic_subscription_customer_full_name(generic_subscription) "#{generic_subscription.customer_name} #{generic_subscription.customer_forname}" end def cancelled?(inca_receipt) 'text-white bg-primary' if inca_receipt.cancellation end def inca_user? current_user.institute == 'Patronato INCA' || current_user.admin == true || current_user.institute == 'Ufficio Amministrazione' end def generic_user? current_user.institute != 'Patronato INCA' || current_user.admin == true || current_user.institute == 'Ufficio Amministrazione' end end
davosky/OpisNext
app/controllers/dashboard_controller.rb
class DashboardController < ApplicationController def index; end def credits; end def authorization; end end
davosky/OpisNext
app/views/howtos/show.json.jbuilder
json.partial! "howtos/howto", howto: @howto
davosky/OpisNext
app/models/howto.rb
<reponame>davosky/OpisNext # frozen_string_literal: true class Howto < ApplicationRecord validates :title, presence: true validates :topic, presence: true validates :description, presence: true end
davosky/OpisNext
app/views/howtos/_howto.json.jbuilder
<reponame>davosky/OpisNext json.extract! howto, :id, :title, :topic, :description, :created_at, :updated_at json.url howto_url(howto, format: :json)
davosky/OpisNext
app/models/ability.rb
<filename>app/models/ability.rb # frozen_string_literal: true class Ability include CanCan::Ability def initialize(user) can :manage, :all if user.present? && user.admin == true can :read, Howto if user.present? if user.institute == 'Ufficio Amministrazione' can :billdownload, IncaReceipt can :billdownload, IncaSubscription can :billdownloadnidil, IncaSubscription can :read, IncaReceipt can :read, IncaSubscription can :billdownload, GenericSubscription can :billdownloadnidil, GenericSubscription can :read, GenericSubscription end if user.institute == 'Patronato INCA' can :billdownload, IncaReceipt do |inca_receipt| inca_receipt.user == user end can :billdownload, IncaSubscription do |inca_subscription| inca_subscription.user == user end can :billdownloadnidil, IncaSubscription do |inca_subscription| inca_subscription.user == user end can :read, IncaReceipt can :create, IncaReceipt can :update, IncaReceipt do |inca_receipt| inca_receipt.user == user end can :read, IncaSubscription can :create, IncaSubscription can :update, IncaSubscription do |inca_subscription| inca_subscription.user == user end end if user.institute != 'Patronato INCA' can :billdownload, GenericSubscription do |generic_subscription| generic_subscription.user == user end can :billdownloadnidil, GenericSubscription do |generic_subscription| generic_subscription.user == user end can :read, GenericSubscription can :create, GenericSubscription can :update, GenericSubscription do |generic_subscription| generic_subscription.user == user end end end end
davosky/OpisNext
app/views/generic_subscriptions/index.json.jbuilder
<reponame>davosky/OpisNext<gh_stars>0 json.array! @generic_subscriptions, partial: 'generic_subscriptions/generic_subscription', as: :generic_subscription
davosky/OpisNext
app/models/inca_receipt.rb
<gh_stars>0 class IncaReceipt < ApplicationRecord belongs_to :inca_office belongs_to :payment_typology belongs_to :user has_one_attached :pdf before_create :set_name def set_name last_name = IncaReceipt.maximum(:name) self.name = last_name.to_i + 1 end validates :date, presence: true validates :user_id, presence: true validates :institute, presence: true validates :inca_office_id, presence: true validates :customer_name, presence: true validates :customer_forname, presence: true validates :customer_birth_place, presence: true validates :customer_birth_date, presence: true validates :customer_fiscal_code, presence: true validates :customer_address, presence: true validates :customer_zip, presence: true validates :customer_city, presence: true validates :customer_province, presence: true validates :payment, presence: true validates :payment_typology_id, presence: true validates :cancellation_reason, if: -> { cancellation == true }, presence: true end
davosky/OpisNext
app/controllers/inca_receipts_controller.rb
# frozen_string_literal: true class IncaReceiptsController < ApplicationController load_and_authorize_resource before_action :set_inca_receipt, only: %i[show edit update destroy] def index @user = current_user @q = IncaReceipt.ransack(params[:q]) @inca_receipts = @q.result(distinct: true).order(name: 'DESC') .paginate(page: params[:page], per_page: 10) end def show respond_to do |format| format.html format.json format.pdf { render template: 'inca_receipts/pdfincareceipt', pdf: 'pdfincareceipt' } end end def new @inca_receipt = IncaReceipt.new end def edit redirect_to inca_receipts_path if @inca_receipt.cancellation.present? end def billdownload @user = current_user @q = IncaReceipt.ransack(params[:q]) @inca_receipts = @q.result(distinct: true) .where(cancellation: [false, nil]) .order(name: 'ASC') respond_to do |format| format.html format.json format.pdf { render template: 'inca_receipts/pdfbilldownload', pdf: 'pdfbilldownload' } format.xlsx end @totale @totalegenerale @ufficio @contanti @contantitotale @pos @postotale @bonifico @bonificototale @ccpostale @ccpostaletotale @altro @altrototale end def create @inca_receipt = current_user.inca_receipts.build(inca_receipt_params) @inca_receipt.date = Date.today @inca_receipt.institute = current_user.institute respond_to do |format| if @inca_receipt.save format.html { redirect_to inca_receipts_path, notice: 'Inca receipt was successfully created.' } format.json { render :show, status: :created, location: @inca_receipt } else format.html { render :new, status: :unprocessable_entity } format.json { render json: @inca_receipt.errors, status: :unprocessable_entity } end end end def update respond_to do |format| if @inca_receipt.update(inca_receipt_params) format.html { redirect_to inca_receipts_path, notice: 'Inca receipt was successfully updated.' } format.json { render :show, status: :ok, location: @inca_receipt } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @inca_receipt.errors, status: :unprocessable_entity } end end end def destroy @inca_receipt.destroy respond_to do |format| format.html { redirect_to inca_receipts_url, notice: 'Inca receipt was successfully destroyed.' } format.json { head :no_content } end end private def set_inca_receipt @inca_receipt = IncaReceipt.find(params[:id]) end def inca_receipt_params params.require(:inca_receipt).permit(:inca_office_id, :customer_name, :customer_forname, :customer_birth_place, :customer_birth_date, :customer_fiscal_code, :customer_address, :customer_zip, :customer_city, :customer_province, :payment, :payment_typology_id, :note, :name, :date, :user_id, :institute, :pdf, :cancellation, :cancellation_reason) end end
davosky/OpisNext
db/migrate/20211121081814_add_cancellation_to_inca_receipt.rb
<reponame>davosky/OpisNext<filename>db/migrate/20211121081814_add_cancellation_to_inca_receipt.rb class AddCancellationToIncaReceipt < ActiveRecord::Migration[6.1] def change add_column :inca_receipts, :cancellation, :boolean add_column :inca_receipts, :cancellation_reason, :string end end
davosky/OpisNext
app/views/generic_subscriptions/show.json.jbuilder
<filename>app/views/generic_subscriptions/show.json.jbuilder json.partial! 'generic_subscriptions/generic_subscription', generic_subscription: @generic_subscription
davosky/OpisNext
db/migrate/20211101104357_create_inca_receipts.rb
<filename>db/migrate/20211101104357_create_inca_receipts.rb class CreateIncaReceipts < ActiveRecord::Migration[6.1] def change create_table :inca_receipts do |t| t.references :inca_office, null: false, foreign_key: true t.string :customer_name t.string :customer_forname t.string :customer_birth_place t.date :customer_birth_date t.string :customer_fiscal_code t.string :customer_address t.string :customer_zip t.string :customer_city t.string :customer_province t.decimal :payment, precision: 8, scale: 2, default: 0 t.references :payment_typology, null: false, foreign_key: true t.text :note t.integer :name t.date :date t.references :user, null: false, foreign_key: true t.string :institute t.timestamps end end end
davosky/OpisNext
app/models/inca_office.rb
<gh_stars>0 # frozen_string_literal: true class IncaOffice < ApplicationRecord has_many :inca_receipts has_many :inca_subscriptions validates :name, presence: true validates :position, presence: true end
davosky/OpisNext
app/views/inca_receipts/show.json.jbuilder
json.partial! "inca_receipts/inca_receipt", inca_receipt: @inca_receipt
davosky/OpisNext
app/models/user.rb
# frozen_string_literal: true class User < ApplicationRecord devise :database_authenticatable, :registerable validate :password_complexity def password_complexity if password.present? && !password.match(/^(?=.*[a-z])(?=.*[A-Z])/) errors.add :password, 'La password non è sufficientemente complessa' end end has_many :inca_receipts has_many :inca_subscriptions has_many :generic_subscriptions validates :name, presence: true validates :institute, presence: true end
davosky/OpisNext
app/models/tariff.rb
class Tariff < ApplicationRecord belongs_to :category before_create :set_name def set_name last_name = Tariff.maximum(:name) self.name = last_name.to_i + 1 end validates :category_id, presence: true validates :typology, presence: true validates :amount, presence: true end
br/cache_fu
test/sti_test.rb
<reponame>br/cache_fu require File.join(File.dirname(__FILE__), 'helper') context "An STI subclass acting as cached" do include StoryCacheSpecSetup setup do @feature = Feature.new(:id => 3, :title => 'Behind the scenes of acts_as_cached') @interview = Interview.new(:id => 4, :title => 'An interview with the Arcade Fire') @feature.expire_cache @interview.expire_cache $stories.update 3 => @feature, 4 => @interview end specify "should be just as retrievable as any other cachable Ruby object" do Feature.cached?(3).should.equal false Feature.get_cache(3) Feature.cached?(3).should.equal true end specify "should have a key corresponding to its parent class" do @feature.cache_key.should.equal "Story:3" @interview.cache_key.should.equal "Story:4" end specify "should be able to get itself from the cache via its parent class" do Story.get_cache(3).should.equal @feature Story.get_cache(4).should.equal @interview end specify "should take on its parents cache options but be able to set its own" do @feature.cache_key.should.equal "Story:3" Feature.cache_config[:version] = 1 @feature.cache_key.should.equal "Story:1:3" @story.cache_key.should.equal "Story:1" end end
br/cache_fu
lib/acts_as_cached/recipes.rb
<reponame>br/cache_fu Capistrano.configuration(:must_exist).load do %w(start stop restart kill status).each do |cmd| desc "#{cmd} your memcached servers" task "memcached_#{cmd}".to_sym, :roles => :app do run "RAILS_ENV=production #{ruby} #{current_path}/script/memcached_ctl #{cmd}" end end end
br/cache_fu
lib/acts_as_cached/memcached_rails.rb
<gh_stars>1-10 class Memcached # A legacy compatibility wrapper for the Memcached class. It has basic compatibility with the <b>memcache-client</b> API. class Rails < ::Memcached def initialize(config) super(config.delete(:servers), config.slice(DEFAULTS.keys)) end def servers=(servers) end def delete(key, expiry = 0) super(key) rescue NotFound end end end
br/cache_fu
test/helper.rb
## # This file exists to fake out all the Railsisms we use so we can run the # tests in isolation. $LOAD_PATH.unshift 'lib/' # begin require 'rubygems' gem 'mocha', '>= 0.4.0' require 'mocha' gem 'test-spec', '= 0.3.0' require 'test/spec' require 'multi_rails_init' rescue LoadError puts '=> acts_as_cached tests depend on the following gems: mocha (0.4.0+), test-spec (0.3.0), multi_rails (0.0.2), and rails.' end begin require 'redgreen' rescue LoadError nil end Test::Spec::Should.send :alias_method, :have, :be Test::Spec::ShouldNot.send :alias_method, :have, :be ## # real men test without mocks if $with_memcache = ARGV.include?('with-memcache') require 'memcache' end ## # init.rb hacks RAILS_ROOT = '.' unless defined? RAILS_ROOT RAILS_ENV = 'test' unless defined? RAILS_ENV ## # get the default config using absolute path, so tests all play nice when run in isolation DEFAULT_CONFIG_FILE = File.expand_path(File.dirname(__FILE__) + '/../defaults/memcached.yml.default') ## # aac require 'acts_as_cached' Object.send :include, ActsAsCached::Mixin ## # i need you. module Enumerable def index_by inject({}) do |accum, elem| accum[yield(elem)] = elem accum end end end ## # mocky. class HashStore < Hash alias :get :[] def get_multi(*values) reject { |k,v| !values.include? k } end def set(key, value, *others) self[key] = value end def namespace nil end end $cache = HashStore.new class Story acts_as_cached($with_memcache ? {} : { :store => $cache }) attr_accessor :id, :title def initialize(attributes = {}) attributes.each { |key, value| instance_variable_set("@#{key}", value) } end def attributes { :id => id, :title => title } end def ==(other) return false unless other.respond_to? :attributes attributes == other.attributes end def self.find(*args) options = args.last.is_a?(Hash) ? args.pop : {} if (ids = args.flatten).size > 1 ids.map { |id| $stories[id.to_i] } elsif (id = args.flatten.first).to_i.to_s == id.to_s $stories[id.to_i] end end def self.find_by_title(*args) title = args.shift find(args).select { |s| s.title == title } end def self.base_class Story end def self.something_cool; :redbull end def something_flashy; :molassy end def self.block_on(target = nil) target || :something end def self.pass_through(target) target end def self.two_params(first, second) "first: #{first} | second: #{second}" end def self.find_live(*args) false end end class Feature < Story; end class Interview < Story; end module ActionController class Base def rendering_runtime(*args) '' end def self.silence; yield end end end class MemCache attr_accessor :servers def initialize(*args) end class MemCacheError < StandardError; end unless defined? MemCacheError end unless $with_memcache module StoryCacheSpecSetup def self.included(base) base.setup do setup_cache_spec Story.instance_eval { @max_key_length = nil } end end def setup_cache_spec @story = Story.new(:id => 1, :title => "acts_as_cached 2 released!") @story2 = Story.new(:id => 2, :title => "BDD is something you can use") @story3 = Story.new(:id => 3, :title => "RailsConf is overrated.") $stories = { 1 => @story, 2 => @story2, 3 => @story3 } $with_memcache ? with_memcache : with_mock end def with_memcache unless $mc_setup_for_story_cache_spec ActsAsCached.config.clear config = YAML.load_file(DEFAULT_CONFIG_FILE) config['test'] = config['development'].merge('benchmarking' => false, 'disabled' => false) ActsAsCached.config = config $mc_setup_for_story_cache_spec = true end Story.send :acts_as_cached Story.expire_cache(1) Story.expire_cache(2) Story.expire_cache(3) Story.expire_cache(:block) Story.set_cache(2, @story2) end def with_mock $cache.clear Story.send :acts_as_cached, :store => $cache $cache['Story:2'] = @story2 end end module FragmentCacheSpecSetup def self.included(base) base.setup { setup_fragment_spec } end def setup_fragment_spec unless $mc_setup_for_fragment_cache_spec ActsAsCached.config.clear config = YAML.load_file(DEFAULT_CONFIG_FILE) if $with_memcache other_options = { 'fragments' => true } else Object.const_set(:CACHE, $cache) unless defined? CACHE other_options = { 'fragments' => true, 'store' => $cache } end config['test'] = config['development'].merge other_options ActsAsCached.config = config ActsAsCached::FragmentCache.setup! $mc_setup_for_fragment_cache_spec = true end end end
br/cache_fu
lib/acts_as_cached/local_cache.rb
module ActsAsCached module LocalCache @@local_cache = {} mattr_accessor :local_cache def fetch_cache_with_local_cache(*args) @@local_cache[cache_key(args.first)] ||= fetch_cache_without_local_cache(*args) end def set_cache_with_local_cache(*args) @@local_cache[cache_key(args.first)] = set_cache_without_local_cache(*args) end def expire_cache_with_local_cache(*args) @@local_cache.delete(cache_key(args.first)) expire_cache_without_local_cache(*args) end alias :clear_cache_with_local_cache :expire_cache_with_local_cache def cached_with_local_cache?(*args) !!@@local_cache[cache_key(args.first)] || cached_without_local_cache?(*args) end def self.add_to(klass) return if klass.ancestors.include? self klass.send :include, self klass.class_eval do %w( fetch_cache set_cache expire_cache clear_cache cached? ).each do |target| alias_method_chain target, :local_cache end end end end end module ActionController class Base def local_cache_for_request ActsAsCached::LocalCache.add_to ActsAsCached::ClassMethods ActsAsCached::LocalCache.local_cache = {} end end end
br/cache_fu
test/benchmarking_test.rb
require File.join(File.dirname(__FILE__), 'helper') ActsAsCached.config.clear config = YAML.load_file(File.join(File.dirname(__FILE__), '../defaults/memcached.yml.default')) config['test'] = config['development'] ActsAsCached.config = config Story.send :acts_as_cached context "When benchmarking is enabled" do specify "ActionController::Base should respond to rendering_runtime_with_memcache" do ActionController::Base.new.should.respond_to :rendering_runtime_with_memcache end specify "cachable Ruby classes should be respond to :logger" do Story.should.respond_to :logger end specify "a cached object should gain a fetch_cache with and without benchmarking methods" do Story.should.respond_to :fetch_cache_with_benchmarking Story.should.respond_to :fetch_cache_without_benchmarking end specify "cache_benchmark should yield and time any action" do ActsAsCached::Benchmarking.cache_runtime.should.equal 0.0 level = Class.new { |k| def k.method_missing(*args) true end } Story.stubs(:logger).returns(level) Story.cache_benchmark("Seriously, nothing.", true) { sleep 0.01 "Nothing." }.should.equal "Nothing." ActsAsCached::Benchmarking.cache_runtime.should.be > 0.0 end end
br/cache_fu
test/local_cache_test.rb
require File.join(File.dirname(__FILE__), 'helper') context "When local_cache_for_request is called" do include StoryCacheSpecSetup setup do ActionController::Base.new.local_cache_for_request $cache = CACHE if $with_memcache end specify "get_cache should pull from the local cache on a second hit" do $cache.expects(:get).with('Story:2').returns(@story2) @story2.get_cache $cache.expects(:get).never @story2.get_cache end specify "set_cache should set to the local cache" do $cache.expects(:set).at_least_once.returns(@story) ActsAsCached::LocalCache.local_cache.expects(:[]=).with('Story:1', @story).returns(@story) @story.set_cache end specify "expire_cache should clear from the local cache" do @story2.get_cache $cache.expects(:delete).at_least_once ActsAsCached::LocalCache.local_cache.expects(:delete).with('Story:2') @story2.expire_cache end specify "clear_cache should clear from the local cache" do @story2.get_cache $cache.expects(:delete).at_least_once ActsAsCached::LocalCache.local_cache.expects(:delete).with('Story:2') @story2.clear_cache end specify "cached? should check the local cache" do @story2.get_cache $cache.expects(:get).never @story2.cached? end end
br/cache_fu
test/extensions_test.rb
<gh_stars>10-100 require File.join(File.dirname(__FILE__), 'helper') module ActsAsCached module Extensions module ClassMethods def user_defined_class_method true end end module InstanceMethods def user_defined_instance_method true end end end end context "When Extensions::ClassMethods exists" do include StoryCacheSpecSetup specify "caching classes should extend it" do Story.singleton_methods.should.include 'user_defined_class_method' end end context "When Extensions::InstanceMethods exists" do include StoryCacheSpecSetup specify "caching classes should include it" do Story.instance_methods.should.include 'user_defined_instance_method' end end
br/cache_fu
test/disabled_test.rb
<gh_stars>10-100 require File.join(File.dirname(__FILE__), 'helper') context "When the cache is disabled" do setup do @story = Story.new(:id => 1, :title => "acts_as_cached 2 released!") @story2 = Story.new(:id => 2, :title => "BDD is something you can use") $stories = { 1 => @story, 2 => @story2 } config = YAML.load_file('defaults/memcached.yml.default') config['test'] = config['development'].merge('disabled' => true, 'benchmarking' => false) ActsAsCached.config = config Story.send :acts_as_cached end specify "get_cache should call through to the finder" do Story.expects(:find).at_least_once.returns(@story2) @story2.get_cache.should.equal @story2 end specify "expire_cache should return true" do $cache.expects(:delete).never @story2.expire_cache.should.equal true end specify "reset_cache should return the object" do $cache.expects(:set).never Story.expects(:find).at_least_once.returns(@story2) @story2.reset_cache.should.equal @story2 end specify "set_cache should just return the object" do $cache.expects(:set).never @story2.set_cache.should.equal @story2 end specify "cached? should return false" do $cache.expects(:get).never @story2.should.not.be.cached end end
br/cache_fu
lib/acts_as_cached/disabled.rb
<reponame>br/cache_fu module ActsAsCached module Disabled def fetch_cache_with_disabled(*args) nil end def set_cache_with_disabled(*args) args[1] end def expire_cache_with_disabled(*args) true end def self.add_to(klass) return if klass.respond_to? :fetch_cache_with_disabled klass.extend self class << klass alias_method_chain :fetch_cache, :disabled alias_method_chain :set_cache, :disabled alias_method_chain :expire_cache, :disabled end class << CACHE include FragmentCache::DisabledExtensions end if ActsAsCached.config[:fragments] && defined?(FragmentCache::DisabledExtensions) end end end
br/cache_fu
lib/acts_as_cached/local_fragment_cache.rb
<filename>lib/acts_as_cached/local_fragment_cache.rb module ActsAsCached module LocalFragmentCache @@local_fragment_cache = {} mattr_accessor :local_fragment_cache def read_with_local_cache(*args) @@local_fragment_cache[args.first] ||= read_without_local_cache(*args) end def self.add_to(klass) return if klass.ancestors.include? self klass.send :include, self klass.class_eval do %w( read ).each do |target| alias_method_chain target, :local_cache end end end module InstanceMethods # cache fu extension to be used around blocks that should only be executed when no cache exists def when_fragment_expired(key, unused_param = nil, &block) puts '@@@@@@@@@@@@@@@@ Update your code! Don\' pass times to this method [key: #{key}]' if unused_param unless read_fragment(key) yield end end end end end module ActionController class Base include ActsAsCached::LocalFragmentCache::InstanceMethods def local_fragment_cache_for_request ActsAsCached::LocalFragmentCache.add_to ActsAsCached::FragmentCache::Extensions ActsAsCached::LocalFragmentCache.local_fragment_cache = {} end end end
br/cache_fu
test/fragment_cache_test.rb
require File.join(File.dirname(__FILE__), 'helper') require 'test/unit' require 'action_controller/test_process' ActionController::Routing::Routes.draw do |map| map.connect ':controller/:action/:id' end class FooController < ActionController::Base def url_for(*args) "http://#{Time.now.to_i}.foo.com" end end class BarController < ActionController::Base def page render :text => "give me my bongos" end def index render :text => "doop!" end def edit render :text => "rawk" end def trees_are_swell? true end def rescue_action(e) raise e end end class FooTemplate include ::ActionView::Helpers::CacheHelper attr_reader :controller def initialize @controller = FooController.new end end context "Fragment caching (when used with memcached)" do include FragmentCacheSpecSetup setup do @view = FooTemplate.new end specify "should be able to cache with a normal, non-keyed Rails cache calls" do _erbout = "" content = "Caching is fun!" ActsAsCached.config[:store].expects(:set).with(@view.controller.url_for.gsub('http://',''), content, ActsAsCached.config[:ttl]) @view.cache { _erbout << content } end specify "should be able to cache with a normal cache call when we don't have a default ttl" do begin _erbout = "" content = "Caching is fun!" original_ttl = ActsAsCached.config.delete(:ttl) ActsAsCached.config[:store].expects(:set).with(@view.controller.url_for.gsub('http://',''), content, 25.minutes) @view.cache { _erbout << content } ensure ActsAsCached.config[:ttl] = original_ttl end end specify "should be able to cache with a normal, keyed Rails cache calls" do _erbout = "" content = "Wow, even a key?!" key = "#{Time.now.to_i}_wow_key" ActsAsCached.config[:store].expects(:set).with(key, content, ActsAsCached.config[:ttl]) @view.cache(key) { _erbout << content } end specify "should be able to cache with new time-to-live option" do _erbout = "" content = "Time to live? TIME TO DIE!!" key = "#{Time.now.to_i}_death_key" ActsAsCached.config[:store].expects(:set).with(key, content, 60) @view.cache(key, { :ttl => 60 }) { _erbout << content } end specify "should ignore everything but time-to-live when options are present" do _erbout = "" content = "Don't mess around, here, sir." key = "#{Time.now.to_i}_mess_key" ActsAsCached.config[:store].expects(:set).with(key, content, 60) @view.cache(key, { :other_options => "for the kids", :ttl => 60 }) { _erbout << content } end specify "should be able to skip cache gets" do ActsAsCached.skip_cache_gets = true ActsAsCached.config[:store].expects(:get).never _erbout = "" @view.cache { _erbout << "Caching is fun!" } ActsAsCached.skip_cache_gets = false end end context "Action caching (when used with memcached)" do include FragmentCacheSpecSetup page_content = "give me my bongos" index_content = "doop!" edit_content = "rawk" setup do @controller = BarController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new end teardown do # clear the filter chain between specs to avoid chaos BarController.write_inheritable_attribute('filter_chain', []) end # little helper for prettier expections on the cache def cache_expects(method, expected_times = 1) ActsAsCached.config[:store].expects(method).times(expected_times) end specify "should cache using default ttl for a normal action cache without ttl" do BarController.caches_action :page key = 'test.host/bar/page' cache_expects(:set).with(key, page_content, ActsAsCached.config[:ttl]) get :page @response.body.should == page_content cache_expects(:read).with(key, nil).returns(page_content) get :page @response.body.should == page_content end specify "should cache using defaul ttl for normal, multiple action caches" do BarController.caches_action :page, :index cache_expects(:set).with('test.host/bar/page', page_content, ActsAsCached.config[:ttl]) get :page cache_expects(:set).with('test.host/bar', index_content, ActsAsCached.config[:ttl]) get :index end specify "should be able to action cache with ttl" do BarController.caches_action :page => { :ttl => 2.minutes } cache_expects(:set).with('test.host/bar/page', page_content, 2.minutes) get :page @response.body.should == page_content end specify "should be able to action cache multiple actions with ttls" do BarController.caches_action :index, :page => { :ttl => 5.minutes } cache_expects(:set).with('test.host/bar/page', page_content, 5.minutes) cache_expects(:set).with('test.host/bar', index_content, ActsAsCached.config[:ttl]) get :page @response.body.should == page_content get :index @response.body.should == index_content cache_expects(:read).with('test.host/bar', nil).returns(index_content) get :index end specify "should be able to action cache conditionally when passed something that returns true" do BarController.caches_action :page => { :if => :trees_are_swell? } cache_expects(:set).with('test.host/bar/page', page_content, ActsAsCached.config[:ttl]) get :page @response.body.should == page_content cache_expects(:read).with('test.host/bar/page', nil).returns(page_content) get :page end #check for edginess if [].respond_to?(:extract_options!) specify "should not break cache_path overrides" do BarController.caches_action :page, :cache_path => 'http://test.host/some/custom/path' cache_expects(:set).with('test.host/some/custom/path', page_content, ActsAsCached.config[:ttl]) get :page end specify "should not break cache_path block overrides" do BarController.caches_action :edit, :cache_path => Proc.new { |c| c.params[:id] ? "http://test.host/#{c.params[:id]}/edit" : "http://test.host/edit" } cache_expects(:set).with('test.host/edit', edit_content, ActsAsCached.config[:ttl]) get :edit get :index cache_expects(:set).with('test.host/5/edit', edit_content, ActsAsCached.config[:ttl]) get :edit, :id => 5 end specify "should play nice with custom ttls and cache_path overrides" do BarController.caches_action :page => { :ttl => 5.days }, :cache_path => 'http://test.host/my/custom/path' cache_expects(:set).with('test.host/my/custom/path', page_content, 5.days) get :page end specify "should play nice with custom ttls and cache_path block overrides" do BarController.caches_action :edit, :cache_path => Proc.new { |c| c.params[:id] ? "http://test.host/#{c.params[:id]}/edit" : "http://test.host/edit" } cache_expects(:set).with('test.host/5/edit', edit_content, ActsAsCached.config[:ttl]) get :edit, :id => 5 end specify "should play nice with the most complicated thing i can throw at it" do BarController.caches_action :index => { :ttl => 24.hours }, :page => { :ttl => 5.seconds }, :edit => { :ttl => 5.days }, :cache_path => Proc.new { |c| c.params[:id] ? "http://test.host/#{c.params[:id]}/#{c.params[:action]}" : "http://test.host/#{c.params[:action]}" } cache_expects(:set).with('test.host/index', index_content, 24.hours) get :index cache_expects(:set).with('test.host/5/edit', edit_content, 5.days) get :edit, :id => 5 cache_expects(:set).with('test.host/5/page', page_content, 5.seconds) get :page, :id => 5 cache_expects(:read).with('test.host/5/page', nil).returns(page_content) get :page, :id => 5 cache_expects(:read).with('test.host/5/edit', nil).returns(edit_content) get :edit, :id => 5 cache_expects(:read).with('test.host/index', nil).returns(index_content) get :index end end specify "should be able to skip action caching when passed something that returns false" do BarController.caches_action :page => { :if => Proc.new {|c| !c.trees_are_swell?} } cache_expects(:set, 0).with('test.host/bar/page', page_content, ActsAsCached.config[:ttl]) get :page @response.body.should == page_content end end
streamroot/avplayer-dna-plugin
AVPlayerDNAPlugin.podspec
Pod::Spec.new do |s| s.name = 'AVPlayerDNAPlugin' s.version = '1.1.25' s.swift_version = '5.5' s.summary = 'Streamroot Distributed Network Architecture AVPlayer plugins, a new way to deliver large-scale OTT video' s.homepage = 'https://www.streamroot.io/' s.author = { 'Name' => '<EMAIL>' } s.license = { :type => 'Copyright', :text => 'Copyright 2021 Streamroot. See the terms of service at https://www.streamroot.io/' } s.platform = :ios s.source ={ :git => 'https://github.com/streamroot/avplayer-dna-plugin.git', :tag => "#{s.version}"} s.source_files = 'PlayerDNAPlugin/Classes/*.swift' s.ios.deployment_target = '10.2' s.tvos.deployment_target = '10.2' s.dependency 'StreamrootSDK', '~> 3.25.1' s.pod_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64', 'EXCLUDED_ARCHS[sdk=appletvsimulator*]' => 'arm64' } s.user_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64', 'EXCLUDED_ARCHS[sdk=appletvsimulator*]' => 'arm64' } end
vicmaster/chartjs-rails
chartjs.gemspec
<reponame>vicmaster/chartjs-rails $:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "chartjs/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "chartjs" s.version = Chartjs::VERSION s.authors = ["<NAME>"] s.email = ["<EMAIL>"] s.homepage = "http://www.chartjs.org/" s.summary = "Easy, object oriented client side graphs for designers and developers" s.description = "This Gem is based on this github project https://github.com/nnnick/Chart.js/tree/master" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 4.0.0" s.add_development_dependency "sqlite3" end
dacur/que
lib/que/locker.rb
<gh_stars>0 # frozen_string_literal: true # The Locker class encapsulates a thread that is listening/polling for new # jobs in the DB, locking them, passing their primary keys to workers, then # cleaning up by unlocking them once the workers are done. require 'set' module Que Listener::MESSAGE_FORMATS[:job_available] = { queue: String, id: Integer, run_at: TIME_REGEX, priority: Integer, } SQL[:clean_lockers] = %{ DELETE FROM public.que_lockers WHERE pid = pg_backend_pid() OR NOT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid = public.que_lockers.pid) } SQL[:register_locker] = %{ INSERT INTO public.que_lockers (pid, worker_count, worker_priorities, ruby_pid, ruby_hostname, listening, queues) VALUES (pg_backend_pid(), $1::integer, $2::integer[], $3::integer, $4::text, $5::boolean, $6::text[]) } class Locker attr_reader :thread, :workers, :job_buffer, :locks MESSAGE_RESOLVERS = {} RESULT_RESOLVERS = {} MESSAGE_RESOLVERS[:job_available] = -> (messages) { metajobs = messages.map { |key| Metajob.new(key) } push_jobs(lock_jobs(job_buffer.accept?(metajobs))) } RESULT_RESOLVERS[:job_finished] = -> (messages) { finish_jobs(messages.map{|m| m.fetch(:metajob)}) } DEFAULT_POLL_INTERVAL = 5.0 DEFAULT_WAIT_PERIOD = 50 DEFAULT_MINIMUM_BUFFER_SIZE = 2 DEFAULT_MAXIMUM_BUFFER_SIZE = 8 DEFAULT_WORKER_PRIORITIES = [10, 30, 50, nil, nil, nil].freeze def initialize( queues: [Que.default_queue], connection_url: nil, listen: true, poll: true, poll_interval: DEFAULT_POLL_INTERVAL, wait_period: DEFAULT_WAIT_PERIOD, maximum_buffer_size: DEFAULT_MAXIMUM_BUFFER_SIZE, minimum_buffer_size: DEFAULT_MINIMUM_BUFFER_SIZE, worker_priorities: DEFAULT_WORKER_PRIORITIES, on_worker_start: nil ) # Sanity-check all our arguments, since some users may instantiate Locker # directly. Que.assert [TrueClass, FalseClass], listen Que.assert [TrueClass, FalseClass], poll Que.assert Numeric, poll_interval Que.assert Numeric, wait_period Que.assert Array, worker_priorities worker_priorities.each { |p| Que.assert([Integer, NilClass], p) } # We use a JobBuffer to track jobs and pass them to workers, and a # ResultQueue to receive messages from workers. @job_buffer = JobBuffer.new( maximum_size: maximum_buffer_size, minimum_size: minimum_buffer_size, priorities: worker_priorities.uniq, ) @result_queue = ResultQueue.new @stop = false Que.internal_log :locker_instantiate, self do { queues: queues, listen: listen, poll: poll, poll_interval: poll_interval, wait_period: wait_period, maximum_buffer_size: maximum_buffer_size, minimum_buffer_size: minimum_buffer_size, worker_priorities: worker_priorities, } end # Local cache of which advisory locks are held by this connection. @locks = Set.new @queue_names = queues.is_a?(Hash) ? queues.keys : queues @wait_period = wait_period.to_f / 1000 # Milliseconds to seconds. @workers = worker_priorities.map do |priority| Worker.new( priority: priority, job_buffer: @job_buffer, result_queue: @result_queue, start_callback: on_worker_start, ) end # To prevent race conditions, let every worker get into a ready state # before starting up the locker thread. loop do break if job_buffer.waiting_count == workers.count sleep 0.001 end # If we weren't passed a specific connection_url, borrow a connection from # the pool and derive the connection string from it. connection_args = if connection_url uri = URI.parse(connection_url) opts = { host: uri.host, user: uri.user, password: <PASSWORD>, port: uri.port || 5432, dbname: uri.path[1..-1], } if uri.query opts.merge!(Hash[uri.query.split("&").map{|s| s.split('=')}.map{|a,b| [a.to_sym, b]}]) end opts else Que.pool.checkout do |conn| c = conn.wrapped_connection { host: c.host, user: c.user, password: <PASSWORD>, port: c.port, dbname: c.db, } end end @connection = Que::Connection.wrap(PG::Connection.open(connection_args)) @thread = Thread.new do # An error causing this thread to exit is a bug in Que, which we want # to know about ASAP, so propagate the error if it happens. Thread.current.abort_on_exception = true # Give this thread priority, so it can promptly respond to NOTIFYs. Thread.current.priority = 1 begin unless connection_args.has_key?(:application_name) @connection.execute( "SELECT set_config('application_name', $1, false)", ["Que Locker: #{@connection.backend_pid}"] ) end Poller.setup(@connection) @listener = if listen Listener.new(connection: @connection) end @pollers = if poll queues.map do |queue, interval| Poller.new( connection: @connection, queue: queue, poll_interval: interval || poll_interval, ) end end work_loop ensure @connection.wrapped_connection.close end end end def stop! stop; wait_for_stop end def stop @job_buffer.stop @stop = true end def stopping? @stop end def wait_for_stop @thread.join end private attr_reader :connection, :pollers def work_loop Que.log( level: :debug, event: :locker_start, queues: @queue_names, ) Que.internal_log :locker_start, self do { backend_pid: connection.backend_pid, worker_priorities: workers.map(&:priority), pollers: pollers && pollers.map { |p| [p.queue, p.poll_interval] } } end begin @listener.listen if @listener startup {} while cycle Que.log( level: :debug, event: :locker_stop, ) shutdown ensure connection.execute :clean_lockers @listener.unlisten if @listener end end def startup # A previous locker that didn't exit cleanly may have left behind # a bad locker record, so clean up before registering. connection.execute :clean_lockers connection.execute :register_locker, [ @workers.count, "{#{@workers.map(&:priority).map{|p| p || 'NULL'}.join(',')}}", Process.pid, CURRENT_HOSTNAME, !!@listener, "{\"#{@queue_names.join('","')}\"}", ] end def cycle # Poll at the start of a cycle, so that when the worker starts up we can # load up the queue with jobs immediately. poll # If we got the stop call while we were polling, break before going to # sleep. return if @stop # The main sleeping part of the cycle. If this is a listening locker, this # is where we wait for notifications. wait # Manage any job output we got while we were sleeping. handle_results # If we haven't gotten the stop signal, cycle again. !@stop end def shutdown unlock_jobs(@job_buffer.clear) wait_for_shutdown handle_results end def wait_for_shutdown @workers.each(&:wait_until_stopped) end def poll # Only poll when there are pollers to use (that is, when polling is # enabled) and when the local queue has dropped below the configured # minimum size. return unless pollers && job_buffer.jobs_needed? # Figure out what job priorities we have to fill. priorities = job_buffer.available_priorities all_metajobs = [] pollers.each do |poller| Que.internal_log(:locker_polling, self) { { priorities: priorities, held_locks: @locks.to_a, queue: poller.queue, } } if metajobs = poller.poll(priorities: priorities, held_locks: @locks) metajobs.sort! all_metajobs.concat(metajobs) # Update the desired priorities list to take the priorities that we # just retrieved into account. metajobs.each do |metajob| job_priority = metajob.job.fetch(:priority) priorities.each do |priority, count| if job_priority <= priority new_priority = count - 1 if new_priority <= 0 priorities.delete(priority) else priorities[priority] = new_priority end break end end end break if priorities.empty? end end all_metajobs.each { |metajob| mark_id_as_locked(metajob.id) } push_jobs(all_metajobs) end def wait if l = @listener l.wait_for_grouped_messages(@wait_period).each do |type, messages| if resolver = MESSAGE_RESOLVERS[type] instance_exec messages, &resolver else raise Error, "Unexpected message type: #{type.inspect}" end end else sleep(@wait_period) end end def handle_results messages_by_type = @result_queue.clear.group_by{|r| r.fetch(:message_type)} messages_by_type.each do |type, messages| if resolver = RESULT_RESOLVERS[type] instance_exec messages, &resolver else raise Error, "Unexpected result type: #{type.inspect}" end end end def lock_jobs(metajobs) metajobs.reject! { |m| @locks.include?(m.id) } return metajobs if metajobs.empty? ids = metajobs.map { |m| m.id.to_i } Que.internal_log :locker_locking, self do { backend_pid: connection.backend_pid, ids: ids, } end jobs = connection.execute \ <<-SQL WITH jobs AS (SELECT * FROM que_jobs WHERE id IN (#{ids.join(', ')})) SELECT * FROM jobs WHERE pg_try_advisory_lock(id) SQL jobs_by_id = {} jobs.each do |job| id = job.fetch(:id) mark_id_as_locked(id) jobs_by_id[id] = job end metajobs.keep_if do |metajob| if job = jobs_by_id[metajob.id] metajob.set_job(job) true else false end end end def push_jobs(metajobs) return if metajobs.empty? # First check that the jobs are all still visible/available in the DB. ids = metajobs.map(&:id) verified_ids = connection.execute( <<-SQL SELECT id FROM public.que_jobs WHERE finished_at IS NULL AND expired_at IS NULL AND id IN (#{ids.join(', ')}) SQL ).map{|h| h[:id]}.to_set good, bad = metajobs.partition{|mj| verified_ids.include?(mj.id)} # Need to unlock any low-importance jobs the new ones may displace. if displaced = @job_buffer.push(*good) bad.concat(displaced) end unlock_jobs(bad) end def finish_jobs(metajobs) unlock_jobs(metajobs) end def unlock_jobs(metajobs) return if metajobs.empty? # Unclear how untrusted input would get passed to this method, but since # we need string interpolation here, make sure we only have integers. ids = metajobs.map { |job| job.id.to_i } Que.internal_log :locker_unlocking, self do { backend_pid: connection.backend_pid, ids: ids, } end values = ids.join('), (') results = connection.execute \ "SELECT pg_advisory_unlock(v.i) FROM (VALUES (#{values})) v (i)" results.each do |result| Que.assert(result.fetch(:pg_advisory_unlock)) do [ "Tried to unlock a job we hadn't locked!", results.inspect, ids.inspect, ].join(' ') end end ids.each do |id| Que.assert(@locks.delete?(id)) do "Tried to remove a local lock that didn't exist!: #{id}" end end end def mark_id_as_locked(id) Que.assert(@locks.add?(id)) do "Tried to lock a job that was already locked: #{id}" end end end end
radamanthus/MovieEffects
app/helpers/effects/progress_helper.rb
module Effects::ProgressHelper end
radamanthus/MovieEffects
app/controllers/effects/base_controller.rb
<reponame>radamanthus/MovieEffects class Effects::BaseController < ApplicationController include ActionView::Helpers::SanitizeHelper helper_method :bgcolor def create saved_config = SavedConfiguration.new({ session_id: request.session.id, effect: effect_name, configuration: configuration_from_params_and_defaults }) saved_config.save! redirect_to edit_path(saved_config) end def edit saved = SavedConfiguration.find_by slug:params[:id] config = ActiveSupport::HashWithIndifferentAccess.new(saved.configuration) permalink = "#{request.protocol}#{Settings.hostname}/effects/#{route}/#{saved.slug}" edit_url = "#{permalink}/edit" render locals:{ id: saved.id, permalink: permalink, edit_url: edit_url, config: config } end def new saved = SavedConfiguration.new(configuration: default_config) config = ActiveSupport::HashWithIndifferentAccess.new(saved.configuration) render locals:{config: config} end def show saved = SavedConfiguration.find_by slug:params[:id] config = ActiveSupport::HashWithIndifferentAccess.new(saved.configuration) render layout: 'effects', locals: { config: config } end def update saved_config = SavedConfiguration.find(params[:id]) saved_config.configuration = configuration_from_params_and_defaults saved_config.save! redirect_to show_path(saved_config) end private def edit_path(saved_config) self.public_send("edit_effects_#{route}_path", {id: saved_config.slug}) end def show_path(saved_config) self.public_send("effects_#{route}_path", {id: saved_config.slug}) end end
radamanthus/MovieEffects
app/controllers/effects/processing_controller.rb
class Effects::ProcessingController < Effects::BaseController helper_method :bgcolor private def bgcolor '#1b1c1d' end def configuration_from_params_and_defaults { processing_text: sanitize(params[:processing_text]) || default_config[:processing_text], progress_bar_color: sanitize(params[:progress_bar_color]) || default_config[:progress_bar_color], start_position: sanitize(params[:start_position]).to_i || default_config[:start_position], start_button_label: sanitize(params[:start_button_label]) || default_config[:start_button_label], start_text: sanitize(params[:start_text]) || default_config[:start_text], step_delay: sanitize(params[:step_delay]).to_i || default_config[:step_delay], step_increment: sanitize(params[:step_increment]).to_i || default_config[:step_increment] } end def default_config { start_position: 0, start_button_label: 'Proceed', start_text: 'Are you sure you want to download the virus?', step_delay: 1000, step_increment: 1, processing_text: 'Downloading Virus...', progress_bar_color: 'blue' } end def effect_name 'processing' end def route 'processing' end def session_saved_config SavedConfiguration.find_by(session_id: request.session.id) end end
radamanthus/MovieEffects
app/controllers/effects/access_controller.rb
<gh_stars>1-10 class Effects::AccessController < Effects::BaseController helper_method :bgcolor private def bgcolor '#ffffff' end def configuration_from_params_and_defaults { header_text: sanitize(params[:header_text]), mode: sanitize(params[:mode]), username_label: sanitize(params[:username_label]) || default_config[:username_label], password_label: sanitize(params[:password_label]) || default_config[:password_label], username_placeholder: sanitize(params[:username_placeholder]) || default_config[:username_placeholder], login_button_label: sanitize(params[:login_button_label]) || default_config[:login_button_label], access_denied_text: sanitize(params[:access_denied_text]) || default_config[:access_denied_text], access_granted_text: sanitize(params[:access_granted_text]) || default_config[:access_granted_text], correct_password: sanitize(params[:correct_password]) || default_config[:correct_password], max_retries: params[:max_retries].to_i || default_config[:max_retries], redirect_delay: params[:redirect_delay].to_i || default_config[:redirect_delay], success_redirect_url: params[:success_redirect_url] || default_config[:success_redirect_url], failure_redirect_url: params[:failure_redirect_url] || default_config[:failure_redirect_url] } end def default_config { username_label: 'Username', password_label: 'Password', username_placeholder: 'Type your username here', login_button_label: 'Login', access_denied_text: 'Access Denied', access_granted_text: 'Access Granted', correct_password: '<PASSWORD>', max_retries: 3, redirect_delay: 0 } end def effect_name 'access' end def route 'access' end def session_saved_config SavedConfiguration.find_by(session_id: request.session.id) end end
radamanthus/MovieEffects
spec/models/saved_configuration_spec.rb
# frozen_string_literal: true require 'rails_helper' describe SavedConfiguration do it "generates a slug on save" do saved_config = SavedConfiguration.new(effect: 'processing') saved_config.save expect(saved_config.slug).not_to be_nil end end
radamanthus/MovieEffects
config/routes.rb
Rails.application.routes.draw do root 'home#index' namespace :effects do resources :processing resources :access end end
radamanthus/MovieEffects
app/services/slug_generator.rb
<filename>app/services/slug_generator.rb # frozen_string_literal: true class SlugGenerator HASHID_ALPHABET = ('a'..'z').to_a.join + ('0'..'9').to_a.join attr_reader :slug def initialize(id) hashid = Hashids.new(Settings.hash_id_salt, 5, HASHID_ALPHABET) @slug = hashid.encode(id) end end
radamanthus/MovieEffects
db/migrate/20190727042057_create_saved_configurations.rb
<filename>db/migrate/20190727042057_create_saved_configurations.rb class CreateSavedConfigurations < ActiveRecord::Migration[5.2] def change create_table :saved_configurations do |t| t.string :effect, null: false t.string :slug t.string :hashed_password t.string :session_id, null: false t.jsonb :configuration, null: false, default: '{}' t.timestamps end add_index :saved_configurations, :slug end end
radamanthus/MovieEffects
app/models/saved_configuration.rb
# frozen_string_literal: true class SavedConfiguration < ApplicationRecord after_create :generate_slug private def generate_slug self.slug = SlugGenerator.new(id).slug self.save end end
ugogon/Autolab
app/models/risk_condition.rb
class RiskCondition < ApplicationRecord serialize :parameters, Hash enum condition_type: { no_condition_selected: 0, grace_day_usage: 1, grade_drop: 2, no_submissions: 3, low_grades: 4 } has_many :watchlist_instances, dependent: :destroy belongs_to :course # parameter correspondence: # :grace_day_usage => :grace_day_threshold, :date # :grade_drop => :percentage_drop, :consecutive_counts # :no_submissions => :no_submissions_threshold # :low_grades => :grade_threshold, :count_threshold def self.create_condition_for_course_with_type(course_id, type, params, version) # parameter check shouldn't surface to user and is for sanity check during development only if (type == 1 && (params[:grace_day_threshold].nil? || params[:date].nil? || params.length != 2)) || (type == 2 && (params[:percentage_drop].nil? || params[:consecutive_counts].nil? || params.length != 2)) || (type == 3 && (params[:no_submissions_threshold].nil? || params.length != 1)) || (type == 4 && (params[:grade_threshold].nil? || params[:count_threshold].nil? || params.length != 2)) raise "Invalid update parameters for risk conditions! Make sure your request body fits the criteria!" end options = { course_id: course_id, condition_type: type, parameters: params, version: version } new_risk_condition = RiskCondition.new(options) unless new_risk_condition.save raise "Fail to create new risk condition with type #{type} for course #{course_id}" end new_risk_condition end def self.get_current_for_course(course_name) conditions = [] course_id = Course.find_by(name: course_name).id max_version = RiskCondition.get_max_version(course_id) return [] if max_version == 0 conditions_for_course = RiskCondition.where(course_id: course_id, version: max_version) condition_types = conditions_for_course.map { |condition| condition.condition_type.to_sym } if condition_types.any? { |type| type == :no_condition_selected } [] else conditions_for_course end end def self.update_current_for_course(course_name, params) # The code below assumes params[type] contains a hash of the parameters needed for the type # where type is a string corresponding to the four types defined at the top of this file course_id = Course.find_by(name: course_name).id max_version = RiskCondition.get_max_version(course_id) # Is params empty? if params.length == 0 and max_version == 0 # puts "case 1: max_version = 0 (no previous conditons have been set) and instructor doesn't want any at this point" WatchlistInstance.refresh_instances_for_course(course_name, true) return [] end previous_conditions = RiskCondition.where(course_id: course_id, version: max_version) previous_types = previous_conditions.map { |c| c.condition_type } if params.length == 0 if previous_types.length > 0 and !previous_types.any? { |t| t == "no_condition_selected" } # puts "case 2: previous conditions set to something and instructor doesn't want any this time" ActiveRecord::Base.transaction do create_condition_for_course_with_type(course_id, 0, {}, max_version + 1) end # else # puts "case 3: previous conditions set to nothing selected and instructor doesn't want any this time either" end # indicator row for "currently no conditions selected" that user doesn't need to access WatchlistInstance.refresh_instances_for_course(course_name, true) [] else conditions = [] no_change = true if params.length == previous_types.length previous_conditions.map do |c| unless params[c.condition_type] == c.parameters no_change = false break end end else no_change = false end unless no_change # puts "case 4: instructor changed conditions this time; previous conditions were either unset, or different from current parameters" ActiveRecord::Base.transaction do params.map do |k, v| new_condition = create_condition_for_course_with_type(course_id, condition_types[k], v, max_version + 1) conditions << new_condition end end # else # puts "case 5: previous conditions and current conditions match and no update is needed" end WatchlistInstance.refresh_instances_for_course(course_name, true) conditions end end def self.get_grade_drop_condition_for_course(course_name) current_conditions = get_current_for_course(course_name) return nil if current_conditions.count == 0 # Check for whether there exists one of type :grade_drop grade_drop_condition = current_conditions.select { |c| c.condition_type.to_sym == :grade_drop } return nil if grade_drop_condition.count != 1 grade_drop_condition = grade_drop_condition[0] [grade_drop_condition.id, grade_drop_condition.parameters[:percentage_drop].to_f, grade_drop_condition.parameters[:consecutive_counts].to_i] end def self.get_low_grades_condition_for_course(course_name) current_conditions = get_current_for_course(course_name) return nil if current_conditions.count == 0 # Check for whether there exists one of type :low_grades low_grades_condition = current_conditions.select { |c| c.condition_type.to_sym == :low_grades } return nil if low_grades_condition.count != 1 low_grades_condition = low_grades_condition[0] [low_grades_condition.id, low_grades_condition.parameters[:grade_threshold].to_f, low_grades_condition.parameters[:count_threshold].to_i] end # return nil if course doesn't have any current gdu condition # return condition_id, grace_day_threshold, date otherwise def self.get_gdu_condition_for_course(course_name) current_conditions = get_current_for_course(course_name) return nil if current_conditions.count == 0 # Check for whether there exists one of type :grace_day_usage grace_day_usage_condition = current_conditions.select do |c| c.condition_type.to_sym == :grace_day_usage end return nil if grace_day_usage_condition.count != 1 grace_day_usage_condition = grace_day_usage_condition[0] [grace_day_usage_condition.id, grace_day_usage_condition.parameters[:grace_day_threshold].to_i, grace_day_usage_condition.parameters[:date]] end def self.get_no_submissions_condition_for_course(course_name) current_conditions = get_current_for_course(course_name) return nil if current_conditions.count == 0 # Check for whether there exists one of type :no_submissions no_submissions_condition = current_conditions.select do |c| c.condition_type.to_sym == :no_submissions end return nil if no_submissions_condition.count != 1 no_submissions_condition = no_submissions_condition[0] [no_submissions_condition.id, no_submissions_condition.parameters[:no_submissions_threshold].to_i] end def self.get_max_version(course_id) conditions = [] conditions_for_course = RiskCondition.where(course_id: course_id) versions = conditions_for_course.map { |each| each.version } max_version = versions.max if max_version.nil? 0 else max_version end end end
iancanderson/tenderjit
test/instructions/opt_aref_test.rb
<gh_stars>0 # frozen_string_literal: true require "helper" class TenderJIT class OptArefTest < JITTest def aref obj, key obj[key] end def test_has_opt_aref assert_has_insn method(:aref), insn: :opt_aref end def test_opt_aref jit.compile method(:aref) jit.enable! v = aref([1, 2, 3], 2) jit.disable! assert_equal 3, v assert_equal 1, jit.compiled_methods assert_equal 1, jit.executed_methods assert_equal 0, jit.exits end def test_opt_aref_twice jit.compile method(:aref) jit.enable! aref([1, 2, 3], 2) v = aref([1, 2, 3], 2) jit.disable! assert_equal 3, v assert_equal 1, jit.compiled_methods assert_equal 2, jit.executed_methods assert_equal 0, jit.exits end def test_opt_aref_hash jit.compile method(:aref) jit.enable! v = aref({ 2 => :hello }, 2) jit.disable! assert_equal :hello, v assert_equal 1, jit.compiled_methods assert_equal 1, jit.executed_methods assert_equal 0, jit.exits end def test_hash_then_array jit.compile method(:aref) jit.enable! v1 = aref({ 2 => :hello }, 2) v2 = aref([1, 2, 3], 2) jit.disable! assert_equal :hello, v1 assert_equal 3, v2 assert_equal 1, jit.compiled_methods assert_equal 2, jit.executed_methods assert_equal 0, jit.exits end def test_hash_then_array_twice jit.compile method(:aref) jit.enable! aref({ 2 => :hello }, 2) aref([1, 2, 3], 2) v1 = aref({ 2 => :hello }, 2) v2 = aref([1, 2, 3], 2) jit.disable! assert_equal :hello, v1 assert_equal 3, v2 assert_equal 1, jit.compiled_methods assert_equal 4, jit.executed_methods assert_equal 0, jit.exits end def test_opt_aref_does_not_crash @peeks = {} jit.compile method(:add_mappings) jit.enable! add_mappings(Object.new) add_mappings(Object.new) add_mappings(Object.new) jit.enable! end def numeric_aref a, b a[b] end def test_opt_aref_numeric expected = numeric_aref(1, 0) jit.compile method(:numeric_aref) jit.enable! numeric_aref(1, 0) v = numeric_aref(1, 0) jit.disable! assert_equal expected, v assert_equal 1, jit.compiled_methods assert_equal 2, jit.executed_methods assert_equal 0, jit.exits end private def add_mappings(peek) # filter the logically equivalent objects @peeks[peek] ||= peek end end end
iancanderson/tenderjit
test/instructions/setlocal_WC_1_test.rb
<reponame>iancanderson/tenderjit # frozen_string_literal: true require "helper" class TenderJIT class SetlocalWc1Test < JITTest def test_setlocal_WC_1 skip "setlocal_WC_1 has been implemented. Please add a test." end end end
iancanderson/tenderjit
test/runtime_test.rb
# frozen_string_literal: true require "helper" class TenderJIT class RuntimeTest < Test attr_reader :rt def setup super fisk = Fisk.new buffer = StringIO.new temp_stack = TempStack.new @rt = Runtime::new(fisk, buffer, temp_stack) end # Smoke test. # def test_if_eq_imm_imm64 @rt.if_eq(2 << 0, 2 << 32) end # Smoke test. # def test_if_eq_imm_immnot64 @rt.if_eq(2 << 0, 2 << 0) end # See https://github.com/tenderlove/tenderjit/issues/35#issuecomment-934872857 # # > The code in main is emitting an extra mov instruction because the lhs is # > an immediate when we could have put the lhs in the rhs and directly used # > the CMP instruction. # # When tackling, update all the invocations, then turn the swap into an # assertion. # def test_if_eq_imm_not_imm skip "Optimize the if_eq invocations" end def test_inc @rt.inc Fisk::Registers::RAX buffer = @rt.write! assert_equal buffer.string, "H\xFF\xC0" end end # class RuntimeTest end
iancanderson/tenderjit
test/make_warnings_errors.rb
<reponame>iancanderson/tenderjit # Make errors into warnings (gcc's -W) # This is somewhat odd, but it's been officially accepted for this purpose (see https://bugs.ruby-lang.org/issues/3916). # module Warning def warn msg raise msg end end
iancanderson/tenderjit
test/temp_stack_test.rb
# frozen_string_literal: true require "helper" class TempStackTest < TenderJIT::Test def test_push_then_read_with_square stack = TenderJIT::TempStack.new stack.push("name") assert_equal 0, stack[0].displacement end def test_negative_numbers_raise_index_error_with_square stack = TenderJIT::TempStack.new assert_raises IndexError do stack[1] end end def test_negative_index_raise_index_error_with_peek stack = TenderJIT::TempStack.new assert_raises IndexError do stack.peek(1) end end def test_push_then_read_with_peek stack = TenderJIT::TempStack.new stack.push("name") assert_equal "name", stack.peek(0).name end end
iancanderson/tenderjit
test/instructions/topn_test.rb
<filename>test/instructions/topn_test.rb<gh_stars>0 # frozen_string_literal: true require "helper" class TenderJIT class TopnTest < JITTest # Disassembly (as of 3.0.2): # # local table (size: 1, argc: 0 [opts: 0, rest: -1, post: 0, block: -1, kw: -1@-1, kwrest: -1]) # [ 1] arr@0 # 0000 duparray [:foo, :bar, :baz] ( 2)[Li] # 0002 setlocal_WC_0 arr@0 # 0004 duparray [:qux, :sav] ( 3)[Li] # 0006 expandarray 1, 0 # 0009 getlocal_WC_0 arr@0 # 0011 putobject_INT2FIX_1_ # 0012 topn 2 # 0014 opt_aset <calldata!mid:[]=, argc:2, ARGS_SIMPLE> # 0016 pop # 0017 pop # 0018 getlocal_WC_0 arr@0 ( 7)[Li] # 0020 leave # # Note the empty prefix string added. # def topn arr = [:foo, :bar, :baz] arr[1], = [:qux, :sav] # not necessary for the instruction to be genrated, but necesary for testing, # since the array assignment returns the rhs value. # arr end def test_topn meth = method(:topn) assert_has_insn meth, insn: :topn jit.compile(meth) jit.enable! v = meth.call jit.disable! assert_equal 1, jit.compiled_methods assert_equal 1, jit.exits assert_equal [:foo, :qux, :baz], v end end end
iancanderson/tenderjit
lib/tenderjit/runtime.rb
<gh_stars>0 class TenderJIT class Runtime def initialize fisk, jit_buffer, temp_stack @fisk = fisk @labels = [] @label_count = 0 @jit_buffer = jit_buffer @temp_stack = temp_stack yield self if block_given? end def flush_pc_and_sp pc, sp cfp_ptr = pointer REG_CFP, type: RbControlFrameStruct cfp_ptr.pc = pc with_ref(sp) do |reg| cfp_ptr.sp = reg end end def load_address_in dest, src if src.memory? offset = src.displacement reg = src.register else raise NotImplementedError end @fisk.lea(dest, @fisk.m(reg, offset)) end def check_vm_stack_overflow temp_stack, exit_location, local_size, stack_max margin = ((local_size + stack_max) * Fiddle::SIZEOF_VOIDP) + RbControlFrameStruct.byte_size loc = temp_stack.first.loc + (margin / Fiddle::SIZEOF_VOIDP) with_ref(loc) do |reg| self.if(reg, :>, REG_CFP) { # do nothing }.else { jump(exit_location) } end end # Converts the Ruby Number stored in +val+ to an int def NUM2INT val @fisk.sar(cast_to_fisk(val), @fisk.lit(1)) end # Converts the Ruby Number stored in +val+ to an int def FIX2LONG val @fisk.sar(cast_to_fisk(val), @fisk.lit(1)) end # Converts an int to a Ruby Number def INT2NUM val @fisk.shl(cast_to_fisk(val), @fisk.lit(1)) @fisk.inc(cast_to_fisk(val)) end def return_value @fisk.rax end def return_value= v @fisk.mov @fisk.rax, v end def patchable_jump dest @fisk.lea(return_value, @fisk.rip) jump dest end def patchable_call dest @fisk.call(@fisk.absolute(dest)) end def call dest @fisk.call(dest) end # Get the register for the i'th parameter in the C calling convention def c_param i Fisk::Registers::CALLER_SAVED.fetch i end # Set the register for the i'th parameter in the C calling convention def set_c_param i, v @fisk.mov Fisk::Registers::CALLER_SAVED.fetch(i), v end def rb_funcall recv, method_name, params @fisk.push REG_BP.to_register # alignment rb_funcall_without_alignment recv, method_name, params @fisk.pop REG_BP.to_register # alignment end def rb_funcall_without_alignment recv, method_name, params raise "Too many parameters!" if params.length > 3 func_addr = Internals.symbol_address "rb_funcall" @fisk.mov(Fisk::Registers::CALLER_SAVED[0], @fisk.uimm(Fiddle.dlwrap(recv))) @fisk.mov(Fisk::Registers::CALLER_SAVED[1], @fisk.uimm(CFuncs.rb_intern(method_name.to_s))) @fisk.mov(Fisk::Registers::CALLER_SAVED[2], @fisk.uimm(params.length)) params.each_with_index do |param, i| i += 3 if param.is_a?(Fisk::Operand) || param.is_a?(TemporaryVariable) param = param.to_register if param.is_a?(TemporaryVariable) @fisk.mov(Fisk::Registers::CALLER_SAVED[i], param) #if param.memory? @fisk.shl(Fisk::Registers::CALLER_SAVED[i], @fisk.uimm(1)) @fisk.inc(Fisk::Registers::CALLER_SAVED[i]) #end else @fisk.mov(Fisk::Registers::CALLER_SAVED[i], @fisk.uimm(Fiddle.dlwrap(param))) end end @fisk.mov(@fisk.rax, @fisk.uimm(func_addr)) .call(@fisk.rax) end def jump location case location when TemporaryVariable @fisk.jmp location.reg when Fisk::Operand @fisk.jmp location else @fisk.jmp @fisk.absolute(location) end end def and reg, num @fisk.and(reg, cast_to_fisk(num)) end def or reg, num @fisk.or(reg, cast_to_fisk(num)) end def flush write! @fisk = Fisk.new end # Writes to the buffer, and freezes the instance. # Returns the buffer, for convenience. # def write! @fisk.assign_registers(TenderJIT::ISEQCompiler::SCRATCH_REGISTERS, local: true) @fisk.write_to(@jit_buffer) @fisk.freeze @jit_buffer end def pointer reg, type: Fiddle::TYPE_VOIDP, offset: 0 Pointer.new reg.to_register, type, find_size(type), offset, self end def sub reg, val @fisk.sub reg, cast_to_fisk(val) end def add reg, val @fisk.add reg.to_register, cast_to_fisk(val) end def inc reg @fisk.inc reg end def mult val1, val2 raise NotImplementedError unless val1.memory? raise NotImplementedError unless val2.memory? # Put val in to RAX # mult should end up in r9, but is in rax @fisk.mov @fisk.rax, cast_to_fisk(val1) temp_var do |temp_1| @fisk.mov cast_to_fisk(temp_1), cast_to_fisk(val2) self.NUM2INT(temp_1) self.NUM2INT(@fisk.rax) # val1 should be in the rax register # and val2 should be in temp_1 # Mulitply reg by the value in RAX @fisk.mul cast_to_fisk(temp_1) end self.INT2NUM(@fisk.rax) @fisk.rax end # Performs a 64-bit division. # Returns RAX, with the result. # def div dividend_val, divisor_val perform_division dividend_val, divisor_val, @fisk.rax end # Performs a 64-bit modulo. # Returns RDX, with the result. # def mod dividend_val, divisor_val perform_division dividend_val, divisor_val, @fisk.rdx end # Performs a division (used by div/mod). # # Returns the register passed. # # params: # - :register: The register returned; must be RAX (for div) or RDX (for mod). # # Reference: https://www.cs.uaf.edu/2006/fall/cs301/support/x86_64. # def perform_division dividend_val, divisor_val, register raise NotImplementedError unless dividend_val.memory? raise NotImplementedError unless divisor_val.memory? @fisk.mov @fisk.rdx, cast_to_fisk(0) # x64 quirk; see reference @fisk.mov @fisk.rax, cast_to_fisk(dividend_val) temp_var do |divisor| @fisk.mov cast_to_fisk(divisor), cast_to_fisk(divisor_val) self.NUM2INT(@fisk.rax) self.NUM2INT(divisor) @fisk.div cast_to_fisk(divisor) end self.INT2NUM register register end private :perform_division def write_memory reg, offset, val @fisk.with_register do |tmp| @fisk.mov(tmp, val) @fisk.mov(@fisk.m64(reg, offset), tmp) end end def write_register reg, offset, val @fisk.mov(@fisk.m64(reg, offset), val) end def write_immediate reg, offset, val @fisk.with_register do |tmp| @fisk.mov(tmp, @fisk.uimm(val)) @fisk.mov(@fisk.m64(reg, offset), tmp) end end def write_immediate_to_reg reg, val @fisk.mov(reg, @fisk.uimm(val)) end def read_to_reg src, offset @fisk.with_register do |tmp| @fisk.mov(tmp, @fisk.m64(src, offset)) yield tmp end end def with_ref reg, offset = 0 if reg.memory? offset = reg.displacement reg = reg.register end @fisk.with_register do |tmp| @fisk.lea(tmp, @fisk.m(reg, offset)) yield tmp end end def write_to_mem dst, offset, src @fisk.mov(@fisk.m64(dst, offset), src) end def write dst, src dst = cast_to_fisk dst src = cast_to_fisk src if dst.memory? && (src.memory? || src.immediate?) @fisk.with_register do |tmp| @fisk.mov(tmp, src) @fisk.mov(dst, tmp) end else @fisk.mov(dst, src) end end def break @fisk.int(@fisk.lit(3)) end # Shift op1 right by op2 def shr op1, op2 @fisk.shr cast_to_fisk(op1), cast_to_fisk(op2) end # Shift op1 left by op2 def shl op1, op2 @fisk.shl cast_to_fisk(op1), cast_to_fisk(op2) end def test_flags obj, flags lhs = cast_to_fisk obj rhs = cast_to_fisk flags @fisk.test lhs, rhs @fisk.jz push_label # else label finish_label = push_label yield if block_given? @fisk.jmp finish_label # finish label self end UINTPTR_MAX = 0xFFFFFFFFFFFFFFFF # on macos anyway RBIMPL_VALUE_FULL = UINTPTR_MAX class Conditional # :nodoc: def initialize lhs, jmp @lhs = lhs @jmp = jmp end def call fisk; @lhs.call(fisk); end def jump fisk, label; @jmp.call(fisk, label); end end def RB_STATIC_SYM_P sym_loc mask = 0xFF lhs = ->(fisk) { temp_var { |tv| tv.write sym_loc tv.and mask fisk.xor tv.to_register, fisk.imm(RUBY_SYMBOL_FLAG) } } jmp = ->(fisk, label) { fisk.jnz(label) } Conditional.new(lhs, jmp) end # Test if a flag has been set on the ep. def VM_ENV_FLAG_SET_P ep_loc, flag ->(fisk) { temp_var { |tv| ep = pointer(ep_loc) tv.write ep[VM_ENV_DATA_INDEX_FLAGS] tv.and(flag) fisk.test(tv.to_register, tv.to_register) } } end # Set the flag +flag+ on the ep def VM_ENV_FLAGS_SET ep_loc, flag temp_var { |tv| ep = pointer(ep_loc) tv.write ep[VM_ENV_DATA_INDEX_FLAGS] tv.or(flag) ep[VM_ENV_DATA_INDEX_FLAGS] = tv.to_register } end def RB_FIXNUM_P obj ->(fisk) { fisk.test(obj, fisk.uimm(RUBY_FIXNUM_FLAG)) } end alias :fixnum? :RB_FIXNUM_P def if lhs, op = nil, rhs = nil else_label = push_label # else label finish_label = push_label if op && rhs lhs = cast_to_fisk lhs rhs = cast_to_fisk rhs maybe_reg lhs do |op1| maybe_reg rhs, only_64: true do |op2| @fisk.cmp op1, op2 end end @fisk.jg else_label # else label else if lhs.respond_to?(:call) lhs.call(@fisk) else @fisk.test lhs, lhs end if lhs.respond_to?(:jump) lhs.jump @fisk, else_label # else label else @fisk.jz else_label # else label end end yield if block_given? @fisk.jmp finish_label # finish label self end def if_eq lhs, rhs lhs = cast_to_fisk lhs rhs = cast_to_fisk rhs # The swap could be avoided in the lhs:imm64 sub-case, but keep it simple for now, # as it may be entirely removed in the future. # lhs, rhs = rhs, lhs if lhs.immediate? && !rhs.immediate? maybe_reg lhs do |op1| maybe_reg rhs, only_64: true do |op2| @fisk.cmp op1, op2 end end @fisk.jne push_label # else label finish_label = push_label yield if block_given? @fisk.jmp finish_label # finish label self end def else finish_label = pop_label else_label = pop_label @fisk.put_label else_label yield @fisk.put_label finish_label end def endif finish_label = pop_label else_label = pop_label @fisk.put_label else_label @fisk.put_label finish_label end # Dereference an operand in to a temp register and yield the register # # Basically just: # `mov(tmp_reg, operand)` # def dereference operand @fisk.with_register do |tmp| @fisk.mov(tmp, operand) yield tmp end end # Checks if the object at +loc+ is a special const. RAX is 0 if this is # *not* a special constant. def RB_SPECIAL_CONST_P loc is_immediate = push_label __ = @fisk reg = @fisk.rax @fisk.mov(reg, loc) @fisk.test(reg, reg) # Is the parameter Qfalse? @fisk.cmovz(reg, @fisk.rsi) # If so, set the register to $rsi (it's non-zero) @fisk.jz(is_immediate) # cmov didn't clear ZF, so we can jump if it's 0 @fisk.test(reg, __.uimm(RUBY_IMMEDIATE_MASK)) @fisk.jnz(is_immediate) @fisk.test(reg, __.imm(~Qnil)) @fisk.jz(is_immediate) @fisk.mov(reg, __.uimm(0)) @fisk.put_label(is_immediate.name) pop_label reg end # Finds the built-in type of the object stored in `loc`. The type is # placed in RAX def RB_BUILTIN_TYPE loc reg = @fisk.rax @fisk.mov(reg, loc) @fisk.mov(reg, @fisk.m64(reg, RBasic.offsetof("flags"))) @fisk.and(reg, @fisk.uimm(RUBY_T_MASK)) reg end # Create a temporary variable def temp_var name = "temp_var" tv = TemporaryVariable.new @fisk.register(name), Fiddle::TYPE_VOIDP, Fiddle::SIZEOF_VOIDP, 0, self if block_given? yield tv tv.release! else tv end end # Push a register on the machine stack def push_reg reg @fisk.push reg.to_register end # Pop a register on the machine stack def pop_reg reg @fisk.pop reg.to_register end def return @fisk.ret end # Push a value on the stack def push val, name:, type: :unknown loc = @temp_stack.push name, type: type val = cast_to_fisk val if val.memory? || val.immediate? write loc, val else write loc, val.to_register end end def vm_get_ep ep_loc, level reg = ep_loc.to_register level.times do @fisk.mov(reg, @fisk.m64(reg, VM_ENV_DATA_INDEX_SPECVAL * Fiddle::SIZEOF_VOIDP)) @fisk.and(reg, @fisk.imm(~0x03)) end end def call_cfunc func_loc, params @fisk.push REG_BP.to_register # alignment call_cfunc_without_alignment func_loc, params @fisk.pop REG_BP.to_register # alignment @fisk.rax end def call_cfunc_without_alignment func_loc, params raise NotImplementedError, "too many parameters" if params.length > 6 raise "No function location" unless func_loc > 0 params.each_with_index do |param, i| case param when Integer @fisk.mov(Fisk::Registers::CALLER_SAVED[i], @fisk.uimm(param)) when Fisk::Operand @fisk.mov(Fisk::Registers::CALLER_SAVED[i], param) when TemporaryVariable @fisk.mov(Fisk::Registers::CALLER_SAVED[i], param.to_register) when Proc param.call Fisk::Registers::CALLER_SAVED[i] else raise NotImplementedError end end @fisk.mov(@fisk.rax, @fisk.uimm(func_loc)) .call(@fisk.rax) @fisk.rax end def release_temp temp @fisk.release_register temp.reg end private def push_label n = "label" @label_count += 1 label = "#{n} #{@label_count}" @labels.push label @fisk.label label end def pop_label @labels.pop end # If the operator is immediate, move to a register, otherwise, leave as is. # This is useful for instructions that don't support immediate for the given # operator, e.g. CMP $immediate, $other_op. # # params # - :only_64: move to register only if the immediate is 64 bits # def maybe_reg op, only_64: false if op.immediate? && (op.size == 64 || !only_64) @fisk.with_register do |tmp| @fisk.mov(tmp, op) yield tmp end else yield op end end def cast_to_fisk val case val when Fisk::Operand val when TemporaryVariable val.to_register else @fisk.imm(val) end end def find_size type type == Fiddle::TYPE_VOIDP ? Fiddle::SIZEOF_VOIDP : type.byte_size end class Array attr_reader :reg, :type, :size def initialize reg, type, size, offset, event_coordinator @reg = reg @type = type @size = size @offset = offset @ec = event_coordinator end def [] idx Fisk::M64.new(@reg, @offset + (idx * size)) end def []= idx, val @ec.write(self[idx], val) end end class Pointer attr_reader :reg, :type, :size def initialize reg, type, size, base, event_coordinator @reg = reg @type = type @size = size @base = base @ec = event_coordinator end # Yield a register that contains the address of this pointer def with_address offset = 0 @ec.with_ref(@reg, @base + (offset * size)) do |reg| yield reg end end def [] idx Fisk::M64.new(@reg, @base + (idx * size)) end def []= idx, val val = val.to_register if val.is_a?(TemporaryVariable) if val.is_a?(Fisk::Operand) if val.memory? @ec.write_memory @reg, @base + (idx * size), val elsif val.register? @ec.write_register @reg, @base + (idx * size), val else raise NotImplementedError end else @ec.write_immediate @reg, @base + (idx * size), val end end # Mutates this pointer. Subtracts the size from itself. Similar to # C's `--` operator def sub num = 1 if num.is_a?(Fisk::Operand) @ec.sub reg, num else @ec.sub reg, size * num end end # Mutates this pointer. Adds the size to itself. Similar to # C's `++` operator def add num = 1 @ec.add reg, size * num end def mult num @ec.mult reg, num end def with_ref offset @ec.with_ref(@reg, @base + (offset * size)) do |reg| yield Pointer.new(reg, type, size, 0, @ec) end end def method_missing m, *values return super if type == Fiddle::TYPE_VOIDP member = m.to_s v = values.first read = true if m =~ /^(.*)=/ member = $1 read = false end if read if type.member(member).substruct? sub_type = type.member(member).type return Pointer.new(@reg, sub_type, sub_type.byte_size, @base + type.offsetof(member), @ec) end end return super unless type.members.include?(member) if read if block_given? @ec.read_to_reg(@reg, type.offsetof(member)) do |reg| yield reg end else if type.member(member).immediate? return Fisk::M64.new(@reg, @base + type.offsetof(member)) else raise Array.new(reg, subtype.first, Fiddle::PackInfo::SIZE_MAP[subtype.first], @base + type.offsetof(member), @ec) end end else if v.is_a?(Pointer) @ec.write_to_mem @reg, type.offsetof(member), v.reg else if v.is_a?(Fisk::Operand) if v.memory? @ec.write_memory @reg, type.offsetof(member), v else @ec.write_register @reg, type.offsetof(member), v end else @ec.write_immediate @reg, type.offsetof(member), v.to_i end end end end end class TemporaryVariable < Pointer # Write something to the temporary variable def write operand if operand.is_a?(Fisk::Operand) @ec.write reg, operand else @ec.write_immediate_to_reg reg, operand end end def write_address_of arg @ec.load_address_in reg, arg end def and num @ec.and(reg, num) end def or num @ec.or(reg, num) end # Shift right def shr val @ec.shr reg, val end # Shift left def shl val @ec.shl reg, val end def to_register reg end def memory?; false; end def immediate?; false; end def register?; true; end def temp_register?; true; end # Release the temporary variable (say you are done using its value) def release! @ec.release_temp self end end end end
reiz/safe_cookies
lib/safe_cookies.rb
<gh_stars>1-10 # -*- encoding: utf-8 -*- require "safe_cookies/configuration" require "safe_cookies/cookie_path_fix" require "safe_cookies/helpers" require "safe_cookies/util" require "safe_cookies/version" require "rack" require "time" # add Time#rfc2822 # Naming: # - application_cookies: cookies received from the application. The 'Set-Cookie' header is a string # - request_cookies: cookies received from the client. Rack::Request#cookies returns a Hash of { 'name' => 'value' } module SafeCookies UnknownCookieError = Class.new(StandardError) STORE_COOKIE_NAME = '_safe_cookies__known_cookies' SECURED_COOKIE_NAME = 'secured_old_cookies' HELPER_COOKIES_LIFETIME = 10 * 365 * 24 * 60 * 60 # 10 years class Middleware include CookiePathFix include Helpers COOKIE_NAME_REGEX = /(?=^|\n)[^\n;,=]+/i def initialize(app) @app = app @config = SafeCookies.configuration or raise "Don't know what to do without configuration" end def call(env) reset_instance_variables @request = Rack::Request.new(env) check_if_request_has_unknown_cookies # call the next middleware up the stack status, @headers, body = @app.call(env) cache_application_cookies_string enhance_application_cookies! store_application_cookie_names delete_cookies_on_bad_path if fix_cookie_paths? rewrite_request_cookies unless cookies_have_been_rewritten_before? [ status, @headers, body ] end private # Instance variables survive requests because the middleware is a singleton. def reset_instance_variables @request, @headers, @application_cookies_string = nil end def check_if_request_has_unknown_cookies request_cookie_names = request_cookies.keys.map(&:to_s) unknown_cookie_names = request_cookie_names - known_cookie_names if unknown_cookie_names.any? message = "Request for '#{@request.url}' had unknown cookies: #{unknown_cookie_names.join(', ')}" log(message) if @config.log_unknown_cookies handle_unknown_cookies(unknown_cookie_names) end end # Overwrites @header['Set-Cookie']! def enhance_application_cookies! if @application_cookies_string cookies = @application_cookies_string.split("\n") # On Rack 1.1, cookie values sometimes contain trailing newlines. # Example => ["foo=1; path=/\n", "bar=2; path=/"] # Note that they also mess up browsers, when this array is merged # again and the "Set-Cookie" header then contains double newlines. cookies = cookies. map(&:strip). select{ |c| c.length > 0}. map(&method(:secure)). map(&method(:http_only)) # Unfortunately there is no pretty way to touch a "Set-Cookie" header. # It contains more information than the "HTTP_COOKIE" header from the # browser's request contained, so a `Rack::Request` can't parse it for # us. A `Rack::Response` doesn't offer a way either. @headers['Set-Cookie'] = cookies.join("\n") end end # Store the names of cookies that are set by the application. # (We are already securing those and will not need to rewrite them.) def store_application_cookie_names if @application_cookies_string application_cookie_names = stored_application_cookie_names + @application_cookies_string.scan(COOKIE_NAME_REGEX) application_cookies_string = application_cookie_names.uniq.join(KNOWN_COOKIES_DIVIDER) set_cookie!(STORE_COOKIE_NAME, application_cookies_string, :expire_after => HELPER_COOKIES_LIFETIME) end end # This method takes the cookies sent with the request and rewrites them, # making them both secure and http-only (unless specified otherwise in # the configuration). # With the SECURED_COOKIE_NAME cookie we remember the exact time that we # rewrote the cookies. def rewrite_request_cookies rewritable_cookies = rewritable_request_cookies # don't rewrite request cookies that the application is setting in the response if @application_cookies_string app_cookie_names = @application_cookies_string.scan(COOKIE_NAME_REGEX) Util.except!(rewritable_cookies, *app_cookie_names) end if rewritable_cookies.any? rewritable_cookies.each do |cookie_name, value| options = @config.registered_cookies[cookie_name] set_cookie!(cookie_name, value, options) end set_cookie!(SECURED_COOKIE_NAME, Time.now.gmtime.rfc2822, :expire_after => HELPER_COOKIES_LIFETIME) end end # API method def handle_unknown_cookies(cookie_names) end def log(error_message) message = '** [SafeCookies] ' message << error_message Rails.logger.error(message) if defined?(Rails) end end end
reiz/safe_cookies
lib/safe_cookies/cookie_path_fix.rb
<reponame>reiz/safe_cookies<filename>lib/safe_cookies/cookie_path_fix.rb module SafeCookies module CookiePathFix # Previously, the SafeCookies gem would not set a path when rewriting # cookies. Browsers then would assume and store the current "directory" # (see below), leading to multiple cookies per domain. # # If the cookies were secured before the configured datetime, this method # instructs the client to delete all cookies it sent with the request and # that we are able to rewrite, plus the SECURED_COOKIE_NAME helper cookie. # # The middleware still sees the request cookies and will rewrite them as # if it hadn't seen them before, setting them on the correct path (root, # by default). def delete_cookies_on_bad_path rewritable_request_cookies.keys.each &method(:delete_cookie_for_current_directory) delete_cookie_for_current_directory(SafeCookies::SECURED_COOKIE_NAME) # Delete this cookie here, so the middleware believes it hasn't secured # the cookies yet. @request.cookies.delete(SafeCookies::SECURED_COOKIE_NAME) end private def fix_cookie_paths? @config.fix_cookie_paths && cookies_have_been_rewritten_before? && (secured_old_cookies_timestamp < @config.correct_cookie_paths_timestamp) end # Delete cookies by giving them an expiry in the past, # cf. https://tools.ietf.org/html/rfc6265#section-4.1.2. # # Most importantly, as specified in # https://tools.ietf.org/html/rfc6265#section-4.1.2.4 and in section 5.1.4, # cookies set without a path will be set for the current "directory", that is: # # > ... the characters of the uri-path from the first character up # > to, but not including, the right-most %x2F ("/"). # # However, Firefox includes the right-most slash when guessing the cookie path, # so we must resort to letting browsers estimate the deletion cookie path again. def delete_cookie_for_current_directory(cookie_name) unless current_directory_is_root? one_week = (7 * 24 * 60 * 60) set_cookie!(cookie_name, "", :path => nil, :expire_after => -one_week) end end def current_directory_is_root? # in words: "there are not three slashes before any query params" !@request.path[%r(^/[^/]+/[^\?]+), 0] end def secured_old_cookies_timestamp @request.cookies.has_key?(SafeCookies::SECURED_COOKIE_NAME) or return nil Time.rfc2822(@request.cookies[SafeCookies::SECURED_COOKIE_NAME]) rescue ArgumentError # If we cannot parse the secured_old_cookies time, # assume it was before we noticed the bug to ensure # broken cookie paths will be fixed. # # One reason to get here is that Rack::Utils.rfc2822 produces an invalid # datetime string in Rack v1.1, writing the date with dashes # (e.g. '04-Nov-2013'). Time.parse "2013-08-25 00:00" end end end
reiz/safe_cookies
lib/safe_cookies/configuration.rb
<reponame>reiz/safe_cookies module SafeCookies MissingOptionError = Class.new(StandardError) class << self attr_accessor :configuration def configure self.configuration ||= Configuration.new yield(configuration) end end class Configuration attr_accessor :log_unknown_cookies attr_reader :registered_cookies, :fix_cookie_paths, :correct_cookie_paths_timestamp, :ignored_cookies def initialize self.registered_cookies = {} self.insecure_cookies = [] self.scriptable_cookies = [] self.ignored_cookies = [] end # Register cookies you expect to receive. The middleware will rewrite all # registered cookies it receives, making them both secure and http_only. # # Unfortunately, the client won't ever tell us if the cookie was originally # sent with flags such as "secure" or which expiry date it currently has: # http://tools.ietf.org/html/rfc6265#section-4.2.2 # # Therefore, specify an expiry, and more options if needed: # # :expire_after => 1.year # :secure => false # :http_only = false # :path => '/foo/path' # def register_cookie(name, options) name.is_a?(String) or raise "Cookie name must be a String" options.has_key?(:expire_after) or raise MissingOptionError.new("Cookie #{name.inspect} was registered without an expiry") raise NotImplementedError if options.has_key?(:domain) registered_cookies[name] = (options || {}).freeze insecure_cookies << name if options[:secure] == false scriptable_cookies << name if options[:http_only] == false end # Ignore cookies that you don't control like this: # # ignore_cookie 'ignored_cookie' # ignore_cookie /^__utm/ def ignore_cookie(name_or_regex) self.ignored_cookies << name_or_regex end def fix_paths(options = {}) options.has_key?(:for_cookies_secured_before) or raise MissingOptionError.new("Was told to fix paths without the :for_cookies_secured_before timestamp.") self.fix_cookie_paths = true self.correct_cookie_paths_timestamp = options[:for_cookies_secured_before] end def insecure_cookie?(name) insecure_cookies.include? name end def scriptable_cookie?(name) scriptable_cookies.include? name end private attr_accessor :insecure_cookies, :scriptable_cookies attr_writer :registered_cookies, :fix_cookie_paths, :correct_cookie_paths_timestamp, :ignored_cookies end end
reiz/safe_cookies
lib/safe_cookies/util.rb
<reponame>reiz/safe_cookies class SafeCookies::Util class << self def slice(hash, *allowed_keys) sliced_hash = hash.select { |key, _value| allowed_keys.include? key } # Normalize the result of Hash#select # (Ruby 1.8 returns an Array, Ruby 1.9 returns a Hash) Hash[sliced_hash] end # rejected_keys may be of type String or Regex def except!(hash, *rejected_keys) hash.delete_if do |key, _value| rejected_keys.any? { |rejected| rejected === key } end end end end
reiz/safe_cookies
spec/util_spec.rb
<filename>spec/util_spec.rb require 'spec_helper' describe SafeCookies::Util do describe '.except!' do before do @hash = { 'a' => 1, 'ab' => 2, 'b' => 3 } end it 'deletes the given keys from the original hash' do SafeCookies::Util.except!(@hash, 'a') @hash.should == { 'ab' => 2, 'b' => 3 } end it 'deletes all keys that match the regex' do SafeCookies::Util.except!(@hash, /b/) @hash.should == { 'a' => 1 } end it 'returns the original hash' do SafeCookies::Util.except!(@hash, /(?!)/).should == @hash end end end
reiz/safe_cookies
lib/safe_cookies/helpers.rb
module SafeCookies module Helpers KNOWN_COOKIES_DIVIDER = '|' # Since we have to operate on and modify the actual @headers hash that the # application returns, cache the @headers['Set-Cookie'] string so that # later on, we still know what the application did set. def cache_application_cookies_string cookies = @headers['Set-Cookie'] # Rack 1.1 returns an Array cookies = cookies.join("\n") if cookies.is_a?(Array) if cookies and cookies.length > 0 @application_cookies_string = cookies end # else, @application_cookies_string will be `nil` end def secure(cookie) # Regexp from https://github.com/tobmatth/rack-ssl-enforcer/ if should_be_secure?(cookie) and cookie !~ /(^|;\s)secure($|;)/ "#{cookie}; secure" else cookie end end def http_only(cookie) if should_be_http_only?(cookie) and cookie !~ /(^|;\s)HttpOnly($|;)/ "#{cookie}; HttpOnly" else cookie end end def set_cookie!(name, value, options) options = options.dup expire_after = options.delete(:expire_after) options[:expires] = Time.now + expire_after if expire_after options[:path] = '/' unless options.has_key?(:path) # allow setting path = nil options[:value] = value options[:secure] = should_be_secure?(name) options[:httponly] = should_be_http_only?(name) # Rack magic Rack::Utils.set_cookie_header!(@headers, name, options) end # getters # returns the request cookies minus ignored cookies def request_cookies Util.except!(@request.cookies.dup, *@config.ignored_cookies) end def stored_application_cookie_names store_cookie = @request.cookies[STORE_COOKIE_NAME] || "" store_cookie.split(KNOWN_COOKIES_DIVIDER) end def rewritable_request_cookies Util.slice(request_cookies, *@config.registered_cookies.keys) end def known_cookie_names known = [STORE_COOKIE_NAME, SECURED_COOKIE_NAME] known += stored_application_cookie_names known += @config.registered_cookies.keys end # boolean def cookies_have_been_rewritten_before? @request.cookies.has_key? SECURED_COOKIE_NAME end def should_be_secure?(cookie) cookie_name = cookie.split('=').first.strip ssl? and not @config.insecure_cookie?(cookie_name) end def ssl? if @request.respond_to?(:ssl?) @request.ssl? else # older Rack versions @request.scheme == 'https' end end def should_be_http_only?(cookie) cookie_name = cookie.split('=').first.strip not @config.scriptable_cookie?(cookie_name) end end end
reiz/safe_cookies
spec/safe_cookies_spec.rb
# -*- encoding: utf-8 -*- require 'spec_helper' describe SafeCookies::Middleware do subject { described_class.new(app) } let(:app) { stub 'application' } let(:env) { { 'HTTPS' => 'on' } } it 'rewrites registered request cookies as secure and http-only, but only once' do SafeCookies.configure do |config| config.register_cookie('foo', :expire_after => 3600) end # first request: rewrite cookie stub_app_call(app) set_request_cookies(env, 'foo=bar') code, headers, response = subject.call(env) headers['Set-Cookie'].should =~ /foo=bar;.* secure; HttpOnly/ # second request: do not rewrite cookie again received_cookies = extract_cookies(headers['Set-Cookie']) received_cookies.should include('foo=bar') # sanity check # client returns with the cookies, `app` and `subject` are different # objects than in the previous request other_app = stub('application') other_subject = described_class.new(other_app) stub_app_call(other_app) set_request_cookies(env, *received_cookies) code, headers, response = other_subject.call(env) headers['Set-Cookie'].to_s.should == '' end it 'doesn’t make cookies secure if the request was not secure' do stub_app_call(app, :application_cookies => 'filter-settings=sort_by_date') env['HTTPS'] = 'off' code, headers, response = subject.call(env) headers['Set-Cookie'].should include("filter-settings=sort_by_date") headers['Set-Cookie'].should_not match(/\bsecure\b/i) end it 'expires the secured_old_cookies helper cookie in ten years' do Timecop.freeze(Time.parse('2013-09-17 17:53')) SafeCookies.configure do |config| config.register_cookie('cookie_to_update', :expire_after => 3600) end set_request_cookies(env, 'cookie_to_update=some_data') stub_app_call(app) code, headers, response = subject.call(env) headers['Set-Cookie'].should =~ /secured_old_cookies.*expires=Fri, 15 Sep 2023 \d\d:\d\d:\d\d/ end context 'cookie attributes' do it 'sets cookies on the root path' do SafeCookies.configure do |config| config.register_cookie('my_old_cookie', :expire_after => 3600) end set_request_cookies(env, 'my_old_cookie=foobar') stub_app_call(app) code, headers, response = subject.call(env) cookies = headers['Set-Cookie'].split("\n") cookies.each do |cookie| cookie.should include('; path=/;') end end it 'should not alter cookie attributes coming from the application' do stub_app_call(app, :application_cookies => 'cookie=data; path=/; expires=next_week') code, headers, response = subject.call(env) headers['Set-Cookie'].should =~ %r(cookie=data; path=/; expires=next_week; secure; HttpOnly) end it 'should respect cookie attributes set in the configuration' do Timecop.freeze SafeCookies.configure do |config| config.register_cookie('foo', :expire_after => 3600, :path => '/special/path') end stub_app_call(app) set_request_cookies(env, 'foo=bar') env['PATH_INFO'] = '/special/path/subfolder' code, headers, response = subject.call(env) expected_expiry = (Time.now + 3600).gmtime.rfc2822 # a special date format needed here headers['Set-Cookie'].should =~ %r(foo=bar; path=/special/path; expires=#{expected_expiry}; secure; HttpOnly) end end context 'cookies set by the application' do it 'should make application cookies secure and http-only' do stub_app_call(app, :application_cookies => 'application_cookie=value') code, headers, response = subject.call(env) headers['Set-Cookie'].should =~ /application_cookie=value;.* secure; HttpOnly/ end it 'should not make application cookies secure that are specified as non-secure' do SafeCookies.configure do |config| config.register_cookie('filter-settings', :expire_after => 3600, :secure => false) end stub_app_call(app, :application_cookies => 'filter-settings=sort_by_date') code, headers, response = subject.call(env) headers['Set-Cookie'].should include("filter-settings=sort_by_date") headers['Set-Cookie'].should_not =~ /filter-settings=.*secure/i end it 'should not make application cookies http-only that are specified as non-http-only' do SafeCookies.configure do |config| config.register_cookie('javascript-cookie', :expire_after => 3600, :http_only => false) end stub_app_call(app, :application_cookies => 'javascript-cookie=xss') code, headers, response = subject.call(env) headers['Set-Cookie'].should include("javascript-cookie=xss") headers['Set-Cookie'].should_not =~ /javascript-cookie=.*HttpOnly/i end it 'does not rewrite a client cookie when the application is setting a cookie with the same name' do SafeCookies.configure do |config| config.register_cookie('cookie', :expire_after => 3600) end stub_app_call(app, :application_cookies => 'cookie=from_application') set_request_cookies(env, 'cookie=from_client') code, headers, response = subject.call(env) headers['Set-Cookie'].should include("cookie=from_application") headers['Set-Cookie'].should_not include("cookie=from_client") end end context 'cookies sent by the client' do it 'should not make request cookies secure that are specified as non-secure' do SafeCookies.configure do |config| config.register_cookie('filter', :expire_after => 3600, :secure => false) end stub_app_call(app) set_request_cookies(env, 'filter=cars_only') code, headers, response = subject.call(env) headers['Set-Cookie'].should =~ /filter=cars_only;.* HttpOnly/ headers['Set-Cookie'].should_not =~ /filter=cars_only;.* secure/ end it 'should not make request cookies http-only that are specified as non-http-only' do SafeCookies.configure do |config| config.register_cookie('js-data', :expire_after => 3600, :http_only => false) end stub_app_call(app) set_request_cookies(env, 'js-data=json') code, headers, response = subject.call(env) headers['Set-Cookie'].should =~ /js-data=json;.* secure/ headers['Set-Cookie'].should_not =~ /js-data=json;.* HttpOnly/ end end context 'ignored cookies' do before do stub_app_call(app) set_request_cookies(env, '__utma=123', '__utmz=456') end it 'does not rewrite ignored cookies given as string' do SafeCookies.configure do |config| config.ignore_cookie '__utma' config.ignore_cookie '__utmz' end code, headers, response = subject.call(env) headers['Set-Cookie'].should_not =~ /__utm/ end it 'does not rewrite ignored cookies given as regex' do SafeCookies.configure do |config| config.ignore_cookie /^__utm/ end code, headers, response = subject.call(env) headers['Set-Cookie'].should_not =~ /__utm/ end end # The unknown cookies mechanism was more important when we were sending # notifications on encountering unknown cookies. Perhaps, it will regain # importance in the future. context 'when a request has unknown cookies,' do it 'allows overwriting the handling mechanism' do stub_app_call(app) set_request_cookies(env, 'foo=bar') def subject.handle_unknown_cookies(*args) @custom_method_called = true end subject.call(env) subject.instance_variable_get('@custom_method_called').should == true end context 'and it is configured to log unknown cookies' do before do SafeCookies.configure do |config| config.log_unknown_cookies = true end end it 'logs an error message' do stub_app_call(app) set_request_cookies(env, 'foo=bar') subject.should_receive(:log).with(/unknown cookies: foo/) subject.call(env) end it 'does not log an error if the (unregistered) cookie was initially set by the application' do # application sets cookie stub_app_call(app, :application_cookies => 'foo=bar; path=/some/path; secure') code, headers, response = subject.call(env) received_cookies = extract_cookies(headers['Set-Cookie']) received_cookies.should include('foo=bar') # sanity check # client returns with the cookie, `app` and `subject` are different # objects than in the previous request other_app = stub('application') other_subject = described_class.new(other_app) stub_app_call(other_app) set_request_cookies(env, *received_cookies) other_subject.should_not_receive(:log) other_subject.call(env) end it 'does not log an error if the cookie is listed in the cookie configuration' do SafeCookies.configure do |config| config.register_cookie('foo', :expire_after => 3600) end stub_app_call(app) set_request_cookies(env, 'foo=bar') subject.should_not_receive(:log) subject.call(env) end it 'does not log an error if the cookie is ignored' do SafeCookies.configure do |config| config.ignore_cookie '__utma' end stub_app_call(app) set_request_cookies(env, '__utma=tracking') subject.should_not_receive(:log) subject.call(env) end end end end
reiz/safe_cookies
spec/cookie_path_fix_spec.rb
require 'spec_helper' require 'cgi' describe SafeCookies::Middleware do describe 'cookie path fix,' do subject { described_class.new(app) } let(:app) { stub 'application' } let(:env) { { 'HTTPS' => 'on' } } before do @now = Time.parse('2050-01-01 00:00') Timecop.travel(@now) end def set_default_request_cookies(secured_at = Time.parse('2040-01-01 00:00')) set_request_cookies(env, 'cookie_to_update=some_data', "secured_old_cookies=#{CGI::escape(secured_at.gmtime.rfc2822)}") end context 'rewriting previously secured cookies,' do before do SafeCookies.configure do |config| config.register_cookie('cookie_to_update', :expire_after => 3600) config.fix_paths :for_cookies_secured_before => Time.parse('2050-01-02 00:00') end stub_app_call(app) set_default_request_cookies end it 'updates the timestamp on the root secured_old_cookies cookie' do code, headers, response = subject.call(env) updated_secured_old_cookies_timestamp = 'Fri%2C+31+Dec+2049+23%3A00%3A00+-0000' headers['Set-Cookie'].should =~ /secured_old_cookies=#{Regexp.escape updated_secured_old_cookies_timestamp}; path=\/;/ end it 'sets the cookie path to "/"' do code, headers, response = subject.call(env) headers['Set-Cookie'].should =~ /cookie_to_update=some_data;.*path=\/;/ end it 'deletes cookies for the current "directory"' do env['PATH_INFO'] = '/complex/sub/path' code, headers, response = subject.call(env) set_cookie = headers['Set-Cookie'] # overwrite the cookie with an empty value set_cookie.should =~ /cookie_to_update=;/ # the deletion cookie must not have a path, so browsers use their own implementation of cookie path # determination, the same they used when the cookie was implicitly set on the wrong path set_cookie.should_not =~ %r(cookie_to_update=;.*path=) # cookies are deleted by giving them an expiry in the past deletion_expiry = set_cookie[/cookie_to_update=;.*expires=([^;]+)/, 1] Time.parse(deletion_expiry).should < @now end it 'does not delete cookies from root ("/") requests, since root cookies are the default we expect' do env['PATH_INFO'] = '/' code, headers, response = subject.call(env) headers['Set-Cookie'].should_not =~ /cookie_to_update=;/ end it 'does not delete cookies from first-level paths like "/first_level", since their "directory" is "/"' do env['PATH_INFO'] = '/first_level' code, headers, response = subject.call(env) headers['Set-Cookie'].should_not =~ /cookie_to_update=;/ end it 'does not delete cookies from first-level paths like "/first_level/", since their "directory" is "/"' do env['PATH_INFO'] = '/first_level' code, headers, response = subject.call(env) headers['Set-Cookie'].should_not =~ /cookie_to_update=;/ end it 'should not be confused by query parameters' do env['PATH_INFO'] = '/some/sub/directory/with?query=params&and=/another/path' code, headers, response = subject.call(env) headers['Set-Cookie'].should =~ %r(cookie_to_update=;) end it 'should not "fix" a path set by the application' do stub_app_call(app, :application_cookies => 'new_cookie=NEW_DATA; path=/special/path') env['PATH_INFO'] = '/special/path/sub/folder' code, headers, response = subject.call(env) headers['Set-Cookie'].should =~ %r(new_cookie=NEW_DATA;.*path=/special/path;) end it 'deletes the secured_old_cookies cookie on the current "directory", so future requests to that directory do not trigger a rewrite of all cookies' do env['PATH_INFO'] = '/complex/sub/path' code, headers, response = subject.call(env) # delete the "directory" secured_old_cookies cookie ... headers['Set-Cookie'].should =~ %r(secured_old_cookies=;) # ... but do not delete the root secured_old_cookies cookie headers['Set-Cookie'].should =~ %r(secured_old_cookies=\w+.*path=/;) end context 'unparseable secured_old_cookies timestamp,' do before do set_request_cookies(env, 'cookie_to_update=some_data', 'secured_old_cookies=rubbish') code, @headers, response = subject.call(env) end it 'rewrites cookies anyway' do @headers['Set-Cookie'].should include('cookie_to_update=some_data;') end it 'sets a new, parseable secured_old_cookies timestamp' do @headers['Set-Cookie'].should include("secured_old_cookies=#{CGI::escape @now.gmtime.rfc2822}") end end end it 'does not rewrite previously secured cookies if not told so' do SafeCookies.configure do |config| config.register_cookie('cookie_to_update', :expire_after => 3600) # missing config.fix_paths end stub_app_call(app) set_default_request_cookies code, headers, response = subject.call(env) headers['Set-Cookie'].should be_nil end it 'raises an error if told to fix cookie paths without specifying a date' do fix_paths_without_timestamp = lambda do SafeCookies.configure do |config| config.fix_paths # missing :for_cookies_secured_before option end end expect(&fix_paths_without_timestamp).to raise_error(SafeCookies::MissingOptionError) end it 'does not rewrite cookies that were secured after the correct_cookie_paths_timestamp' do SafeCookies.configure do |config| config.register_cookie('cookie_to_update', :expire_after => 3600) config.fix_paths :for_cookies_secured_before => Time.parse('2050-01-02 00:00') end stub_app_call(app) set_default_request_cookies(Time.parse('2050-01-03 00:00')) code, headers, response = subject.call(env) headers['Set-Cookie'].should be_nil end end end
reiz/safe_cookies
spec/spec_helper.rb
require File.expand_path('../../lib/safe_cookies', __FILE__) require 'timecop' RSpec.configure do |config| config.treat_symbols_as_metadata_keys_with_true_values = true config.run_all_when_everything_filtered = true config.filter_run :focus # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = 'random' config.before(:each) { SafeCookies.configure {} } config.after(:each) { SafeCookies.configuration = nil Timecop.return } end def stub_app_call(app, options = {}) env = {} env['Set-Cookie'] = options[:application_cookies] if options[:application_cookies] app.stub :call => [ stub, env, stub ] end def set_request_cookies(env, *cookies) env['HTTP_COOKIE'] = cookies.join(',') end def extract_cookies(set_cookies_header) set_cookies_header.scan(/(?=^|\n)[^\n;]+=[^\n;]+(?=;\s)/i) end
reiz/safe_cookies
spec/configuration_spec.rb
# encoding: utf-8 require 'spec_helper' describe SafeCookies::Middleware do it 'does not allow registered cookies to be altered' do SafeCookies.configure do |config| config.register_cookie('filter', :expire_after => 3600) end filter_options = SafeCookies.configuration.registered_cookies['filter'] expect { filter_options[:foo] = 'bar' }.to raise_error(Exception, /can't modify frozen hash/i) end describe '.configure' do it 'currently does not support the :domain cookie option' do registration_with_domain = lambda do SafeCookies.configure do |config| config.register_cookie('filter', :domain => 'example.com', :expire_after => 3600) end end expect(&registration_with_domain).to raise_error(NotImplementedError) end describe 'register_cookie' do it 'raises an error if a cookie is registered without passing its expiry' do registration_without_expiry = lambda do SafeCookies.configure do |config| config.register_cookie('filter', :some => :option) end end expect(&registration_without_expiry).to raise_error(SafeCookies::MissingOptionError) end it 'raises an error if the cookie name is not a String, because the middleware’s logic depends on strings' do registration_as_symbol = lambda do SafeCookies.configure do |config| config.register_cookie(:filter, :some => :option) end end expect(&registration_as_symbol).to raise_error(RuntimeError, /must be a string/i) end it 'allows nil as expiry (means session cookie)' do registration_with_nil_expiry = lambda do SafeCookies.configure do |config| config.register_cookie('filter', :expire_after => nil) end end expect(&registration_with_nil_expiry).to_not raise_error(SafeCookies::MissingOptionError) end end end end
antrix1/omniauth-bnet
lib/omniauth-bnet.rb
<filename>lib/omniauth-bnet.rb require "omniauth-bnet/version" require "omniauth/strategies/bnet"
antrix1/omniauth-bnet
lib/omniauth/strategies/bnet.rb
require 'omniauth-oauth2' require 'base64' module OmniAuth module Strategies class Bnet < OmniAuth::Strategies::OAuth2 option :region, 'us' option :client_options, { :scope => 'wow.profile sc2.profile' } def client # Setup urls based on region option if !options.client_options.has_key(:authorize_url) options.client_options[:authorize_url] = "https://#{getHost(options.region)}/oauth/authorize" end if !options.client_options.has_key(:token_url) options.client_options[:token_url] = "https://#{getHost(options.region)}/oauth/token" end if !options.client_options.has_key(:site) options.client_options[:site] = "https://#{getHost(options.region)}/" end super end def request_phase super end def authorize_params super.tap do |params| %w[scope client_options].each do |v| if request.params[v] params[v.to_sym] = request.params[v] end end end end uid { raw_info['id'].to_s } info do raw_info end def raw_info return @raw_info if @raw_info access_token.options[:mode] = :query @raw_info = access_token.get('oauth/userinfo').parsed end private def callback_url full_host + script_name + callback_path end def getHost(region) case region when "cn" "www.battlenet.com.cn" else "#{region}.battle.net" end end end end end
antrix1/omniauth-bnet
examples/sinatra.rb
#!/usr/bin/env ruby # This example provides login links for github and bnet in order to test that # bnet oauth is correctly working. require 'omniauth' require 'omniauth-bnet' require 'omniauth-github' require 'sinatra' # Uncomment to see requests going back and forth <3 # require 'httplog' # HttpLog.options[:log_headers] = true configure do use OmniAuth::Builder do provider :github, ENV['GITHUB_ID'], ENV['GITHUB_SECRET'] provider :bnet, ENV['BNET_ID'], ENV['BNET_SECRET'], scope: "wow.profile sc2.profile" end OmniAuth.config.full_host = "https://localhost" enable :sessions enable :inline_templates end helpers do def current_user session[:user_id] end def current_user_info session[:user_info] end def h(text) Rack::Utils.escape_html(text) end end get '/' do if current_user erb '<h1>Sinatra OAuth Test</h1><%=current_user%><br><pre><%=h current_user_info%></pre><br><pre><%=h session[:debug]%></pre><br><a href="/logout">Logout</a>' else erb '<h1>Sinatra OAuth Test</h1><a href="/auth/github">Login with Github</a><br><a href="/auth/bnet">Login with Bnet</a>' end end get '/auth/:name/callback' do auth = request.env["omniauth.auth"] session[:user_id] = auth["uid"] session[:user_info] = auth["info"] session[:debug] = auth.to_yaml redirect OmniAuth.config.full_host end get '/auth/failure' do erb "<h1>Authentication Failed:</h1><h3>message:#{params[:message]}<h3> <pre>#{params}</pre>" end get '/auth/:provider/deauthorized' do erb "#{params[:provider]} has deauthorized this app." end get '/logout' do session[:user_id] = nil session[:user_info] = nil redirect OmniAuth.config.full_host end __END__ @@ layout <html> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script> </head> <body> <div class='container'> <div class='content'> <%= yield %> </div> </div> </body> </html>
antrix1/omniauth-bnet
lib/omniauth-bnet/version.rb
<filename>lib/omniauth-bnet/version.rb module OmniAuth module Bnet VERSION = "2.0.0" end end
javier-delgado/URF-picker
app/models/highest_stat.rb
<gh_stars>0 # == Schema Information # # Table name: highest_stats # # id :integer not null, primary key # champion_id :integer # assists :float # champ_level :float # deaths :float # double_kills :float # gold_earned :integer # kills :float # magic_damage_dealt_to_champions :integer # magic_damage_taken :integer # minions_killed :float # neutral_minions_killed :float # penta_kills :float # physical_damage_dealt_to_champions :integer # physical_damage_taken :integer # quadra_kills :float # total_damage_dealt_to_champions :integer # total_damage_taken :integer # total_heal :integer # total_time_crowd_control_dealt :integer # tower_kills :float # triple_kills :float # true_damage_dealt_to_champions :integer # unreal_kills :float # wards_placed :float # wins :float # loses :float # region_id :integer # count :integer # class HighestStat < ActiveRecord::Base belongs_to :champion belongs_to :region scope :by_region, ->(region) { where(region: region) } scope :by_champ_name, ->(name) { joins(:champion).where("champions.name = ?", name) } def stats_names names = attribute_names - ['id', 'champion_id', 'region_id', 'count'] names.sort_by { |n| n.downcase } end end
javier-delgado/URF-picker
db/migrate/20150405231715_change_integer_to_decimal.rb
class ChangeIntegerToDecimal < ActiveRecord::Migration def change change_table :highest_stats do |t| t.change :assists, :float t.change :champ_level, :float t.change :deaths, :float t.change :double_kills, :float t.change :kills, :float t.change :minions_killed, :float t.change :neutral_minions_killed, :float t.change :penta_kills, :float t.change :quadra_kills, :float t.change :tower_kills, :float t.change :triple_kills, :float t.change :unreal_kills, :float t.change :wards_placed, :float t.change :wins, :float t.change :loses, :float end end end
javier-delgado/URF-picker
app/controllers/home_controller.rb
<filename>app/controllers/home_controller.rb class HomeController < ApplicationController def search; end end
javier-delgado/URF-picker
config/deploy.rb
<reponame>javier-delgado/URF-picker # config valid only for Capistrano 3.1 lock '3.1.0' set :application, 'URF-picker' set :repo_url, '<EMAIL>:javier-delgado/URF-picker.git' set :deploy_to, '/home/deploy/URF-picker' set :linked_files, %w{config/database.yml config/secrets.yml} set :linked_dirs, %w{log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system} set :whenever_identifier, ->{ "#{fetch(:application)}_#{fetch(:stage)}" } namespace :deploy do desc 'Restart application' task :restart do on roles(:app), in: :sequence, wait: 5 do execute :touch, release_path.join('tmp/restart.txt') end end after :publishing, 'deploy:restart' after :finishing, 'deploy:cleanup' end
javier-delgado/URF-picker
db/migrate/20150331012700_create_teams.rb
<reponame>javier-delgado/URF-picker class CreateTeams < ActiveRecord::Migration def change create_table :teams do |t| t.integer :team_key t.integer :baron_kills t.integer :dragon_kills t.boolean :firs_baron t.boolean :first_dragon t.boolean :first_blood t.boolean :first_inhibitor t.boolean :first_tower t.integer :tower_kills t.boolean :winner t.references :match_detail, index: true t.timestamps null: false end add_foreign_key :teams, :match_details end end
javier-delgado/URF-picker
app/models/team.rb
<reponame>javier-delgado/URF-picker # == Schema Information # # Table name: teams # # id :integer not null, primary key # team_key :integer # baron_kills :integer # dragon_kills :integer # firs_baron :boolean # first_dragon :boolean # first_blood :boolean # first_inhibitor :boolean # first_tower :boolean # tower_kills :integer # winner :boolean # match_detail_id :integer # created_at :datetime not null # updated_at :datetime not null # class Team < ActiveRecord::Base belongs_to :match_detail scope :by_key, ->(key) { where(team_key: key).first } end
javier-delgado/URF-picker
db/migrate/20150331012746_create_participants.rb
<gh_stars>0 class CreateParticipants < ActiveRecord::Migration def change create_table :participants do |t| t.references :match_detail, index: true t.references :team, index: true t.integer :champion_key t.integer :team_key t.string :highest_achieved_season_tier t.integer :participant_key t.integer :spell1Id t.integer :spell2Id t.timestamps null: false end add_foreign_key :participants, :match_details add_foreign_key :participants, :teams end end
javier-delgado/URF-picker
app/models/region.rb
<reponame>javier-delgado/URF-picker # == Schema Information # # Table name: regions # # id :integer not null, primary key # key :string # name :string # created_at :datetime not null # updated_at :datetime not null # class Region < ActiveRecord::Base validates_uniqueness_of :key has_many :highest_stats scope :by_key, ->(key) { where(key: key).first } def url_key key.downcase end def self.for_select all.map { |x| x.key } end end
javier-delgado/URF-picker
app/models/participant_stat.rb
<reponame>javier-delgado/URF-picker # == Schema Information # # Table name: participant_stats # # id :integer not null, primary key # participant_id :integer # assists :integer # champ_level :integer # deaths :integer # double_kills :integer # gold_earned :integer # item0 :integer # item1 :integer # item2 :integer # item3 :integer # item4 :integer # item5 :integer # item6 :integer # item7 :integer # kills :integer # magic_damage_dealt_to_champions :integer # magic_damage_taken :integer # minions_killed :integer # neutral_minions_killed :integer # penta_kills :integer # physical_damage_dealt_to_champions :integer # physical_damage_taken :integer # quadra_kills :integer # total_damage_dealt_to_champions :integer # total_damage_taken :integer # total_heal :integer # total_time_crowd_control_dealt :integer # tower_kills :integer # triple_kills :integer # true_damage_dealt_to_champions :integer # unreal_kills :integer # wards_placed :integer # winner :boolean # created_at :datetime not null # updated_at :datetime not null # class ParticipantStat < ActiveRecord::Base belongs_to :participant end
javier-delgado/URF-picker
app/services/data_parser.rb
<gh_stars>0 class DataParser def initialize(json_string) @data = JSON.parse(json_string) @teams = [] end def parse! ActiveRecord::Base.transaction do match = parse_match_details parse_teams(match) parse_participants(match) end end private def parse_match_details MatchDetail.create( match_creation: @data['matchCreation'], match_duration: @data['matchDuration'], region_key: @data['region'] ) end def parse_teams(match) @data['teams'].each do |team| Team.create( match_detail: match, team_key: team['teamId'], baron_kills: team['baronKills'], dragon_kills: team['dragonKills'], firs_baron: team['firstBaron'], first_dragon: team['firstDragon'], first_blood: team['firstBlood'], first_inhibitor: team['firstInhibitor'], first_tower: team['firstTower'], tower_kills: team['towerKills'], winner: team['winner'] ) end end def parse_participants(match) @data['participants'].each do |participant| Participant.create( match_detail: match, team: match.teams.by_key(participant['teamId']), team_key: participant['teamId'], champion_key: participant['championId'], highest_achieved_season_tier: participant['highestAchievedSeasonTier'], participant_key: participant['participantId'], spell1Id: participant['spell1Id'], spell2Id: participant['spell2Id'], stats: parse_participant_stats(participant['stats']) ) end end def parse_participant_stats(stats) ParticipantStat.create( assists: stats['assists'], champ_level: stats['champLevel'], deaths: stats['deaths'], double_kills: stats['doubleKills'], gold_earned: stats['goldEarned'], item0: stats['item0'], item1: stats['item1'], item2: stats['item2'], item3: stats['item3'], item4: stats['item3'], item5: stats['item4'], item6: stats['item5'], item7: stats['item6'], kills: stats['kills'], magic_damage_dealt_to_champions: stats['magicDamageDealtToChampions'], magic_damage_taken: stats['magicDamageTaken'], minions_killed: stats['minionsKilled'], neutral_minions_killed: stats['neutralMinionsKilled'], penta_kills: stats['pentaKills'], physical_damage_dealt_to_champions: stats['physicalDamageDealtToChampions'], physical_damage_taken: stats['physicalDamageTaken'], quadra_kills: stats['quadraKills'], total_damage_dealt_to_champions: stats['totalDamageDealtToChampions'], total_damage_taken: stats['totalDamageTaken'], total_heal: stats['totalHeal'], total_time_crowd_control_dealt: stats['totalTimeCrowdControlDealt'], tower_kills: stats['towerKills'], triple_kills: stats['tripleKills'], true_damage_dealt_to_champions: stats['trueDamageDealtToChampions'], unreal_kills: stats['unrealKills'], wards_placed: stats['wardsPlaced'], winner: stats['winner'] ) end end
javier-delgado/URF-picker
db/migrate/20150331020555_create_champions_participants.rb
class CreateChampionsParticipants < ActiveRecord::Migration def self.up create_table :champions_participants, :id => false do |t| t.references :champion t.references :participant end add_index :champions_participants, [:champion_id, :participant_id] add_index :champions_participants, :participant_id end def self.down drop_table :champions_participants end end
javier-delgado/URF-picker
db/migrate/20150331015316_create_banned_champions.rb
<gh_stars>0 class CreateBannedChampions < ActiveRecord::Migration def change create_table :banned_champions do |t| t.references :team, index: true t.references :champion, index: true t.integer :champion_key t.timestamps null: false end add_foreign_key :banned_champions, :teams add_foreign_key :banned_champions, :champions end end
javier-delgado/URF-picker
lib/tasks/calculate_averages.rake
<filename>lib/tasks/calculate_averages.rake<gh_stars>0 namespace :data do task :calculate_averages => :environment do t = Time.now puts "Caclulating averages..." champ_average = ChampAverages.new champ_average.calculate! puts "Done, " + (Time.now - t).to_s + " seconds" end end
javier-delgado/URF-picker
app/helpers/application_helper.rb
module ApplicationHelper def put_background_image(image_path, position = "center") "<style media='screen'> body { background: #222222 url(#{image_path}) no-repeat #{position} center; background-size: cover; background-attachment: fixed; } </style>".html_safe end end