text
stringlengths
10
2.61M
class Admin < ApplicationRecord validates :email, presence: true validates :email, format: { with: URI::MailTo::EMAIL_REGEXP } devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable class << self def authenticate(email, password) user = Admin.find_for_authentication(email: email) user.try(:valid_password?, password) ? user : nil end end end
require "spec_helper" describe FuzzyFind do class Foo include FuzzyFind end describe ".fuzzy_find!" do subject { Foo.fuzzy_find id } context "when the id is a uuid" do let(:id) { "abc123" } it "uses uuid to find" do expect(Foo).to receive(:find_by!).with uuid: "abc123" subject end end context "when the id is an integer id" do let(:id) { "123" } it "uses id to find" do expect(Foo).to receive(:find_by!).with id: "123" subject end end end describe ".fuzzy_find" do subject { Foo.fuzzy_find 1 } before do expect(Foo).to receive(:find_by!) do raise ActiveRecord::RecordNotFound end end it { expect{ subject }.not_to raise_error } end end
# -*- coding: utf-8 -*- # -*- mode: ruby -*- # vi: set ft=ruby : # Vagrantfile API/syntax version. Don't touch unless you know what you're doing VAGRANTFILE_API_VERSION = '2' Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = 'centos65-base' config.vm.box_url = '~/Vagrant/centos65/centos65.box' config.vm.network 'private_network', ip: '192.168.56.101' config.vm.synced_folder '.', '/vagrant', { :create => true, :owner => 'root', :group => 'root', :mount_options => ['dmode=777', 'fmode=777'] } config.vm.provider :virtualbox do |v| v.customize ['modifyvm', :id, '--cpus', '1'] v.customize ['modifyvm', :id, '--memory', '512'] end config.omnibus.chef_version = :latest config.vm.hostname = 'redmine.vm' config.vm.provision :chef_solo do |chef| chef.cookbooks_path = ['berks-cookbooks', 'site-cookbooks'] chef.custom_config_path = '.chef/vagrant.rb' chef.add_recipe 'update-packages' chef.add_recipe 'git' chef.add_recipe 'nginx' chef.add_recipe 'postgresql' chef.add_recipe 'postfix' chef.add_recipe 'rbenv' chef.add_recipe 'redmine' chef.add_recipe 'redmine::deploy' chef.json = { :environment => 'development' } end end
class ChangeColName < ActiveRecord::Migration[5.1] def change rename_column :pending_companies, :job_posting, :job_postings end end
# typed: false require "spec_helper" describe Vndb::Response do before do @raw_login_response = "ok\x04".freeze @successful_response = Vndb::Response.new(raw_body: "test") @unsuccessful_response = Vndb::Response.new(raw_body: "error") end describe ".new" do it "can be created" do response = Vndb::Response.new(raw_body: @raw_login_response) _(response).wont_be_nil end end describe "#failure?" do it "will return false when there's no error" do _(@successful_response.failure?).must_equal(false) end it "will return true when there is an error" do _(@unsuccessful_response.failure?).must_equal(true) end end describe "#success?" do it "will return true when there's no error" do _(@successful_response.success?).must_equal(true) end it "will return false when there is an error" do _(@unsuccessful_response.success?).must_equal(false) end end end
class RemovedAbbreviationFromCountries < ActiveRecord::Migration[5.2] def change remove_column :countries, :abbreviation end end
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper #def back_path(default = root_path) # session[:return_to] || default #end def bread_category(category) categories = [] parent = category.parent klass = "current" categories << link_to(parent.title, parent, :class => klass) if parent categories << link_to(category.title, category, :class => klass) categories.join(" -- ") end def rubl(price) price + ' руб.' end def paginate(collection) content_tag :div, will_paginate(collection, :previous_label => "&#171; Назад", :next_label => "Вперед &#187;" ), :class => "emph" end def display_standard_flashes(message = 'Хм.. Возникли проблемы...') if flash[:success] flash_to_display, level = flash[:success], 'notice' elsif flash[:notice] flash_to_display, level = flash[:notice], 'notice' elsif flash[:warning] flash_to_display, level = flash[:warning], 'warning' elsif flash[:failure] flash_to_display, level = flash[:failure], 'error' elsif flash[:error] level = 'error' if flash[:error].instance_of?(ActiveRecord::Errors) || flash[:error].is_a?(Hash) flash_to_display = message flash_to_display << activerecord_error_list(flash[:error]) else flash_to_display = flash[:error] end else return end content_tag 'div', content_tag(:span, sanitize(flash_to_display) + link_to("X", "#", :id => "close_flash", :style => "position:absolute; right:5px;")), :id => "flash", :class => "flash-#{level}", :style => "position:relative;" end def link_to(*args, &block) if block_given? options = args.first || {} html_options = args.second concat(link_to(capture(&block), options, html_options)) else name = args.first options = args.second || {} html_options = args.third url = url_for(options) if html_options html_options = html_options.stringify_keys href = html_options['href'] convert_options_to_javascript!(html_options, url) tag_options = tag_options(html_options) else tag_options = nil end format = '.html' href_attr = "href=\"#{url}\"" unless href "<a #{href_attr}#{tag_options}>#{name || url}</a>".html_safe end end end
require 'rails_helper' RSpec.describe Dish, type: :model do describe "validations" do it {should validate_presence_of :name} it {should validate_presence_of :description} end describe "relationships" do it {should belong_to :chef} end describe "methods" do it "total_calories" do chef1 = Chef.create!(name: "Matt") dish1 = chef1.dishes.create!(name: "Grilled Cheese", description: "Tasty") ingredient1 = dish1.ingredients.create!(name: "Bread", calories: 40) ingredient2 = dish1.ingredients.create!(name: "Cheese", calories: 60) expect(dish1.total_calories).to eq(100) end end end
class UpdateForeignKey < ActiveRecord::Migration[6.0] def change remove_foreign_key :teams, :trainers add_foreign_key :teams, :trainers, on_delete: :cascade end end
class ProductsController < ApplicationController before_action :authenticate_admin!, except: [:index, :show, :search] def index only_show_discount = params[:discount] == "true" if only_show_discount @products = Product.where("price < ?", 10) elsif params[:category_name] != nil selected_category = Category.find_by(name: params[:category_name]) @products = selected_category.products else sort_attribute = params[:sort] || "name" sort_order = params[:sort_order] || "asc" @products = Product.order(sort_attribute => sort_order) end render 'index.html.erb' end def new render 'new.html.erb' end def create @product = Product.new( name: params[:name], description: params[:description], price: params[:price], supplier_id: 1 ) if @product.save image = Image.new( url: params[:image], product_id: @product.id ) image.save flash[:success] = "Product Created" redirect_to "/products/#{@product.id}" else render 'new.html.erb' end end def show if params[:id] == "random" products = Product.all @product = products.sample else @product = Product.find_by(id: params[:id]) end render 'show.html.erb' end def edit @product = Product.find_by(id: params[:id]) render 'edit.html.erb' end def update @product = Product.find_by(id: params[:id]) @product.name = params[:name] @product.description = params[:description] @product.price = params[:price] if @product.save flash[:success] = "Product Updated" redirect_to "/products/#{@product.id}" else render 'edit.html.erb' end end def destroy @product = Product.find_by(id: params[:id]) @product.destroy flash[:warning] = "Product Destroyed" redirect_to "/products" end def search search_term = params[:search] @products = Product.where("name LIKE ?", '%' + search_term + '%') render 'index.html.erb' end end
# frozen_string_literal: true require 'benchmark' require 'fileutils' require 'rake' # os detection module OS def self.windows? (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil end def self.mac? (/darwin/ =~ RUBY_PLATFORM) != nil end def self.unix? !OS.windows? end def self.linux? OS.unix? && !OS.mac? end def self.jruby? RUBY_ENGINE == 'jruby' end end # benchmarking tasks $task_benchmarks = [] # add some benchmark logging to Task class Rake::Task def execute_with_benchmark(*args) puts "***************** executing #{name}" bm = Benchmark.realtime { execute_without_benchmark(*args) } $task_benchmarks << [name, bm] end alias execute_without_benchmark execute alias execute execute_with_benchmark end at_exit do total_time = $task_benchmarks.reduce(0) { |acc, x| acc + x[1] } $task_benchmarks .sort { |a, b| b[1] <=> a[1] } .each do |res| percentage = res[1] / total_time * 100 next unless percentage.round > 0 percentage_bar = '' percentage.round.times { percentage_bar += '|' } puts "#{percentage_bar} (#{'%.1f' % percentage} %) #{res[0]} ==> #{'%.1f' % res[1]}s" end puts "total time was: #{'%.1f' % total_time}" end # version management class Versioner def self.for(type, version_dir) case type when :gemspec GemspecVersioner.new(version_dir) when :package_json JsonVersioner.new(version_dir) when :cargo_toml TomlVersioner.new(version_dir) end end end def current_version_with_regex(filelist, r) current_version = nil FileUtils.cd @version_dir, :verbose => false do filelist.each do |file| text = File.read(file) if match = text.match(r) current_version = match.captures[1] end end end current_version end class Versioner def initialize(version_dir) @version_dir = version_dir end def get_next_version(jump) current_version = get_current_version v = Version.new(current_version) v.send(jump) end def increment_version(jump) next_version = get_next_version(jump) puts "increment version from #{get_current_version} ==> #{next_version}" update_version(next_version) end end class TomlVersioner < Versioner VERSION_REGEX = /^(version\s=\s['\"])(\d+\.\d+\.\d+)(['\"])/i.freeze def get_current_version current_version_with_regex(['Cargo.toml'], VERSION_REGEX) end def update_version(new_version) FileUtils.cd @version_dir, :verbose => false do ['Cargo.toml'].each do |file| text = File.read(file) new_contents = text.gsub(VERSION_REGEX, "\\1#{new_version}\\3") File.open(file, 'w') { |f| f.puts new_contents } end end end end class GemspecVersioner < Versioner VERSION_REGEX = /^(\s*.*?\.version\s*?=\s*['\"])(.*)(['\"])/i.freeze DATE_REGEX = /^(\s*.*?\.date\s*?=\s*['\"])(.*)(['\"])/.freeze def get_current_version current_version_with_regex(FileList['*.gemspec'], VERSION_REGEX) end def update_version(new_version) FileUtils.cd @version_dir, :verbose => false do FileList['*.gemspec'].each do |file| text = File.read(file) today = Time.now.strftime('%Y-%m-%d') correct_date_contents = text.gsub(DATE_REGEX, "\\1#{today}\\3") new_contents = correct_date_contents.gsub(VERSION_REGEX, "\\1#{new_version}\\3") File.open(file, 'w') { |f| f.write new_contents } end end end end class JsonVersioner < Versioner VERSION_REGEX = /^(\s+['\"]version['\"]:\s['\"])(.*)(['\"])/i.freeze def get_current_version current_version_with_regex(['package.json'], VERSION_REGEX) end def update_version(new_version) FileUtils.cd @version_dir, :verbose => false do ['package.json'].each do |file| text = File.read(file) new_contents = text.gsub(VERSION_REGEX, "\\1#{new_version}\\3") File.open(file, 'w') { |f| f.puts new_contents } end end end end class Version < Array def initialize(s) super(s.split('.').map(&:to_i)) end def as_version_code get_major * 1000 * 1000 + get_minor * 1000 + get_patch end def <(x) (self <=> x) < 0 end def >(x) (self <=> x) > 0 end def ==(x) (self <=> x) == 0 end def patch patch = last self[0...-1].concat([patch + 1]) end def minor self[1] = self[1] + 1 self[2] = 0 self end def major self[0] = self[0] + 1 self[1] = 0 self[2] = 0 self end def get_major self[0] end def get_minor self[1] end def get_patch self[2] end def to_s join('.') end end ## git related utilities desc 'push tag to github' task :push do sh 'git push origin' current_version = get_current_version sh "git push origin #{current_version}" end def assert_tag_exists(version) raise "tag #{version} missing" if `git tag -l #{version}`.empty? end def create_changelog(current_version, next_version) sha1s = `git log #{current_version}..HEAD --oneline`.strip.split(/\n/).collect { |line| line.split(' ').first } log_entries = [] sha1s.each do |sha1| raw_log = `git log --format=%B -n 1 #{sha1}`.strip log_lines = raw_log.split(/\n/) first_line = true entry = log_lines .reject { |x| x.strip == '' } .collect do |line| if line =~ /^\s*\*/ line.sub(/\s*\*/, ' *').to_s else res = first_line ? "* #{line}" : " #{line}" first_line = false res end end log_entries << entry end log = log_entries.join("\n") date = Time.now.strftime('%m/%d/%Y') log_entry = "### [#{next_version}] - #{date}\n#{log}" puts "logmessages:\n#{log}" ['CHANGELOG.md'].each do |file| File.open(file, 'w') { |f| f.write('# Changelog') } unless File.exist?(file) text = File.read(file) new_contents = text.gsub(/^#\sChangelog/, "# Changelog\n\n#{log_entry}") File.open(file, 'w') { |f| f.puts new_contents } end end
class AddFieldsToUsers < ActiveRecord::Migration def change add_column :users, :first_name, :string add_column :users, :last_name, :string add_column :users, :is_coach, :boolean add_column :users, :token, :string add_column :users, :avatar, :string add_column :users, :phone, :string add_column :users, :language, :string add_column :users, :sport_id, :integer add_column :users, :credit_card_id, :integer add_column :users, :location_id, :integer add_column :users, :experience, :integer add_column :users, :qualification, :string add_column :users, :achievements, :string add_column :users, :description, :string end end
require_relative '../spec_helper' describe Codex::Entry do before do @id = 4242 @date = DateTime.now @content = 'Tu es un gros totoro !' @param = { id: @id, date: @date, content: @content } @subject = Codex::Entry.new(**@param) end describe '#date' do it 'returns the right date' do _(@subject.date).must_equal @date end end describe '#content' do it 'returns the right content' do _(@subject.content).must_equal @content end end end
# Copyright 2010 Mark Logic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "yaml" require 'ActiveDocument/mark_logic_http' require 'ActiveDocument/corona_interface' require "ActiveDocument/finder" module ActiveDocument # This class is used to manage the configuration of MarkLogic. It can create, list and change / delete a variety of # configuration options including indexes namespaces and fields class DatabaseConfiguration attr_reader :namespaces # @param yaml_file [The yaml file containing the configuration information for the server connection] def self.initialize(yaml_file) config = YAML.load_file(yaml_file) @@ml_http = ActiveDocument::MarkLogicHTTP.new(config['uri'], config['user_name'], config['password']) @@namespaces = Hash.new end # @param namespaces [a Hash of namespaces prefixes to namespaces] def self.define_namespaces(namespaces) namespaces.keys.each do |key| corona_array = ActiveDocument::CoronaInterface.declare_namespace(key, namespaces[key]) @@ml_http.send_corona_request(corona_array[0], corona_array[1]) end end # @param prefix [The prefix for which you wish to find a matching namespace] # @return The matching namespace as a string or nil if there is no matching namespace for the prefix def self.lookup_namespace(prefix) corona_array = ActiveDocument::CoronaInterface.lookup_namespace(prefix) begin @@ml_http.send_corona_request(corona_array[0], corona_array[1]) rescue Exception => exception if exception.response.code == "404" nil #return nil when no namespace is found else raise exception end end end def self.delete_all_namespaces corona_array = ActiveDocument::CoronaInterface.delete_all_namespaces begin @@ml_http.send_corona_request(corona_array[0], corona_array[1]) rescue Exception => exception if exception.response && exception.response.code == "404" nil else raise exception end end end end end
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :first_name, null: false t.string :last_name, null: false t.string :email, null: false t.integer :id_number t.string :current_homeroom t.string :password_digest t.boolean :admin, default: false t.integer :grade_level, null: false t.timestamps null: false end end end
class Order < ActiveRecord::Base belongs_to :table has_and_belongs_to_many :foods end
# encoding: utf-8 #============================================================================== # ■ 共有スイッチ・変数スクリプトさん #------------------------------------------------------------------------------ # 2021/12/15 Ruたん #------------------------------------------------------------------------------ # 指定のスイッチ・変数をゲーム全体で共有するようにします。 # # 共有されたスイッチ・変数は、値が変更されると、 # オートセーブのように直ちに共有セーブに反映されます。 # (正確には約1/60秒後に保存されます) #------------------------------------------------------------------------------ # 【更新履歴】 # 2021/12/15 作成 #============================================================================== #============================================================================== # ● 設定項目 #============================================================================== module Torigoya module SharedData module Config # 共有セーブのファイル名 FILENAME = 'shared.rvdata2' # 共有するスイッチのID(複数登録する場合はカンマ区切り) SWITCH_IDS = [ 1, 2 ] # 共有する変数のID(複数登録する場合はカンマ区切り) VARIABLE_IDS = [ 1, 2 ] end end end #============================================================================== # ↑   ここまで設定   ↑ # ↓ 以下、スクリプト部 ↓ #============================================================================== #============================================================================== # ■ Shared #============================================================================== module Torigoya module SharedData #-------------------------------------------------------------------------- # ● 共有データ #-------------------------------------------------------------------------- class Item attr_accessor :changed #-------------------------------------------------------------------------- # ● 初期化 #-------------------------------------------------------------------------- def initialize(default_value = 0) @data = {} @default_value = default_value @changed = false end #-------------------------------------------------------------------------- # ● データの取得 #-------------------------------------------------------------------------- def [](id) @data[id] || @default_value end #-------------------------------------------------------------------------- # ● データの登録 #-------------------------------------------------------------------------- def []=(id, value) return if @data[id] == value @changed = true @data[id] = value end #-------------------------------------------------------------------------- # ● 内容に変更があるか? #-------------------------------------------------------------------------- def changed? !!@changed end end #-------------------------------------------------------------------------- # ● 共有データセット(スイッチ・変数) #-------------------------------------------------------------------------- class ItemSet attr_reader :shared_switch attr_reader :shared_variable #-------------------------------------------------------------------------- # ● 初期化 #-------------------------------------------------------------------------- def initialize @shared_switch = Item.new(false) @shared_variable = Item.new(0) end #-------------------------------------------------------------------------- # ● 内容に変更があるか? #-------------------------------------------------------------------------- def changed? @shared_switch.changed? || @shared_variable.changed? end alias changed changed? #-------------------------------------------------------------------------- # ● 内容変更フラグの設定 #-------------------------------------------------------------------------- def changed=(value) @shared_switch.changed = @shared_variable.changed = value end end class << self #-------------------------------------------------------------------------- # ● 共有データの取得 #-------------------------------------------------------------------------- def data @data ||= begin File.open(filename, 'rb') { |f| Marshal.load(f) }.tap do |data| raise unless data.kind_of?(Torigoya::SharedData::ItemSet) end rescue => e puts e.inspect Torigoya::SharedData::ItemSet.new end end #-------------------------------------------------------------------------- # ● 共有データの保存 # 内容に変更がない場合は保存処理を行わない #-------------------------------------------------------------------------- def save return unless data.changed? data.changed = false File.open(filename, 'wb') { |f| f.write Marshal.dump(data) } end #-------------------------------------------------------------------------- # ● 共有データのファイル名 #-------------------------------------------------------------------------- def filename Torigoya::SharedData::Config::FILENAME end end end end #============================================================================== # ■ Game_Switches #============================================================================== class Game_Switches #-------------------------------------------------------------------------- # ● スイッチの取得(エイリアス) #-------------------------------------------------------------------------- alias torigoya_shared_data__get [] def [](switch_id) if Torigoya::SharedData::Config::SWITCH_IDS.include?(switch_id) return Torigoya::SharedData.data.shared_switch[switch_id] end torigoya_shared_data__get(switch_id) end #-------------------------------------------------------------------------- # ● スイッチの設定(エイリアス) #-------------------------------------------------------------------------- alias torigoya_shared_data__set []= def []=(switch_id, value) if Torigoya::SharedData::Config::SWITCH_IDS.include?(switch_id) Torigoya::SharedData.data.shared_switch[switch_id] = value end torigoya_shared_data__set(switch_id, value) end end #============================================================================== # ■ Game_Variables #============================================================================== class Game_Variables #-------------------------------------------------------------------------- # ● 変数の取得(エイリアス) #-------------------------------------------------------------------------- alias torigoya_shared_data__get [] def [](variable_id) if Torigoya::SharedData::Config::VARIABLE_IDS.include?(variable_id) return Torigoya::SharedData.data.shared_variable[variable_id] end torigoya_shared_data__get(variable_id) end #-------------------------------------------------------------------------- # ● 変数の設定(エイリアス) #-------------------------------------------------------------------------- alias torigoya_shared_data__set []= def []=(variable_id, value) if Torigoya::SharedData::Config::VARIABLE_IDS.include?(variable_id) Torigoya::SharedData.data.shared_variable[variable_id] = value end torigoya_shared_data__set(variable_id, value) end end #============================================================================== # ■ Scene_Base #============================================================================== class Scene_Base #-------------------------------------------------------------------------- # ● フレーム更新(基本)(エイリアス) #-------------------------------------------------------------------------- alias torigoya_shared_data__update_basic update_basic def update_basic Torigoya::SharedData.save torigoya_shared_data__update_basic end end
=begin 1. Сделать хеш, содеращий месяцы и количество дней в месяце. В цикле выводить те месяцы, у которых количество дней ровно 30 =end months = {January: 31, February: 28, March: 31, April: 30, May: 31, June: 30, July: 31, August: 31, September: 30, October: 31, November:30, December: 31} puts months.select{|month, days| days == 30}
module Fog module Compute class Google class InstanceGroupManagers < Fog::Collection model Fog::Compute::Google::InstanceGroupManager def all(zone: nil, filter: nil, max_results: nil, order_by: nil, page_token: nil) opts = { :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token } if zone data = service.list_instance_group_managers(zone, **opts).items || [] else data = [] service.list_aggregated_instance_group_managers(**opts).items.each_value do |group| data.concat(group.instance_group_managers) if group.instance_group_managers end end load(data.map(&:to_h)) end def get(identity, zone = nil) if zone instance_group_manager = service.get_instance_group_manager(identity, zone).to_h return new(instance_group_manager) elsif identity response = all(:filter => "name eq .*#{identity}", :max_results => 1) instance_group_manager = response.first unless response.empty? return instance_group_manager end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end
class E # shorthand for `response.set_cookie` and `response.delete_cookie`. # also it allow to make cookies readonly. def cookies @__e__cookies_proxy ||= Class.new do def initialize controller @controller, @request, @response = controller, controller.request, controller.response end # set cookie header # # @param [String, Symbol] key # @param [String, Hash] val # @return [Boolean] def []= key, val return if readonly? @response.set_cookie key, val end # get cookie by key def [] key @request.cookies[key] end # instruct browser to delete a cookie # # @param [String, Symbol] key # @param [Hash] opts # @return [Boolean] def delete key, opts ={} return if readonly? @response.delete_cookie key, opts end # prohibit further cookies writing # # @example prohibit writing for all actions # before do # cookies.readonly! # end # # @example prohibit writing only for :render and :display actions # before :render, :display do # cookies.readonly! # end def readonly! @readonly = true end def readonly? @readonly end def method_missing *args @request.cookies.send *args end end.new self end end
module Ricer::Plug::Params class UserParam < TargetParam def default_options; { online: nil, channels: '0', users: '1', multiple: '0', connectors: '*' }; end end end
Rails.application.routes.draw do root 'welcome#index' resources :trainer1 get 'trainer1', to: 'trainer1#christy', as: 'christy' get 'trainer2', to: 'trainer2#natalia', as: 'natalia' get 'trainer3', to: 'trainer3#nola', as: 'nola' get 'trainer4', to: 'trainer4#elyssa', as: 'elyssa' get 'trainer5', to: 'trainer5#geovany', as: 'geovany' namespace :api do namespace :v1 do resources :coaches, only: [:index, :create, :destroy, :update] end end # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
class Artist attr_reader :name, :years_experience @@all = [] def initialize(name, years_experience) @name = name @years_experience = years_experience @@all << self end def self.all # Returns an array of all the artists @@all end def paintings # Returns an array all the paintings by an artist Painting.all.select{|painting| painting.artist == self} end def galleries # Returns an array of all the galleries that an artist has paintings in self.paintings.map{|painting| painting.gallery}.uniq end def cities # Return an array of all cities that an artist has paintings in self.paintings.map{|painting| painting.gallery.city}.uniq end def self.total_experience # Returns an integer that is the total years of experience of all artists self.all.sum{|artist| artist.years_experience} end def self.most_prolific # Returns an instance of the artist with the highest amount of paintings per year of experience. self.all.max_by{|artist| artist.paintings.length / artist.years_experience } end def create_painting(title, price, gallery) # Given the arguments of title, price and gallery, creates a new painting belonging to that artist Painting.new(title, price, self, gallery) end end
# frozen_string_literal: true require 'spec_helper' RSpec.describe AsciiDetector::Fields::FieldBase do let(:input) do [ [0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0] ] end subject { described_class.new(input) } describe '#new' do context 'when argument is 2D Array' do it 'returns instance' do is_expected.to be_an_instance_of(described_class) end end context 'when argument 1D Array' do let(:input) { [1, 2, 3] } it 'raises ArgumentError exception' do expect { is_expected }.to raise_error(ArgumentError, 'input must be 2D array') end end context 'when argument has wrong type' do let(:input) { 'foo' } it 'raises ArgumentError exception' do expect { is_expected }.to raise_error(ArgumentError, 'input must be 2D array') end end end describe '#height' do it 'returns count of rows' do expect(subject.height).to eq(input.count) end end describe '#width' do it 'returns count of the first subarray' do expect(subject.width).to eq(input.first.count) end end describe '#to_s' do it 'returns muliline string representation of array' do expect(subject.to_s).to eq("00100\n01110\n00100\n00000") end end end
class Reputable::PointCap < ActiveRecord::Base set_table_name :reputable_caps # returns the proper number of points a user can earn from a given action and cap (if present) def self.remaining_points event cap = find_by_key event.action award = App.reputable_point_values[event.action.to_s] return award unless cap current_points = Reputable::Event.sum(:points, :conditions => ["action = ? and user_id = ? and created_at > ?", event.action, event.user.id, cap_frequency(cap.frequency)]) if (current_points + award) <= cap.value award else cap.value - current_points end end protected def self.cap_frequency freq case freq when 'month' then Time.now.beginning_of_month when 'all_time' then Time.parse('01/01/00') else Time.now.beginning_of_month end end end
json.array!(@stores) do |store| json.extract! store, :id, :name, :address_name, :street, :zip, :city, :phone, :email, :active json.url store_url(store, format: :json) end
module LatencyStats class Histogram attr_reader :data, :settings def initialize(data, settings) @data = data @settings = settings end end end
class Source::Wikipedia < Source::Base class << self def extract_query(href) CGI::unescape(href.scan(/wiki\/(.*)/).last.pop.humanize) end end end
require 'rails_helper' RSpec.describe ExamResult, type: :model do it { should belong_to(:student).class_name('User') } it { should belong_to(:teacher).class_name('User') } it { should belong_to(:question) } it 'should filter by teacher' do teacher = create(:teacher) result = create(:exam_result, {teacher: teacher}) expect(ExamResult.by_teacher(teacher.id)).to include(result) end it 'should filter by correct answer' do student = create(:student) correct = create(:correct_answer_result, {student: student}) expect(ExamResult.correct).to include(correct) end it 'should filter wrong answer' do student = create(:student) wrong = create(:wrong_answer_result, {student: student}) expect(ExamResult.wrong).to include(wrong) end describe 'compare teacher and student answer' do # matching_answers(teacher_answer, student_answer) it 'small and big letter should be ok' do expect(ExamResult.matching_answers('BIG', 'big')).to eq(true) end it 'number answer by student and words number by teacher should be ok' do expect(ExamResult.matching_answers('five', '5')).to eq(true) end it 'number answer by teacher and number words by student should be ok' do expect(ExamResult.matching_answers('5', 'five')).to eq(true) end it 'integer number answer by teacher and number words by student should be ok' do expect(ExamResult.matching_answers(5, 'five')).to eq(true) end it 'number answer by teacher and integer number by student should be ok' do expect(ExamResult.matching_answers('5', 5)).to eq(true) end it 'not equal string should not be correct' do expect(ExamResult.matching_answers('BIG', 'small')).to eq(false) end it 'not equal integer should not be correct' do expect(ExamResult.matching_answers('5', 3)).to eq(false) end end end
class Playlist def self.<<(song) songs << song end def self.songs @@songs ||= [] end def self.pop songs.delete_at(0) end end
require 'spec_helper' module Alchemy describe UserSessionsController do let(:user) { FactoryGirl.create(:admin_user) } let(:alchemy_page) { FactoryGirl.create(:page) } before { sign_in :user, user } describe "signout" do it "should unlock all pages" do @request.env["devise.mapping"] = Devise.mappings[:user] alchemy_page.lock(user) delete :destroy user.locked_pages.should be_empty end end end end
require "features_helper" RSpec.feature "To test Forgot password functionality", type: :feature do let(:owner) { create(:admin, :power_user) } login_page = AdminPage::Sessions::New.new forgot_password = AdminPage::Passwords::New.new it "Owner should be able to click on Forgot password Link" do visit root_path login_page.click_forgot_password_link forgot_password.assert_forgot_password_landing_page end describe "Owner Provides valid login data and click on forgot password link" do it "Verify Owner should be able to click on Forgot password Link " do visit root_path login_page.set_email_text_box(owner.email) login_page.set_password_text_box(owner.password) login_page.click_forgot_password_link forgot_password.assert_forgot_password_landing_page forgot_password.do_reset_password(owner.email) end end it "verify Login link in Forgot password Page" do visit root_path login_page.click_forgot_password_link forgot_password.click_login_link expect(page).to have_content("Login") end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| # SHARED PROVISIONING config.vm.provision "shell", inline: <<-SHELL echo "Hello world! Starting deploy procedures." sudo apt-get install -qy apt-transport-https sudo apt-key adv --keyserver hkp://pgp.mit.edu:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D sudo bash -c "echo 'deb https://apt.dockerproject.org/repo debian-jessie main' > /etc/apt/sources.list.d/docker.list" sudo apt-get update sudo apt-get install -qy docker-engine sudo service docker start sudo bash -c "curl -L https://github.com/docker/compose/releases/download/1.5.0rc1/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose" sudo chmod +x /usr/local/bin/docker-compose sudo apt-get install -qy vim emacs24 ln -s /vagrant/ ~/dev SHELL config.vm.define "ci" do |ci| ci.vm.hostname = "ci" ci.vm.box = "debian/jessie64" ci.vm.network "private_network", ip: "192.168.33.50" ci.vm.network "private_network", ip: "192.168.33.50", virtualbox__intnet: true ci.vm.provider "virtualbox" do |vb| vb.gui = false vb.memory = "4096" vb.cpus = 4 end ci.vm.provision "shell", inline: <<-SHELL echo "CI started" sh -c "wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add -" sh -c 'echo "deb http://pkg.jenkins-ci.org/debian binary/" >> /etc/apt/sources.list' sudo apt-get update sudo apt-get install -qy jenkins SHELL end end
class Trip < ApplicationRecord belongs_to :user has_many :tripgears has_many :gears, through: :tripgears end
require 'easy_extensions/easy_xml_data/importables/importable' module EasyXmlData class WorkflowRuleImportable < Importable def initialize(data) @klass = WorkflowRule super @belongs_to_associations['tracker_id'] = 'tracker' end def mappable? false end private def before_record_save(workflow_rule, xml, map) !workflow_rule.tracker_id.blank? && !workflow_rule.role_id.blank? && !workflow_rule.old_status.blank? && !workflow_rule.new_status.blank? end end end
class ApplicationController < ActionController::Base protect_from_forgery def after_sign_in_path_for(resource) if current_show show_dashboard_path(current_show.id) else root_path if current_user end end end
class ApplicationController < ActionController::Base include ApplicationHelper #before_filter :block_ip_addresses, :except => [:click_through] protect_from_forgery with: :exception # Captures info from 404 errors and submits the info into the table # Crawlers. Alternatively, if the info cannot be entered into the database, # the controller will make a note of the crawler in the log file. # def page_not_found params = { ip_address: request.ip, access_path: request.path, browser_type: browser.to_s, is_it_a_bot: browser.bot?.to_bool } if Crawler.create!(params) logger.info "awesome!" else logger.warn("\n\nCrawler on #{Date.today}:"\ "\n\tIp Address: #{request.ip}"\ "\n\Access Path: #{request.path}"\ "\n\tBrowser Type: #{browser.to_s}"\ "\n\tIs it a bot? #{browser.bot?}\n\n\n") end redirect_to "http://sweeps-support.com" end end
module AppConfig module Processor # Process string value def process_string(value) value.strip end # Process array of strings def process_array(value) value.split("\n").map { |s| s.to_s.strip }.compact.select { |s| !s.empty? } end # Parse boolean string def process_boolean(value) ['true', 'on', 'yes', 'y', '1'].include?(value.to_s.downcase) end # Parse hash string # value should be in the following format: # "keyname: value, key2: value2" def process_hash(value) result = {} unless value.empty? value.split(",").each do |s| k,v = s.split(':').compact.map { |i| i.to_s.strip } result[k] = v.to_s end end result end # Process data value for the format def process(data, type) raise InvalidType, 'Type is invalid!' unless FORMATS.include?(type) send("process_#{type}".to_sym, data.to_s) end end end
class DefaultDonetoFalse < ActiveRecord::Migration def up change_column_default(:todos, :done, false) end def down change_column_default(:todos, :done, nil) end end
# encoding: binary # frozen_string_literal: true RSpec.describe RbNaCl::PasswordHash::SCrypt do let(:reference_password) { vector :scrypt_password } let(:reference_salt) { vector :scrypt_salt } let(:reference_opslimit) { RbNaCl::TEST_VECTORS[:scrypt_opslimit] } let(:reference_memlimit) { RbNaCl::TEST_VECTORS[:scrypt_memlimit] } let(:reference_digest) { vector :scrypt_digest } it "calculates the correct digest for a reference password/salt" do digest = RbNaCl::PasswordHash.scrypt( reference_password, reference_salt, reference_opslimit, reference_memlimit ) expect(digest).to eq reference_digest end end
json.array!(@users) do |user| json.extract! user, :id, :user_day_since_last, :user_day_since_first, :user_returning, :user_visit_count json.url user_url(user, format: :json) end
class QuestionsController < ApplicationController include Voted before_action :authenticate_user!, except: [ :show, :index ] before_action :load_question, only: [ :show, :edit, :update, :destroy, :vote ] before_action :build_answer, only: :show after_action :publish_question, only: [ :create ] authorize_resource def index @vote = Vote.new gon.current_user = current_user || false respond_with(@questions = Question.all) end def show @best = @question.answers.best.first gon.current_user = current_user || false gon.question = @question respond_with @question end def new respond_with(@question = Question.new) end def edit end def create respond_with(@question = current_user.questions.create(question_params)) end def update @question.update(question_params) end def destroy respond_with(@question.destroy, location: questions_path) end private def load_question @question = Question.find(params[:id]) end def question_params params.require(:question).permit(:title, :body, attachments_attributes: [:file, :id, :_destroy]) end def publish_question return if @question.errors.any? renderer = ApplicationController.renderer.new renderer.instance_variable_set(:@env, { "HTTP_HOST"=>"localhost:3000", "HTTPS"=>"off", "REQUEST_METHOD"=>"GET", "SCRIPT_NAME"=>"", "warden" => warden }) ActionCable.server.broadcast( 'questions', @question.to_json ) end def build_answer @answer = @question.answers.new end end
class Booking < ActiveRecord::Base BOOKING_STATUS = ["Booked", "Cancelled"] belongs_to :lodge belongs_to :room end
class AddFieldsToTradeRequests < ActiveRecord::Migration[5.0] def change add_column :trade_requests, :user_id, :integer, null: false add_column :trade_requests, :type, :string, null: false add_column :trade_requests, :profit, :string, null: false add_column :trade_requests, :location, :string, null: false change_column_null :trade_requests, :name, false end end
RSpec.describe Evil::Client::Middleware::StringifyMultipart do let(:app) { double :app } let(:type) { "file" } let(:env) do { format: "multipart", headers: {}, files: [ { file: StringIO.new('{"text":"Hello!"}'), type: MIME::Types["application/json"].first, charset: "utf-16", filename: "greetings.json" } ] } end def update!(result) @result = result end before { allow(app).to receive(:call) { |env| update!(env) } } subject { described_class.new(app).call(env) } context "with a multipart format:" do let(:body_string) { @result[:body_string] } it "builds multipart body_string" do subject expect(body_string).to include '{"text":"Hello!"}' end it "uses name and filename" do subject expect(body_string).to include "Content-Disposition: form-data;" \ ' name="AttachedFile1";' \ ' filename="greetings.json"' end it "uses content-type and charset" do subject expect(body_string) .to include "Content-Type: application/json; charset=utf-16" end it "adds the header" do subject expect(@result[:headers]["content-type"]) .to include "multipart/form-data; boundary=" end end context "with non-multipart format:" do before { env[:format] = "json" } it "does nothing" do subject expect(@result).to eq env end end end
#question folloqws require_relative 'student_questions' require 'sqlite3' require 'singleton' require 'byebug' class QuestionFollows attr_reader :id, :question_id, :user_id def self.find_by_id(id) reply = QuestionsDatabase.instance.execute(<<-SQL, id) SELECT * FROM question_follows WHERE id = ? SQL return nil unless id > 0 QuestionFollows.new(reply.first) end def self.all data = QuestionsDatabase.instance.execute("SELECT * FROM question_follows") data.map { |datum| QuestionFollows.new(datum) } end def initialize(options) @id = options['id'] @question_id = options['question_id'] @user_id = options['user_id'] end def create raise "#{self} already in database" if @id QuestionsDatabase.instance.execute(<<-SQL, @question_id, @user_id) INSERT INTO question_follows (question_id, user_id) VALUES (?, ?) SQL @id = QuestionsDatabase.instance.last_insert_row_id end def update raise "#{self} not in database" unless @id QuestionsDatabase.instance.execute(<<-SQL, @question_id, @user_id, @id) UPDATE question_follows SET question_id = ?, user_id = ? WHERE id = ? SQL end end
class Word < ActiveRecord::Base belongs_to :language belongs_to :meaning has_many :originals, :class_name => "Play", :foreign_key => "original_id" has_many :translations, :class_name => "Play", :foreign_key => "translation_id" has_many :histories has_many :users, through: :histories scope :meaning_order, -> { order('meaning_id') } GRACE_PERIOD = 5 # defines user just getting started HIGH_SUCCESS_RATE = 0.8 NEW_WORD_RATE = 10 def self.import(file) CSV.foreach(file.path, headers: true) do |row| process_imported(row) end end def self.process_imported(row) row_hash = row.to_hash spelling = row_hash['SPELLING'] meaning = row_hash['MEANING'] language = row_hash['LANGUAGE'] if language.present? #don't add langauges on the fly language_id = Language.where(name: language).first end if language_id.present? && meaning.present? && spelling.present? #add on the fly meaning_id = Meaning.where(denotation: meaning.capitalize).first_or_create.id Word.where(language_id: language_id, meaning_id: meaning_id, spelling: spelling.capitalize).first_or_create end end def self.next_word_for(user) if !user.premium? random_word_for(user) else #only check history of words in from_language histories = user.histories.select{|m| m.word.language_id == user.from_language_id} if (histories.count < GRACE_PERIOD) random_word_for(user) else overall_success_rate = histories.map(&:successes).sum.to_f / histories.map(&:tries).sum.to_f #if user has a high success rate, pick a word at random, #which most likely (but not always) will be a new word #for use with a low success rate, mostly go back to words #alreadty seen, but throw in new word on random occasions if (overall_success_rate > HIGH_SUCCESS_RATE) || (rand(NEW_WORD_RATE) == 0) random_word_for(user) else pick_word_from(histories) end end end end def self.pick_word_from(histories) #create an array with the words frequency based on its repeat rate #tk this should restrict word to the langguage now translating from weighted = [] histories.each do |h| h.repeat_rate.times do weighted << h.word end end weighted[rand(weighted.count)] end def self.random_word_for(user) Word.where(language_id: user.from_language_id).order('Random()').first end def history_for(user) History.where(word_id: id, user_id: user.id) end end
#!/usr/bin/env rake # -*- coding: utf-8 -*- require 'rake' require 'highline/import' task :default => :travis task :travis => [:spec, :rubocop, 'coveralls:push'] require 'rspec/core/rake_task' require 'rubocop/rake_task' require 'coveralls/rake/task' Coveralls::RakeTask.new RSpec::Core::RakeTask.new(:spec) do |t| t.pattern = 'spec/**/*_spec.rb' end RuboCop::RakeTask.new(:rubocop) do |task| task.patterns = %w(lib/**/*.rb spec/**/*.rb) end task :release do |t| puts "Releaseing gem" require_relative 'lib/lbspec' version_current = Lbspec::VERSION puts "now v#{version_current}" version_new = ask("Input version") file_path = 'lib/lbspec/version.rb' text = File.read(file_path) text = text.gsub(/#{version_current}/, version_new) File.open(file_path, "w") {|file| file.puts text} sh('gem build lbspec.gemspec') if agree("Shall we continue? ( yes or no )") puts "Pushing gem..." sh("gem push lbspec-#{version_new}.gem") else puts "Exiting" end end
class TodosController < ApplicationController before_action :set_todo, only: [:show, :destroy] def index @todos = current_user.todos @todo = Todo.new end def show; end def new @todo = Todo.new end def create @todo = Todo.new(todo_params) @todo.user_id = current_user.id if @todo.save redirect_to todos_path else render "new" end end def destroy @todo.destroy redirect_to end private def set_todo @todo = Todo.find(params[:id]) end def todo_params params.require(:todo).permit(:name, :due_date, :completed) end end
class MoonsController < ApplicationController before_action :get_moon, only: [:show, :edit, :update, :destroy] before_action :check_if_logged_in, except: [:index, :show] def new @moon = Moon.new end def create @moon = Moon.new moon_params @moon.save if @moon.persisted? redirect_to moons_path else flash[:errors] = @moon.errors.full_messages redirect_to new_moon_path end end def index @moons = Moon.all end def show end def edit end def update @moon.update moon_params redirect_to moons_path end def destroy @moon.destroy redirect_to moons_path end private def moon_params params.require(:moon).permit(:name, :description, :image_url, :planet_id) end def get_moon @moon = Moon.find params[:id] end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }]) # Mayor.create(:name => 'Daley', :city => cities.first) [ {:title => "BlogApp", :description => "Simple Blog App in Rails", :status => "Pending", :deadline => "2012-2-2"}, {:title => "Student Management", :description => "Manage Students in School", :status => "Pending", :deadline => "2012-2-2"}, {:title => "Hotel Management", :description => "Manage Students in School", :status => "Pending", :deadline => "2012-2-2"}, {:title => "Hospital Management", :description => "Manage Students in School", :status => "Pending", :deadline => "2012-2-2"} ].each do |attrs| project= Project.find_or_create_by_title(attrs) end [ {:name => "Ram", :email => "ram@email.com", :password => "password" }, {:name => Faker::Name.name, :email => Faker::Internet.email, :password => "password" }, {:name => Faker::Name.name, :email => Faker::Internet.email, :password => "password" }, {:name => Faker::Name.name, :email => Faker::Internet.email, :password => "password" } ].each do |attr| person= Person.find_or_create_by_name(attr) end [ {:name => "Pending" }, {:name => "Ongoing" }, {:name => "Finished" } ].each do |attrb| person= TaskCategory.find_or_create_by_name(attrb) end
class MembersController < ApplicationController # GET /members # GET /members.json before_filter :require_user#, :only => :not_allowed before_filter :require_admin, :only => [:index, :show, :new, :create, :edit, :create, :update, :destroy] def index @members = Member.all respond_to do |format| format.html # index.html.erb format.json { render :json => @members } end end def visual @members = Member.all.map! {|x| if x.visits.today!=[]; x end} if @members.any? {|x| x==nil} @members.delete(nil) end @members=@members.sort! {|a,b| a.visits.today.recent[0].local_time<=> b.visits.today.recent[0].local_time} end # GET /members/1 # GET /members/1.json def show @member = Member.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render :json => @member } end end # GET /members/new # GET /members/new.json def new @member = Member.new respond_to do |format| format.html # new.html.erb format.json { render :json => @member } end end # GET /members/1/edit def edit @member = Member.find(params[:id]) end # POST /members # POST /members.json def create @member = Member.new(params[:member]) respond_to do |format| if @member.save add_plan_to_user_if_specified! format.html { redirect_to(@member, :notice => 'Member was successfully created.') } format.json { render :json => @member, :status => :created, :location => @member } else format.html { render :action => "new" } format.json { render :json => @member.errors, :status => :unprocessable_entity } end end end # PUT /members/1 # PUT /members/1.json def update @member = Member.find(params[:id]) respond_to do |format| if @member.update_attributes(params[:member]) add_plan_to_user_if_specified! format.html { redirect_to(@member, :notice => 'Member was successfully updated.') } format.json { head :ok } else format.html { render :action => "edit" } format.json { render :json => @member.errors, :status => :unprocessable_entity } end end end # DELETE /members/1 # DELETE /members/1.json def destroy @member = Member.find(params[:id]) @member.destroy respond_to do |format| format.html { redirect_to(members_url) } format.json { head :ok } end end private def add_plan_to_user_if_specified! if params[:plan_id].present? @member.plans.delete_all @member.plans << Plan.find(params[:plan_id]) end end end
class Api::V1::PrayersController < ApplicationController def create entry = Entry.find(params[:entry_id]) prayer = entry.prayers.build(prayer_params) if prayer.valid? entry.save render :json => PrayerSerializer.new(prayer), status: :accepted else #error message render :json => {errors: prayer.errors.full_messages}, status: :unprocessible_entity end end # def update # entry = Entry.find(params[:entry_id]) # prayer = Prayer.find(params[:id]) # if prayer.update(prayer_params) # prayer.save # render :json => {prayer: PrayerSerializer.new(prayer), entry: EntrySerializer.new(entry)}, status: :accepted # else # #error message # render :json => {errors: prayer.errors.full_messages}, status: :unprocessible_entity # end # end private def prayer_params params.require(:prayer).permit(:user_id, :entry_id, :prayed) end end
# frozen_string_literal: true class Message < ApplicationRecord belongs_to :user belongs_to :room, counter_cache: true validates :content, presence: true, length: { maximum: 4000 } scope :unread_by_room_user, ->(room_id, last_read_message_id) { query = where(room_id: room_id) query = query.where('id > ?', last_read_message_id) if last_read_message_id query } scope :not_muted, ->(room_id) { query = where(room_id: room_id) query = query.where.not( user_id: MutedRoomUser.where(room_id: room_id).pluck(:user_id) ) query } def author user.username end end
# frozen_string_literal: true require 'test_helper' class NewsletterMailerTest < ActionMailer::TestCase def test_newsletter mail = NewsletterMailer.newsletter(news_items(:first), members(:lars)) assert_equal 'My first news item', mail.subject assert_equal %w[lars@example.com], mail.to assert_equal %w[noreply@test.jujutsu.no], mail.from assert_match 'Har du problemer', mail.body.encoded end end
class MakeOAuthAccountsUserIdNullable < ActiveRecord::Migration[5.1] def change change_column_null :oauth_accounts, :user_id, true end end
# == Schema Information # # Table name: shortened_urls # # id :integer not null, primary key # long_url :string # short_url :string # submitter_id :integer # created_at :datetime # updated_at :datetime # class ShortenedUrl < ActiveRecord::Base validates :submitter_id, :long_url, :presence => true validates :short_url, :presence => true, :uniqueness => true def self.random_code short_url = nil while short_url.nil? || self.exists?(:short_url => short_url) short_url = SecureRandom::urlsafe_base64 end short_url end def self.create_for_user_and_long_url!(user_id,long_url) ShortenedUrl.create!(submitter_id: user_id,long_url: long_url, short_url: ShortenedUrl.random_code) end belongs_to( :user, class_name: :User, foreign_key: :submitter_id, primary_key: :id ) has_many( :visits, class_name: :Visit, primary_key: :id, foreign_key: :short_url_id ) has_many( :visitors, Proc.new{distinct}, through: :visits, source: :user ) def num_clicks visitors.count end def num_uniques visitors.distinct.count end # def num_recent_uniques # visitors.where(created_at: 10.minutes.ago..Time.now).distinct.count # end end
require_relative 'graph' require 'byebug' # Implementing topological sort using both Khan's and Tarian's algorithms # Khan's topological sorting algorithms def topological_sort(vertices) next_vertex = Queue.new result = [] vertices.each do |vertex| next_vertex.push(vertex) if vertex.in_edges.length < 1 end while !next_vertex.empty? vertex = next_vertex.pop vertex.out_edges.each do |edge| new_vertex = edge.to_vertex next_vertex.push(new_vertex) if new_vertex.in_edges.length <= 1 end vertex.out_edges.each{|edge| edge.destroy!} result.push(vertex) end result end
#!/usr/bin/env ruby # frozen_string_literal: true require_relative 'example_helper' require 'benchmark' WORDS = File.readlines('/usr/share/dict/words').map(&:chomp).freeze COUNT = WORDS.count module Common def main_loop if output[:current] < input[:limit] consumed = yield output[:current] += consumed plan_event(nil) suspend end end def batch WORDS.drop(output[:current]).take(input[:chunk]) end end class Regular < ::Dynflow::Action include Common def run(event = nil) output[:current] ||= 0 output[:words] ||= [] main_loop do words = batch output[:words] << words words.count end end end class Chunked < ::Dynflow::Action include Common def run(event = nil) output[:current] ||= 0 main_loop do words = batch output_chunk(words) words.count end end end if $0 == __FILE__ ExampleHelper.world.action_logger.level = 4 ExampleHelper.world.logger.level = 4 Benchmark.bm do |bm| bm.report('regular 1000 by 100') { ExampleHelper.world.trigger(Regular, limit: 1000, chunk: 100).finished.wait } bm.report('chunked 1000 by 100') { ExampleHelper.world.trigger(Chunked, limit: 1000, chunk: 100).finished.wait } bm.report('regular 10_000 by 100') { ExampleHelper.world.trigger(Regular, limit: 10_000, chunk: 100).finished.wait } bm.report('chunked 10_000 by 100') { ExampleHelper.world.trigger(Chunked, limit: 10_000, chunk: 100).finished.wait } bm.report('regular 10_000 by 1000') { ExampleHelper.world.trigger(Regular, limit: 10_000, chunk: 1000).finished.wait } bm.report('chunked 10_000 by 1000') { ExampleHelper.world.trigger(Chunked, limit: 10_000, chunk: 1000).finished.wait } bm.report('regular 100_000 by 100') { ExampleHelper.world.trigger(Regular, limit: 100_000, chunk: 100).finished.wait } bm.report('chunked 100_000 by 100') { ExampleHelper.world.trigger(Chunked, limit: 100_000, chunk: 100).finished.wait } bm.report('regular 100_000 by 1000') { ExampleHelper.world.trigger(Regular, limit: 100_000, chunk: 1000).finished.wait } bm.report('chunked 100_000 by 1000') { ExampleHelper.world.trigger(Chunked, limit: 100_000, chunk: 1000).finished.wait } bm.report('regular 100_000 by 10_000') { ExampleHelper.world.trigger(Regular, limit: 100_000, chunk: 10_000).finished.wait } bm.report('chunked 100_000 by 10_000') { ExampleHelper.world.trigger(Chunked, limit: 100_000, chunk: 10_000).finished.wait } end end
require 'spec_helper' describe Vine::Authentication::TokenStrategy do include Rack::Test::Methods describe 'access w/ token' do it 'should return ok w/o an access token to unsecured endpoint' do get '/' expect(last_response.status).to eq(200) expect(JSON.parse(last_response.body)).to eq({"ok" => true}) end it 'should return unauthorized w/o an access token' do get '/secure' expect(last_response.status).to eq(401) expect(JSON.parse(last_response.body)).to eq({"error" => "access_denied"}) end it 'should return unauthorized w/ an invalid access token' do header 'Authorization', 'Bearer AbCdEf123456' get '/secure' expect(last_response.status).to eq(401) expect(JSON.parse(last_response.body)).to eq({"error" => "invalid_grant"}) end it 'should return unauthorized w/ an expired access token' do encoded_token = encode({test: '123', exp: 1.week.ago.to_i}) header 'Authorization', "Bearer #{encoded_token}" get '/secure' expect(last_response.status).to eq(401) expect(JSON.parse(last_response.body)).to eq({"error" => "token_expired"}) end it 'should allow access w/ a valid access token' do encoded_token = encode({test: '123'}) header 'Authorization', "Bearer #{encoded_token}" get '/secure' expect(last_response.status).to eq(200) expect(last_response.headers['Refresh-Token']).to be(nil) expect(JSON.parse(last_response.body)).to eq({"ok" => true}) end it 'should send a refresh token if a valid access token is about to expire' do encoded_token = encode({test: '123', exp: DateTime.now.to_i + 3.days.to_i}) header 'Authorization', "Bearer #{encoded_token}" get '/secure' expect(last_response.status).to eq(200) expect(Vine::Authentication::Token.valid? last_response.headers['Refresh-Token']).to eq(true) expect(JSON.parse(last_response.body)).to eq({"ok" => true}) end end describe 'access w/ token & scopes' do it 'should return unauthorized w/ a valid access token and no scopes' do encoded_token = encode({test: '123'}) header 'Authorization', "Bearer #{encoded_token}" get '/secured_with_scopes' expect(last_response.status).to eq(401) expect(JSON.parse(last_response.body)).to eq({"error" => "access_denied"}) end it 'should return unauthorized w/ a valid access token and different scopes' do encoded_token = encode({test: '123', scopes: ['customer']}) header 'Authorization', "Bearer #{encoded_token}" get '/secured_with_scopes' expect(last_response.status).to eq(401) expect(JSON.parse(last_response.body)).to eq({"error" => "access_denied"}) end it 'should allow access w/ a valid access token and scopes' do encoded_token = encode({test: '123', scopes: ['admin']}) header 'Authorization', "Bearer #{encoded_token}" get '/secured_with_scopes' expect(last_response.status).to eq(200) expect(last_response.headers['Refresh-Token']).to be(nil) expect(JSON.parse(last_response.body)).to eq({"ok" => true}) end end describe 'optional secure endpoints' do it 'should allow access w/ no access token but with securable option enabeled' do get '/optional_secure_enabled' expect(last_response.status).to eq(200) expect(JSON.parse(last_response.body)).to eq({"ok" => true}) end it 'should not allow access w/ no access token and securable option disabled' do get '/optional_secure_disabled' expect(last_response.status).to eq(401) end end end
# frozen_string_literal: true module TokyoApi class Campact < Base def base_path 'campact' end def full_user(session_id) client.get_request("#{normalized_base_path}full_user/#{url_escape(session_id)}").body end def session_status(session_id) client.get_request("/#{normalized_base_path}session/#{url_escape(session_id)}/status").body end def destroy_session(session_id) client.delete_request("/#{normalized_base_path}session/#{url_escape(session_id)}").status == 204 end def subscription_status(token) client.get_request(subscription_status_path(token)).body rescue Vertebrae::ResponseError => e # Status 404 is expected in these calls return nil if e.status_code == 404 raise end def user_path(session_id, petition_id:, with_subscription_status: false, required_fields: nil) path = String.new("/#{normalized_base_path}user/#{url_escape(session_id)}?petition_id=#{url_escape(petition_id)}") path << '&with_subscription_status=true' if with_subscription_status path << "&#{required_fields_param(required_fields)}" unless required_fields.nil? path end def subscription_status_path(token) "/#{normalized_base_path}subscription_status/#{url_escape(token)}" end end end
require 'rails_helper' RSpec.describe UserExamsController, :type => :controller do before do @user = FactoryGirl.create :user, email: "wp@wp.pl" sign_in @user FactoryGirl.create :course FactoryGirl.create :lesson_category FactoryGirl.create :exam FactoryGirl.create :question_category FactoryGirl.create :question QuestionCategory.create(name: 'a', exam_id: 1) FactoryGirl.create :attending end describe "GET new" do it "returns http success" do get :new, id: 1 expect(response).to have_http_status 200 end end describe "GET start" do it "creates new user exam" do expect do get :start, id: 1 end.to change{UserExam.count}.by 1 expect(assigns(:exam)).to eq Exam.first expect(response).to redirect_to question_user_exam_path end end describe "GET question" do before do get :start, id: 1 end it "returns http success" do get :question expect(response).to have_http_status(:success) end context "exam closed" do it "ends exam" do Exam.first.update_attribute(:duration, 1) allow(Time).to receive(:now) { Time.new + 5.minutes } get :question expect(UserExam.first.open?).to eq false expect(response).to redirect_to user_exam_path(1) end end end describe 'sample exam' do before do Question.destroy_all FactoryGirl.create(:question, name: "Czy ziemia jest płaska?", value: 2) Answer.create(name: "Tak", correct: false, question_id: 2) Answer.create(name: "Nie", correct: true, question_id: 2) FactoryGirl.create(:question, name: "Jakie programy domyślnie ma Łubuntu?", value: 2, form: 1) Answer.create(name: "Firefox", correct: true, question_id: 3) Answer.create(name: "Google Chrome", correct: false, question_id: 3) Answer.create(name: "LibreOffice Writer", correct: true, question_id: 3) Answer.create(name: "Microsoft Office Word", correct: false, question_id: 3) FactoryGirl.create(:question, name: "Jakiego koloru jest krew ludzka?", form: 2, value: 2) Answer.create(name: "Czerwonego", question_id: 4) Answer.create(name: "Czerwony", question_id: 4) get :start, id: 1 end context "valid answers" do before do 3.times do get :question case session[:current_question_id].to_i when 2 post :answer, answer: { id: '2' } when 3 post :answer, answer: { id: ['3', '', '', ''] } else post :answer, answer: { text: 'czerwony' } end end end it "makes correct result" do @ue = UserExam.first res = @ue.result @ue.update_result expect(@ue.result).to eq res expect(res).to eq 5 end it "renders show page" do get :show, id: 1 expect(response).to be_ok end end context "blank_answers" do it "creates user_answers" do expect do 3.times do get :question case session[:current_question_id].to_i when 2 post :answer, answer: { id: '' } when 3 post :answer, answer: { id: ['']} else post :answer, answer: { text: '' } end end end.to change{UserAnswer.count}.by(3) end end context "end of time" do it "redirects from exam" do expect do 3.times do |n| get :question UserExam.first.update_attribute(:closed, true) if n == 2 case session[:current_question_id].to_i when 2 post :answer, answer: { id: '' } when 3 post :answer, answer: { id: ['']} else post :answer, answer: { text: '' } end end end.to change{UserAnswer.count}.by(2) expect(:response).to redirect_to user_exam_path(1) end end end describe "GET exit" do before do Question.destroy_all FactoryGirl.create(:question, name: "Czy ziemia jest płaska?", value: 2) Answer.create(name: "Tak", correct: false, question_id: 2) Answer.create(name: "Nie", correct: true, question_id: 2) FactoryGirl.create(:question, name: "Jakie programy domyślnie ma Łubuntu?", value: 2, form: 1) Answer.create(name: "Firefox", correct: true, question_id: 3) Answer.create(name: "Google Chrome", correct: false, question_id: 3) Answer.create(name: "LibreOffice Writer", correct: true, question_id: 3) Answer.create(name: "Microsoft Office Word", correct: false, question_id: 3) FactoryGirl.create(:question, name: "Jakiego koloru jest krew ludzka?", form: 2, value: 2) Answer.create(name: "Czerwonego", question_id: 4) Answer.create(name: "Czerwony", question_id: 4) get :start, id: 1 2.times do get :question case session[:current_question_id].to_i when 2 post :answer, answer: { id: '2' } when 3 post :answer, answer: { id: ['3', '', '', ''] } else post :answer, answer: { text: 'czerwony' } end end get :exit, id: 1 end it "ends exam" do expect(UserExam.first.closed).to eq true expect(UserExam.first.result).to be > 1 end end describe 'GET edit' do before do FactoryGirl.create :user_exam Attending.first.update_attribute(:role, 1) FactoryGirl.create(:question, name: "Czy ziemia jest płaska?", value: 2) Answer.create(name: "Tak", correct: false, question_id: 2) Answer.create(name: "Nie", correct: true, question_id: 2) UserAnswer.create(question_id: 1, user_exam_id: 1, answer_id: 1) UserExam.first.close! end it 'renders page' do get :edit, id: 1 expect(response).to have_http_status :success end end describe 'GET correct_answer' do before do Attending.first.update_attribute(:role, 1) FactoryGirl.create :question, form: 2 Answer.create(name: "Czerw", question_id: 2) FactoryGirl.create :user_exam UserAnswer.create(question_id: 2, text: "Foo", user_exam_id: 1) UserExam.first.close! end it 'makes user answer correct' do expect(UserAnswer.first.correct).to be false expect(UserExam.first.result).to eq 0 get :correct_answer, id: 1, user_answer_id: 1 expect(UserAnswer.first.correct).to be true expect(UserExam.first.result).not_to eq 0 expect(response).to redirect_to edit_user_exam_path(1) end end end
class UserSerializer < ActiveModel::Serializer attributes :id, :name, :email, :password, :score has_many :user_events, serializer: UserEventSerializer has_many :events, serializer: EventSerializer end
# frozen_string_literal: true require 'mail' class Inquiry < ApplicationRecord belongs_to :contact, autosave: true belongs_to :property store :message, accessors: %i( headers attachments html text subject ), coder: JSON validates :property, presence: true validates :contact, presence: true before_validation :find_property, :find_contact def from @from = Mail::Address.new(message['from']) end def to @to = Mail::Address.new(message['to']) end def valid_to_address? return if User.where(mail_handle: to.local).exist? errors.add :to, 'is not a registered email address' end def find_property vrbo_id = subject.gsub(/.*#([0-9]+)/, '\1') user = find_user return unless user.present? self.property = Property.joins(:property_externals) .find_by(property_externals: { external_id: vrbo_id, entity: :vrbo }) end def find_user User.find_by(mail_handle: to.local) end def find_contact contact = Contact.find_or_initialize_by(email: from.address.downcase) self.contact = contact.tap do |c| first_name, last_name = from.display_name.split(' ', 2) c.first_name ||= first_name c.last_name ||= last_name end end end
require "minitest/autorun" describe "elm-rails" do before do File.write "/tmp/rails_template.rb", <<-RUBY.strip_heredoc gem "elm-rails", path: ".." file "app/assets/elm/Hello.elm", <<-ELM.strip_heredoc module Hello exposing (..) import Html exposing (text) main = text "Hello, World" ELM file "app/assets/javascripts/application.js", <<-JS.strip_heredoc //= require Hello JS RUBY sh 'rm -rf dummy && rails new dummy\ --template=/tmp/rails_template.rb\ --skip-action-mailer\ --skip-active-record\ --skip-puma\ --skip-action-cable\ --skip-spring\ --skip-listen\ --skip-coffee\ --skip-turbolinks\ --skip-test\ --skip-javascript\ --skip-bundle' end it "compiles elm files" do sh 'cd dummy && bundle exec rake assets:precompile' sh 'cat dummy/public/assets/application-*.js | grep "_elm_lang\$html\$Html\$text(\'Hello, World\')"' end it "respects the ELM_RAILS_DEBUG environment variable" do sh 'cd dummy && export ELM_RAILS_DEBUG="true" && bundle exec rake assets:precompile' sh 'cat dummy/public/assets/application-*.js | grep "_elm_lang$virtual_dom$Native_Debug"' end def sh command assert system(command) end class String def strip_heredoc min = scan(/^[ \t]*(?=\S)/).min indent = min && min.size || 0 gsub(/^[ \t]{#{indent}}/, '') end end end
class RenameTransferBalanceCents < ActiveRecord::Migration[5.2] def change rename_column :transfers, :balance_cents, :amount_cents end end
# frozen_string_literal: true def benchmark(&block) start_time = Time.now results = block.call puts results end_time = Time.now end_time - start_time end long_string = 'apple' * 100_000_000 running_time = benchmark { long_string.reverse } puts "string.reverse took #{running_time} seconds to run"
class Api::V1::KindsController < Api::V1::BaseController def index render json: Kind.all end end
class SadminController < ApplicationController def index render template: "sadmin/index" end end
class Category < ActiveRecord::Base attr_accessor :count has_many :children, class_name: "Category", foreign_key: "parent_id", :dependent => :delete_all belongs_to :parent, class_name: "Category" has_many :articles, :dependent => :delete_all end
class Product < ApplicationRecord validates :category_id, presence: true, numericality: { greater_than_or_equal_to: 5 } belongs_to :category end
module TicTacToeRZ module Core class Player def initialize @will_block = true @can_retry = false end def will_block? @will_block end def can_retry? @can_retry end end end end
#Module for giving a message to the user. Can be called at any point, and the #message will show up. Only shows messages if global variable MESSAGE_ON is true. module Messenger def Messenger.show_message(text) if $MESSAGES_ON system "cls" puts "#{text}" puts "==============================================" puts "Press Enter to return." gets end end def Messenger.show_error(text) show_message("ERROR: #{text}") if $MESSAGES_ON end end
module IdentityCache module ParentModelExpiration # :nodoc: extend ActiveSupport::Concern class << self def add_parent_expiry_hook(cached_association_hash) association_reflection = cached_association_hash[:association_reflection] name = model_basename(association_reflection.class_name) lazy_hooks[name] ||= [] lazy_hooks[name] << cached_association_hash end def install_all_pending_parent_expiry_hooks until lazy_hooks.empty? lazy_hooks.keys.each do |key| lazy_hooks.delete(key).each do |cached_association_hash| install_hook(cached_association_hash) end end end end def install_pending_parent_expiry_hooks(model) name = model_basename(model.name) lazy_hooks.delete(name).try!(:each) do |cached_association_hash| install_hook(cached_association_hash) end end def check_association(cached_association_hash) association_reflection = cached_association_hash[:association_reflection] parent_model = association_reflection.active_record child_model = association_reflection.klass unless child_model < IdentityCache message = "cached association #{parent_model}\##{association_reflection.name} requires" \ " associated class #{child_model} to include IdentityCache" message << " or IdentityCache::WithoutPrimaryIndex" if cached_association_hash[:embed] == true raise UnsupportedAssociationError, message end cached_association_hash[:inverse_name] ||= association_reflection.inverse_of.try!(:name) || parent_model.name.underscore.to_sym unless child_model.reflect_on_association(cached_association_hash[:inverse_name]) raise InverseAssociationError, "Inverse name for association #{parent_model}\##{association_reflection.name} could not be determined. " \ "Please use the :inverse_name option to specify the inverse association name for this cache." end end private def model_basename(name) name.split("::").last end def lazy_hooks @lazy_hooks ||= {} end def install_hook(cached_association_hash) check_association(cached_association_hash) association_reflection = cached_association_hash[:association_reflection] parent_model = association_reflection.active_record child_model = association_reflection.klass parent_expiration_entry = [parent_model, cached_association_hash[:only_on_foreign_key_change]] child_model.parent_expiration_entries[cached_association_hash[:inverse_name]] << parent_expiration_entry end end included do |base| base.class_attribute :parent_expiration_entries base.parent_expiration_entries = Hash.new{ |hash, key| hash[key] = [] } base.after_commit :expire_parent_caches end def expire_parent_caches ParentModelExpiration.install_pending_parent_expiry_hooks(cached_model) parents_to_expire = {} add_parents_to_cache_expiry_set(parents_to_expire) parents_to_expire.each_value do |parent| parent.send(:expire_primary_index) end end def add_parents_to_cache_expiry_set(parents_to_expire) self.class.parent_expiration_entries.each do |association_name, cached_associations| parents_to_expire_on_changes(parents_to_expire, association_name, cached_associations) end end def add_record_to_cache_expiry_set(parents_to_expire, record) key = record.primary_cache_index_key unless parents_to_expire[key] parents_to_expire[key] = record record.add_parents_to_cache_expiry_set(parents_to_expire) end end def parents_to_expire_on_changes(parents_to_expire, association_name, cached_associations) parent_association = self.class.reflect_on_association(association_name) foreign_key = parent_association.association_foreign_key new_parent = send(association_name) old_parent = nil if transaction_changed_attributes[foreign_key].present? begin if parent_association.polymorphic? parent_class_name = transaction_changed_attributes[parent_association.foreign_type] parent_class_name ||= read_attribute(parent_association.foreign_type) klass = parent_class_name.try!(:safe_constantize) else klass = parent_association.klass end old_parent = klass.find(transaction_changed_attributes[foreign_key]) rescue ActiveRecord::RecordNotFound # suppress errors finding the old parent if its been destroyed since it will have expired itself in that case end end cached_associations.each do |parent_class, only_on_foreign_key_change| if new_parent && new_parent.is_a?(parent_class) && should_expire_identity_cache_parent?(foreign_key, only_on_foreign_key_change) add_record_to_cache_expiry_set(parents_to_expire, new_parent) end if old_parent && old_parent.is_a?(parent_class) add_record_to_cache_expiry_set(parents_to_expire, old_parent) end end end def should_expire_identity_cache_parent?(foreign_key, only_on_foreign_key_change) if only_on_foreign_key_change destroyed? || was_new_record? || transaction_changed_attributes[foreign_key].present? else true end end end private_constant :ParentModelExpiration end
Rails.application.routes.draw do resources :orders resources :products devise_for :users root 'home#index' get "/payments/success", to: "payments#success" post "/payments/webhook", to: "payments#webhook" get '*path', to: redirect('/products'), constraints: lambda { |req| req.path.exclude? 'rails/active_storage' } # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html # get '/user' => "products#index", :as => :user_root end
class Post < ApplicationRecord def self.reversed order('created_at DESC') end end
# frozen_string_literal: true FactoryBot.define do factory :transaction do user credit_card store kind factory: :transaction_kind occurred_at { Faker::Date.between(from: 2.days.ago, to: Date.current) } amount { Faker::Number.decimal(l_digits: 3, r_digits: 2) } end end
class Document < Base attr_accessor :reference self.query = <<-EOL PREFIX foaf: <http://xmlns.com/foaf/0.1> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX stories: <http://purl.org/ontology/stories/> PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ho: <http://www.bbc.co.uk/ontologies/health/> CONSTRUCT { ?doc stories:supports ?ref . } WHERE { ?doc stories:supports ?ref . } EOL def self.find_all graph = self.retrieve documents_index_query = RDF::Query.new do |query| query << [:uri, RDF::URI('http://purl.org/ontology/stories/supports'), :efficacy] end documents = [] documents_index_query.execute(graph).each do |document| documents << Document.new(:uri => document.uri) end documents end def self.find(uri) resource = RDF::URI(uri) Rails.logger.info "Finding #{resource}" graph = self.retrieve document_index_query = RDF::Query.new do |query| query << [resource, RDF::URI('http://purl.org/ontology/stories/supports'), :efficacy] end document_index_query.execute(graph).each do |document| return Document.new( :uri => resource ) end return nil end def initialize(params = {}) super [:reference].each do |attr| send("#{attr}=", params[attr]) if params.key?(attr) end end def load graph = Document.retrieve query = RDF::Query.new do |query| query << [resource, RDF::URI('http://purl.org/ontology/stories/supports'), :efficacy] end query.execute(graph).each do |document| end self end end
require 'test_helper' class TeamsEditTest < ActionDispatch::IntegrationTest include Devise::TestHelpers def setup @team = teams(:tsi) @user = users(:johnny) #@request.env["devise.mapping"] = Devise.mappings[:user] end test "unsuccessful edit" do sign_in(@user) get edit_team_path(@team) assert_template 'teams/edit' patch team_path(@team), team: { team_name: "", team_contact_name: "foo@invalid", team_phone_nr: 123, user_id: 0 } assert_template 'teams/edit' end test "successful edit" do sign_in(@user) get edit_team_path(@team) assert_template 'teams/edit' name = "The Champions" contact = "John Doe" phone = 11111111 id = @user.user_id patch team_path(@team), team: { team_name: name, team_contact_name: contact, team_phone_nr: phone, user_id: id } assert_not flash.empty? assert_redirected_to @team @team.reload assert_equal name, @team.team_name assert_equal contact, @team.team_contact_name assert_equal phone, @team.team_phone_nr assert_equal id, @team.user_id end end
class UserMailer < ActionMailer::Base #default from: "drkwright@capp-usa.org" layout "email" def contact_confirmation(contact) @contact = contact mail(:to => contact.email, :from => "website-notifications@capp-usa.org", :subject => "CAPP-USA.org Thank you for joining our mailing list!") end def reminder_email(er, user) end def event_registered_user(event, attendee_event) @event = event @attendee_event = attendee_event mail(:to => attendee_event.email, :from => "drkwright@capp-usa.org", :subject => "You have registered for a CAPP-USA event!") end def event_registered_admin(event, attendee_event, other) @event = event @attendee_event = attendee_event @payment_method = attendee_event.payment_method @other = other admins = User.where("role_list like ?", "%admin%").collect { |u| u.email } mail(:to => admins, :from => "website-notifications@capp-usa.org", :subject => "Someone registered for a CAPP-USA event!") end def event_daily_summary(event, attendees_events) @event = event @attendees_events = attendees_events.sort { |a, b| a.attendee.last_name <=> b.attendee.last_name } @director = @event.director @program_contact = "frederickfak@gmail.com" cc = nil if @director && @director.email != @program_contact cc = @director.email end mail(:to => [@program_contact, "rnalewajek@capp-usa.org"], :from => "website-notifications@capp-usa.org", :cc => cc, :subject => "#{@event.title} - Contact List (Daily Summary)") end def event_reminder_user(event, user) end def welcome_email(user) @user = user mail(:to => user.email, :from => "website-notifications@capp-usa.org", :subject => "Thank you for registering to CAPP-USA.org!") end def bulk_email(sem, to_user) @user = sem.user @to = to_user @subject = sem.subject @header = sem.header @body = sem.body @content_fragments = sem.content_fragments mail(:to => @to, :from => "website-notifications@capp-usa.org", :subject => @subject, :css => :email) end def activate_user(user) @user = user @user.reset_password_token = User.reset_password_token @user.reset_password_sent_at = Time.now @user.save! mail(:to => user.email, :from => "website-notifications@capp-usa.org", :subject => "A CAPP-USA.org Admin has created an account for you") end def upgrade_contact(contact) @contact = contact mail(:to => contact.email, :from => "website-notifications@capp-usa.org", :subject => "You are invited to create a CAPP-USA.org Account.") end def signup_confirm(signup) @signup = signup recipients = ["nancy5638@msn.com", "frederickfak@gmail.com"] mail(:to => recipients, :from => "website-notifications@capp-usa.org", :subject => "#{@signup.name} registered for the 2016 conference") end def signup_user_confirm(signup) @signup = signup mail(:to => @signup.email, :from => "website-notifications@capp-usa.org", :subject => "Confirmation of registration for the 2016 conference") end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'pdf/reader/markup/version' Gem::Specification.new do |spec| spec.name = "pdf-reader-markup" spec.version = PDF::Reader::MarkupPage::VERSION spec.authors = ["Liz Conlan"] spec.email = ["lizconlan@gmail.com"] spec.description = %q{A markup extension for the PDF::Reader library} spec.summary = %q{Adds the option to retrieve text lines marked up with bold and italic tags when parsing PDF pages with PDF::Reader} spec.homepage = "https://github.com/lizconlan/pdf-reader-markup" 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 "pdf-reader", "~> 1.3" spec.add_dependency "nokogiri" spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" spec.add_development_dependency "simplecov" end
# rubocop:disable Style/GlobalVars if ENV["REDIS_URL"] $redis_url = ENV["REDIS_URL"] else host = ENV.fetch('REDIS_1_PORT_6379_TCP_HOST', 'localhost') port = ENV.fetch('REDIS_1_PORT_6379_TCP_PORT', '6379') $redis_url = "redis://#{host}:#{port}" end $redis_namespace = ENV.fetch('REDIS_NAMESPACE', 'default') $redis = Redis::Namespace.new($redis_namespace, redis: Redis.new(url: $redis_url)) # rubocop:enable Style/GlobalVars
class ApplicationController < ActionController::Base include SessionsHelper # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception def bonjour render html: "bonjour bienvenu sur le super serveur" end end def logged_in_user unless logged_in? store_location flash[:danger] = "please login" redirect_to login_url end end
module Features module SessionHelpers def sign_in_to_admin_area(user: create(:admin_user)) visit new_admin_user_session_url fill_in 'admin_user[username]', with: user.username fill_in 'admin_user[password]', with: user.password click_button 'Sign in' end def sign_in_to_registrar_area(user: create(:api_user)) visit new_registrar_user_session_url fill_in 'registrar_user_username', with: user.username fill_in 'registrar_user_password', with: user.plain_text_password click_button 'Login' end def sign_in_to_registrant_area user = create(:registrant_user) sign_in(user, scope: :user) end end end
class ExercisePlanLogSerializer < ActiveModel::Serializer include Pundit attributes :id, :name, :note, :exercise_session_logs, :can_update, :can_delete def exercise_session_logs object.exercise_session_logs.map do |session_log| ExerciseSessionLogSerializer.new(session_log, scope: scope, root: false) end end def can_update policy(object).update? end def can_delete policy(object).destroy? end def pundit_user scope end end
#!/usr/bin/env ruby -U # frozen_string_literal: true require "tty-fzy" require "optparse" OptionParser.new do |opts| opts.on("-l LINES", "--lines=LINES") do |lines| TTY::Fzy.configure do |config| config.lines = lines.to_i end end end.parse! def parse_tag(line) return if line.start_with?("!_TAG_") line.split("\t") end choices = if ARGV[0] `ctags -f - #{ARGV[0]}` else File.read("tags") end.split("\n").map(&method(:parse_tag)).compact.map do |line| search = line[0..1].push(line[2][1..-4]).join("\t") choice = { text: line[0], returns: search } choice[:alt] = line[1] if ARGV[0].nil? choice end TTY::Fzy.new(choices: choices).call
class CreateAccounts < ActiveRecord::Migration[6.0] def change create_table :accounts do |t| t.string :branch, null: false, limit: 4 t.string :account_number, null: false, limit: 5 t.decimal :limit, null: false, default: 0.0 t.timestamp :last_limit_update, null: false t.decimal :balance t.references :user, null: false, foreign_key: true end add_index :accounts, [:branch, :account_number], unique: true end end
class Activity < ActiveRecord::Base attr_accessible :activitable_type, :activitable_id, :date, :action, :description, :kudos_points, :sub_type belongs_to :activitable, :polymorphic => true belongs_to :user #before_save :check_for_limit acts_as_paranoid Max_Activities_Per_Day = 1 module Kudos_Scores Goal_Completed = 100 end scope :custom_activities, proc {|type| where("activitable_type = ?", type)} scope :page_wise, proc {|month_number| where("(updated_at >= '#{month_number.months.ago.to_date.beginning_of_day}' AND updated_at <= '#{(month_number - 1).months.ago.to_date.end_of_day + 1.day}') OR (created_at >= '#{month_number.months.ago.to_date.beginning_of_day}' AND created_at <= '#{(month_number - 1).months.ago.to_date.end_of_day + 1.day}')", month_number)} scope :created_today, proc{|activity| where("sub_type = ? AND DATE(created_at) = DATE(?)", activity.sub_type, Time.now)} scope :non_zero_kudos, where('kudos_points > 0') def set_sub_type @sub_type = nil end def check_for_limit current_user = self.user user_profile = current_user.user_profile if user_profile.present? && user_profile.activities.created_today(self).count >= Max_Activities_Per_Day return false end end def custom_icon_path activitable_type == 'Photo' ? (activitable.image_url(:standard_image)) : (icon_path) end def update_my_activity(activitable, action = nil, description = nil, kp = -1) self.activitable = activitable self.description = description.present? ? (description) : (activitable.description) self.action = action.present? ? (action) : (activitable.action) self.kudos_points = kp != -1 ? (kp) : (activitable.set_kudos_score) self.date = activitable.updated_at if self.save && self.user.present? self.user.kudos_points = (self.user.kudos_points.present? ? (self.user.kudos_points) : (0)) + self.kudos_points self.user.save end end def update_user_profile_activity end end
class AddColumnsToListings < ActiveRecord::Migration[5.2] def change add_column :listings, :essentials, :boolean, null: false, default: false add_column :listings, :wifi, :boolean, null: false, default: false add_column :listings, :shampoo, :boolean, null: false, default: false add_column :listings, :clothing_storage, :boolean, null: false, default: false add_column :listings, :tv, :boolean, null: false, default: false add_column :listings, :heat, :boolean, null: false, default: false add_column :listings, :air_conditioning, :boolean, null: false, default: false add_column :listings, :breakfast_coffee_tea, :boolean, null: false, default: false add_column :listings, :desk, :boolean, null: false, default: false add_column :listings, :fireplace, :boolean, null: false, default: false add_column :listings, :iron, :boolean, null: false, default: false add_column :listings, :hair_dryer, :boolean, null: false, default: false add_column :listings, :pets, :boolean, null: false, default: false add_column :listings, :private_entrance, :boolean, null: false, default: false add_column :listings, :smoke_detector, :boolean, null: false, default: false add_column :listings, :carbon_monoxide_detector, :boolean, null: false, default: false add_column :listings, :first_aid, :boolean, null: false, default: false add_column :listings, :safety_card, :boolean, null: false, default: false add_column :listings, :fire_extinguisher, :boolean, null: false, default: false add_column :listings, :bedroom_lock, :boolean, null: false, default: false end end
require "rails_helper" describe "a user visits a destination show page" do it "a user sees all attributes of a destination show page" do destination = create(:destination) visit destination_path(destination) expect(current_path).to eq("/destinations/#{destination.id}") expect(page).to have_content(destination.city) expect(page).to have_content(destination.state) expect(page).to have_content(destination.longitude) expect(page).to have_content(destination.latitude) expect(page).to have_content(destination.population) end end
# # > vendor/plugins/polydata/lib mmell$ ruby ../test/type_data_test.rb require 'test/unit' require "polydata/type_data.rb" require "polydata/type_segment.rb" class TypeDataTest < Test::Unit::TestCase def test_one_level assert_raise(RuntimeError) { Polydata::TypeData.new } assert_raise(RuntimeError) { Polydata::TypeData.new('') } assert_raise(RuntimeError) { Polydata::TypeData.new({}) } td = Polydata::TypeData.new({:query_path => '+supporter', :data_type => '$value', :relation => '=', :value => '@!72CD'}) assert_equal('+supporter$value=@!72CD', td.encode) assert_equal('+supporter$value=@!72CD', td.encode(0)) assert(td.has_data?) assert_equal('+supporter', td.flat_query_path) assert_equal('$value', td[0].data_type) assert_equal('=', td[0].relation) assert_equal('@!72CD', td[0].value) assert_nil( td[0].instance_id) td[0].instance_id = 2 assert_equal( 2, td[0].instance_id) td[0].instance_id = [2,3] assert_equal( [2,3], td[0].instance_id) td = Polydata::TypeData.new('+supporter/') assert_equal('+supporter', td.encode) assert_equal('+supporter', td.encode(0)) assert_equal("+supporter", td.flat_query_path) assert_nil(td.child_of) td = Polydata::TypeData.new("+supporter/role/#{Polydata::TypeSegment::ParentQueryPath}") assert_equal('+supporter/role/_', td.encode) assert_equal('+supporter', td.encode(0)) assert_equal('+supporter/role', td.encode(1)) assert_equal('+supporter/role/_', td.encode(2)) assert_equal("+supporter", td.flat_query_path(2)) td = Polydata::TypeData.new('+supporter$value=$null') assert_equal('+supporter$value=$null', td.encode) assert_equal('+supporter$value=$null', td.encode(0)) assert(td[0].has_data?) assert_equal(nil, td[0].value) td = Polydata::TypeData.new('+supporter$value=@!72CD') assert(td.has_data?) assert_equal('$value', td[0].data_type) td = Polydata::TypeData.new('+supporter$value=@!72CD/') assert(td.has_data?) assert_equal('$value', td[0].data_type) td = Polydata::TypeData.new('+supporter$value=@!72CD') assert(td[0].has_data?) assert_equal('$value', td[0].data_type) assert_equal('=', td[0].relation) assert_equal('@!72CD', td[0].value) assert_nil( td[0].instance_id) td = Polydata::TypeData.new('+supporter$id>1234') assert(td[0].has_data?) assert_equal('$id', td[0].data_type) assert_equal('>', td[0].relation) assert_equal('1234', td[0].value) td = Polydata::TypeData.new('+supporter$modified>1234') assert_equal('$modified', td[0].data_type) td = Polydata::TypeData.new('+supporter$nada>1234') assert_nil(td[0].data_type) end def test_children td = Polydata::TypeData.new('+supporter$value=@!72CD.1/role') assert_equal('+supporter$value=@!72CD.1/role', td.encode) assert_equal('+supporter$value=@!72CD.1', td.encode(0)) assert_equal('+supporter$value=@!72CD.1/role', td.encode(1)) assert(td.has_data?) assert_equal('+supporter', td.flat_query_path( td.first ) ) assert_equal('$value', td.first.data_type) assert_equal('=', td.first.relation) assert_equal('@!72CD.1', td.first.value) assert(td.child_of, td.inspect) assert_not_nil( td.child_of(td[0]) ) assert_nil( td.child_of(td[1]) ) assert_equal('+supporter/role', td.flat_query_path( td[1] ) ) assert_equal('+supporter/role', td.flat_query_path( td.child_of(td[0]) ) ) assert_equal('+supporter/role', td.flat_query_path( td.last ) ) assert(!td.child_of.has_data?) assert_equal(td.child_of, td.last) td.delete_at(td.last.position) assert_nil(td.child_of) assert_equal('+supporter', td.flat_query_path(td.last)) td = Polydata::TypeData.new('+admin/lllids$value=@llli*area*alaska/_/admins') assert_equal('+admin/lllids$value=@llli*area*alaska/_/admins', td.encode) assert_equal('+admin', td.encode(0)) assert_equal('+admin/lllids$value=@llli*area*alaska', td.encode(1)) assert_equal('+admin/lllids$value=@llli*area*alaska/_', td.encode(2)) assert_equal('+admin/lllids$value=@llli*area*alaska/_/admins', td.encode(3)) assert_equal('+admin', td.flat_query_path(0)) assert_equal('+admin/admins', td.flat_query_path( td.last )) assert_equal('+admin/lllids', td.flat_query_path( td.child_of )) assert(td.child_of) td = Polydata::TypeData.new('+supporter$value=@!72CD/role$value=ActiveMember') assert_equal('+supporter$value=@!72CD/role$value=ActiveMember', td.encode) assert_equal('+supporter$value=@!72CD', td.encode(0)) assert_equal('+supporter$value=@!72CD/role$value=ActiveMember', td.encode(1)) assert(td.has_data?) assert(td.has_data?) assert_equal('+supporter', td.flat_query_path(0)) assert_equal('$value', td[0].data_type) assert_equal('=', td[0].relation) assert_equal('@!72CD', td[0].value) assert(td.child_of) assert(td.child_of.has_data?) assert_equal('+supporter/role', td.flat_query_path(1)) assert_equal('$value', td.child_of.data_type) assert_equal('=', td.child_of.relation) assert_equal('ActiveMember', td.child_of.value) td = Polydata::TypeData.new('+supporter$value=@!72CD/role$value=ActiveMember/foo$value=2') assert_equal('+supporter$value=@!72CD/role$value=ActiveMember/foo$value=2', td.encode) assert(td.has_data?) assert(td.child_of.has_data?) assert(td[2].has_data?) assert_equal('+supporter/role/foo', td.flat_query_path(2)) assert_equal('$value', td[2].data_type) assert_equal('=', td[2].relation) assert_equal('2', td[2].value) assert_equal(td[2], td.last) td = Polydata::TypeData.new('+supporter$value=@!72CD/role$value=ActiveMember/foo$id=2') assert(td[0].has_data?, td.inspect) assert(td.child_of.has_data?) assert(td[2].has_data?) assert(td[2].instance_id) assert_equal('+supporter/role/foo', td.flat_query_path(2)) assert_equal('$id', td[2].data_type) assert_equal('=', td[2].relation) assert_equal('2', td[2].value) td = Polydata::TypeData.new('+supporter/role$value=3/foo') assert(td.child_of.has_data?, td.inspect) assert(!td.last.has_data?, td.inspect) assert(td.child, td.inspect) assert_equal('+supporter/role/foo', td.flat_query_path(2)) assert_equal('+supporter/role/foo', td.flat_query_path(td.last)) assert_equal('$value', td.child_of.data_type) assert_equal('=', td.child_of.relation) assert_equal('3', td.child_of.value) td = Polydata::TypeData.new('+supporter/role/foo$value=2') assert(td.last.has_data?, td.inspect) assert(td[3].nil?) assert_equal('+supporter/role/foo', td.flat_query_path) assert_equal('+supporter', td.flat_query_path(0)) assert_equal('+supporter/role', td.flat_query_path(1)) assert_equal('+supporter/role/foo', td.flat_query_path(2)) assert_equal('$value', td[2].data_type) assert_equal('=', td[2].relation) assert_equal('2', td[2].value) td = Polydata::TypeData.new('+supporter$value=@!72CD/role$value$in[ActiveMember,ActiveLeader]') assert_equal('+supporter$value=@!72CD/role$value$in[ActiveMember,ActiveLeader]', td.encode) assert(td.child_of.has_data?) assert_equal('+supporter/role', td.flat_query_path(1)) assert_equal('$value', td.child_of.data_type) assert_equal('$in', td.child_of.relation) assert_equal('[ActiveMember,ActiveLeader]', td.child_of.value) td = Polydata::TypeData.new( [ { :query_path => '+supporter', :data_type => '$value', :relation => '=', :value => '@!72CD.2' }, { :query_path => 'role', :data_type => '$value', :relation => '$in', :value => '[ActiveMember,ActiveLeader]', } ] ) assert_not_nil(td.child_of) assert(td.child_of.has_data?) assert_equal('+supporter/role', td.flat_query_path(1)) assert_equal('$value', td.child_of.data_type) assert_equal('$in', td.child_of.relation) assert_equal('[ActiveMember,ActiveLeader]', td.child_of.value) td = Polydata::TypeData.new( [ { :query_path => '+supporter', :data_type => '$value', :relation => '=', :value => '@!72CD' }, 'role$value$in[ActiveMember,ActiveLeader]' ] ) assert(td.child_of.has_data?) assert_equal('+supporter/role', td.flat_query_path(1)) assert_equal('$value', td.child_of.data_type) assert_equal('$in', td.child_of.relation) assert_equal('[ActiveMember,ActiveLeader]', td.child_of.value) end def test_parent_flat_query_path td = Polydata::TypeData.new( "+supporter/lllid$value=@llli*mike/#{Polydata::TypeSegment::ParentQueryPath}/lllid" ) assert_equal('+supporter/lllid', td.flat_query_path) assert_equal('+supporter/lllid', td.flat_query_path(1)) assert_equal('+supporter', td.flat_query_path(2)) assert_equal('+supporter/lllid', td.flat_query_path(3)) assert_equal('+supporter/lllid', td.flat_query_path(td.last)) td = Polydata::TypeData.new( "+supporter/role$value=Leder/#{Polydata::TypeSegment::ParentQueryPath}/lllid" ) assert_equal('+supporter/lllid', td.flat_query_path) assert_equal('+supporter', td.flat_query_path(0)) assert_equal('+supporter/role', td.flat_query_path(1)) assert_equal('+supporter', td.flat_query_path(2)) assert_equal('+supporter/lllid', td.flat_query_path(3)) assert_equal('+supporter/lllid', td.flat_query_path(td.last)) td = Polydata::TypeData.new( "+supporter$value=@!72CD/role$value$in[ActiveMember,ActiveLeader]/#{Polydata::TypeSegment::ParentQueryPath}" ) assert(td[2].is_parent_query?) assert_equal(td.flat_query_path, td.flat_query_path(2)) td = Polydata::TypeData.new([ { :query_path => '+supporter', :data_type => '$value', :relation => '=', :value => '@!72CD' }, "role$value$in[ActiveMember,ActiveLeader]/#{Polydata::TypeSegment::ParentQueryPath}" ] ) assert(td[2].is_parent_query?) assert_equal(td.flat_query_path, td.flat_query_path(2)) td = Polydata::TypeData.new( "+supporter$value=@!72CD/role$value$in[ActiveMember,ActiveLeader]/#{Polydata::TypeSegment::ParentQueryPath}/lllid" ) assert(td[2].is_parent_query?, td[2].inspect) assert_equal('+supporter/lllid', td.flat_query_path ) assert_equal('+supporter', td.flat_query_path(0) ) assert_equal('+supporter/role', td.flat_query_path(1) ) assert_equal('+supporter', td.flat_query_path(2) ) assert_equal('+supporter/lllid', td.flat_query_path(3) ) td = Polydata::TypeData.new( "+supporter/foo1/foo2/#{Polydata::TypeSegment::ParentQueryPath}/foo3" ) assert_equal('+supporter/foo1/foo3', td.flat_query_path ) assert_equal('+supporter', td.flat_query_path(0) ) assert_equal('+supporter/foo1', td.flat_query_path(1) ) assert_equal('+supporter/foo1/foo2', td.flat_query_path(2) ) assert_equal('+supporter/foo1', td.flat_query_path(3) ) assert_equal('+supporter/foo1/foo3', td.flat_query_path(4) ) td = Polydata::TypeData.new( "+supporter/foo1/foo2/#{Polydata::TypeSegment::ParentQueryPath}/#{Polydata::TypeSegment::ParentQueryPath}/foo3" ) assert_equal('+supporter/foo3', td.flat_query_path ) assert_equal('+supporter', td.flat_query_path(0) ) assert_equal('+supporter/foo1', td.flat_query_path(1) ) assert_equal('+supporter/foo1/foo2', td.flat_query_path(2) ) assert_equal('+supporter/foo1', td.flat_query_path(3) ) assert_equal('+supporter', td.flat_query_path(4) ) assert_equal('+supporter/foo3', td.flat_query_path(5) ) end def test_merge_parent td = Polydata::TypeData.new( [ { :query_path => '+supporter' }, 'role$value$in[ActiveMember,ActiveLeader]' ] ) assert(td.child_of) assert(td.child_of.has_data?) assert_equal('+supporter/role', td.flat_query_path(1)) assert_equal('$value', td.child_of.data_type) assert_equal('$in', td.child_of.relation) assert_equal('[ActiveMember,ActiveLeader]', td.child_of.value) td = Polydata::TypeData.new( [ '+supporter', "role$value$in[ActiveMember,ActiveLeader]/#{Polydata::TypeSegment::ParentQueryPath}" ] ) assert(!td[0].has_data?) assert(td.child_of.has_data?) assert_equal('+supporter/role', td.flat_query_path(1)) assert_equal('$value', td.child_of.data_type) assert_equal('$in', td.child_of.relation) assert_equal('[ActiveMember,ActiveLeader]', td.child_of.value) assert_equal("+supporter", td.flat_query_path(2)) end def test_array td = Polydata::TypeData.new( '+supporter$id$in[123456]' ) assert_nil(td[0].instance_id) assert_equal('$id', td[0].data_type) assert_equal('$in', td[0].relation) assert_equal('[123456]', td[0].value) assert_equal('+supporter$id$in[123456]', td.to_s) td[0].instance_id = "12" assert_equal('12', td[0].value) assert_equal('+supporter$id=12', td.to_s) end end # /class TypeDataTest
class CreateUsersettings < ActiveRecord::Migration def change create_table :usersettings do |t| t.integer :userstride t.integer :strideunit, :default => 1 t.integer :distanceunit, :default => 1 t.integer :user_id t.timestamps end add_index :usersettings, :user_id end end
require 'spec_helper' describe Jobs do it 'has a version number' do expect(Jobs::VERSION).not_to be nil end context 'instance methods' do describe 'Jobs#order' do # Given you’re passed an empty string (no jobs), the result should be an empty sequence. it 'should pass example 1' do job_structure = '' expected_output = '' j = Jobs.new job_structure expect(j.to_s).to eq expected_output end # Given the following job structure: # a => # The result should be a sequence consisting of a single job a. it 'should pass example 2' do job_structure = { a: nil } expected_output = 'a' j = Jobs.new job_structure expect(j.to_s).to eq expected_output end # Given the following job structure: # a => # b => # c => # The result should be a sequence containing all three jobs abc in no significant order. it 'should pass example 3' do job_structure = { a: nil, b: nil, c: nil } expected_output = 'abc' j = Jobs.new job_structure expect(j.to_s).to eq expected_output end # Given the following job structure: # a => # b => c # c => # The result should be a sequence that positions c before b, containing all three jobs abc. it 'should pass example 4' do job_structure = { a: nil, b: :c, c: nil } expected_output = 'acb' j = Jobs.new job_structure expect(j.to_s).to eq expected_output end # Given the following job structure: # a => # b => c # c => f # d => a # e => b # f => # The result should be a sequence that positions f before c, c before b, b before e and a before d containing # all six jobs abcdef. it 'should pass example 5' do job_structure = { a: nil, b: :c, c: :f, d: :a, e: :b, f: nil } expected_output = 'afcbde' j = Jobs.new job_structure expect(j.to_s).to eq expected_output end # Given the following job structure: # a => # b => # c => c # The result should be an error stating that jobs can’t depend on themselves. it 'should pass example 6' do job_structure = { a: nil, b: nil, c: :c } expect { Jobs.new job_structure }.to raise_error(Jobs::DependencyError, "Jobs can't depend on themselves") end # Given the following job structure: # a => # b => c # c => f # d => a # e => # f => b # The result should be an error stating that jobs can’t have circular dependencies. it 'should pass example 7' do job_structure = { a: nil, b: :c, c: :f, d: :a, e: nil, f: :b } expect { Jobs.new job_structure }.to raise_error(Jobs::CircularDependencyError, "Jobs can't have circular dependencies") end end end end
class Web::RemindPasswordsController < Web::ApplicationController def new @user = User.new end def create @user = User.find_by_email(params[:user][:email]) if @user && @user.active? token = @user.build_auth_token token.save! UserMailer.remind_password(@user, token).deliver flash_success redirect_to root_path else @user = User.new params[:user] flash_error render :new end end end
json.array!(@docentes) do |docente| json.extract! docente, :id, :cedula, :nombre, :apellido, :telefono, :email, :area, :titulos, :cargo, :colegio_id json.url docente_url(docente, format: :json) end
require 'rails_helper' require 'factory_girl_rails' describe User do let(:user){ FactoryGirl.create(:user) } it "has a valid FACTORY" do expect(FactoryGirl.create(:user)).to be_valid end it "should have an email address" do #when left blank, this tests for truthiness expect(user.email).to be end it "should have a valid email address" do expect(user.email).to match(/^\w+.\w+@\w+.\w+$/) end it 'should be able to create snippets' do expect(user.snippets).to be end it 'should be able to create stories' do expect(user.stories).to be end it 'should be able to vote' do expect(user.votes).to be end end
require File.join(File.dirname(__FILE__), '../test_helper') class Overflowable < ActiveRecord::Base acts_as_overflowable :overflow_column => :overflowable_text, :overflow_limit => 50, :overflow_indicator => :has_overflow, :overflow_table => :overflow end class Overflow < ActiveRecord::Base end HUNDRED_CHARS = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" HUNDRED_LETTERS = "qwertyuiopasdfghjklzxcvbnqwertyuiopasdfghjklzxcvbnqwertyuiopasdfghjklzxcvbnqwertyuiopasdfghjklzxcvbn" FORTY_CHARS = "0123456789012345678901234567890123456789" class ActsAsOverflowableTest < Test::Unit::TestCase include ActiveRecordTestHelper def setup ar_setup() ActiveRecord::Schema.define(:version => 1) do create_table :overflowables do |t| t.boolean :has_overflow t.string :overflowable_text t.timestamps end create_table :overflows do |t| t.integer :overflowable_id t.string :overflowable_type t.string :overflow t.timestamps end end end def teardown ar_teardown() end def test_that_overflowable_options_are_processed_correctly overflowable = Overflowable.new(:overflowable_text => HUNDRED_CHARS) assert_equal "overflowable_text", overflowable.overflow_column assert_equal "50", overflowable.overflow_limit assert_equal "has_overflow", overflowable.overflow_indicator assert_equal "overflow", overflowable.overflow_table end def test_that_content_not_needing_truncation_is_saved_only_in_overflowable_table overflowable = Overflowable.create!(:overflowable_text => FORTY_CHARS) assert_not_nil overflowable.id assert !overflowable.has_overflow assert_nil overflowable.overflow assert_equal overflowable.overflowable_text, FORTY_CHARS end def test_that_truncated_overflow_field_is_saved_in_the_overflow_table overflowable = Overflowable.create!(:overflowable_text => HUNDRED_CHARS) assert_not_nil overflowable.id assert overflowable.has_overflow assert_equal overflowable.overflow.overflow, HUNDRED_CHARS assert_equal overflowable.overflowable_text_with_overflow, HUNDRED_CHARS end def test_that_overflow_is_updated_when_original_content_id_updated overflowable = Overflowable.create!(:overflowable_text => HUNDRED_CHARS) assert_equal overflowable.overflowable_text_with_overflow, HUNDRED_CHARS overflowable.overflowable_text = HUNDRED_LETTERS overflowable.save overflowable.save assert_equal overflowable.overflowable_text_with_overflow, HUNDRED_LETTERS assert_equal 100, overflowable.overflowable_text_with_overflow.length end def test_that_overflow_is_erased_when_size_of_overflowable_text_field_becomes_less_than_limit overflowable = Overflowable.create!(:overflowable_text => HUNDRED_CHARS) assert_equal overflowable.overflowable_text_with_overflow, HUNDRED_CHARS overflowable.overflowable_text = FORTY_CHARS overflowable.save assert_equal overflowable.overflowable_text, FORTY_CHARS assert_equal 40, overflowable.overflowable_text.length assert_equal "", Overflow.find(:all).last.overflow end def test_that_short_field_id_updated_to_longer_value overflowable = Overflowable.create!(:overflowable_text => FORTY_CHARS) assert_equal overflowable.overflowable_text, FORTY_CHARS overflowable.overflowable_text = HUNDRED_CHARS overflowable.save assert_equal HUNDRED_CHARS[0..49], overflowable.overflowable_text assert_equal HUNDRED_CHARS, overflowable.overflowable_text_with_overflow end end
class AddTemplateResourceToEmailTemplates < ActiveRecord::Migration def change add_column :email_templates, :template_resource, :string, :default => "Appointment" add_index :email_templates, :template_resource end end
require 'spec_helper' describe JobTemplate do it 'has many steps' do expect(subject).to have_many(:steps) end it 'responds to .cluster_job_templates' do expect(described_class.respond_to?(:cluster_job_templates)).to be_truthy end it 'responds to #environment' do expect(subject.respond_to?(:environment)).to be_truthy end it 'responds to #vendor' do expect(subject.respond_to?(:vendor)).to be_truthy end it 'responds to #adapter' do expect(subject.respond_to?(:adapter)).to be_truthy end let(:step_a) { JobTemplateStep.create(order: 1) } let(:step_b) { JobTemplateStep.create(order: 2) } describe '#steps' do let(:steps) { [step_b, step_a] } # out of order subject { described_class.create(steps: steps) } it 'returns job steps in order' do subject.reload expect(subject.steps).to match_array([step_b, step_a]) expect(subject.steps.first).to eq step_a expect(subject.steps.second).to eq step_b end end describe '.default_type' do it 'is the cluster type' do expect(described_class.default_type).to eq 'ClusterJobTemplate' end end describe '.load_templates' do let(:child) { double(:child, read: '') } let(:pathname) { double(:pathname) } before do allow(pathname).to receive(:each_child).and_yield(child) end it 'invokes the JobTemplateBuilder' do expect(JobTemplateBuilder).to receive(:create).once described_class.load_templates(pathname) end end describe '#override' do let(:job_template) do JobTemplate.create('environment' => [{ 'variable' => 'foo', 'value' => 'bar' }]) end let(:other_template) do JobTemplate.create('environment' => [{ 'variable' => 'foo', 'value' => 'baz' }, { 'variable' => 'foo2', 'value' => 'quux' }]) end it 'replaces existing environment variables with those in the other template' do job_template.override(other_template) expect(job_template.environment).to include('variable' => 'foo', 'value' => 'baz') end it 'adds new environment variables from the other template to the existing template' do job_template.override(other_template) expect(job_template.environment).to include('variable' => 'foo2', 'value' => 'quux') end end end
# frozen_string_literal: true # == Schema Information # # Table name: tasks # # id :bigint not null, primary key # comments_count :integer default(0) # discarded_at :datetime # position :integer # priority :string # slug :string # story_points :integer # title :string default(""), not null # created_at :datetime not null # updated_at :datetime not null # assignee_id :integer # label_id :bigint not null # reporter_id :integer # # Indexes # # index_tasks_on_assignee_id (assignee_id) # index_tasks_on_discarded_at (discarded_at) # index_tasks_on_label_id (label_id) # index_tasks_on_reporter_id (reporter_id) # index_tasks_on_slug (slug) # # Foreign Keys # # fk_rails_... (label_id => labels.id) # class Task < ApplicationRecord extend FriendlyId include Discard::Model friendly_id :uuid, use: :slugged acts_as_list scope: :label has_rich_text :description belongs_to :label belongs_to :reporter, class_name: 'User' belongs_to :assignee, class_name: 'User', optional: true has_many :comments, -> { order(created_at: :desc) }, inverse_of: :task, dependent: :destroy validates :title, presence: true, length: { minimum: 2, maximum: 50 } validate :description? enum priority: { trivial: 'trivial', minor: 'minor', major: 'major', blocker: 'blocker' } private def description? return if description&.body&.present? errors.add(:description, "can't be blank") end def uuid return SecureRandom.uuid unless label.labelable.class.name == 'Project' "#{label.labelable.name[0..2]}-#{SecureRandom.hex(4)}" end end